babylon.no-module.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288
  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. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * 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)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * 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)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * 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)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * 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)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * 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)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * 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)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * 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)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * 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)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * 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)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * 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)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * 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)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * 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)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. var KeyboardEventTypes = /** @class */ (function () {
  1242. function KeyboardEventTypes() {
  1243. }
  1244. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1245. get: function () {
  1246. return KeyboardEventTypes._KEYDOWN;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1252. get: function () {
  1253. return KeyboardEventTypes._KEYUP;
  1254. },
  1255. enumerable: true,
  1256. configurable: true
  1257. });
  1258. KeyboardEventTypes._KEYDOWN = 0x01;
  1259. KeyboardEventTypes._KEYUP = 0x02;
  1260. return KeyboardEventTypes;
  1261. }());
  1262. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. function KeyboardInfo(type, event) {
  1265. this.type = type;
  1266. this.event = event;
  1267. }
  1268. return KeyboardInfo;
  1269. }());
  1270. BABYLON.KeyboardInfo = KeyboardInfo;
  1271. /**
  1272. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1273. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1274. */
  1275. var KeyboardInfoPre = /** @class */ (function (_super) {
  1276. __extends(KeyboardInfoPre, _super);
  1277. function KeyboardInfoPre(type, event) {
  1278. var _this = _super.call(this, type, event) || this;
  1279. _this.skipOnPointerObservable = false;
  1280. return _this;
  1281. }
  1282. return KeyboardInfoPre;
  1283. }(KeyboardInfo));
  1284. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1287. var BABYLON;
  1288. (function (BABYLON) {
  1289. var PointerEventTypes = /** @class */ (function () {
  1290. function PointerEventTypes() {
  1291. }
  1292. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1293. get: function () {
  1294. return PointerEventTypes._POINTERDOWN;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1300. get: function () {
  1301. return PointerEventTypes._POINTERUP;
  1302. },
  1303. enumerable: true,
  1304. configurable: true
  1305. });
  1306. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1307. get: function () {
  1308. return PointerEventTypes._POINTERMOVE;
  1309. },
  1310. enumerable: true,
  1311. configurable: true
  1312. });
  1313. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1314. get: function () {
  1315. return PointerEventTypes._POINTERWHEEL;
  1316. },
  1317. enumerable: true,
  1318. configurable: true
  1319. });
  1320. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1321. get: function () {
  1322. return PointerEventTypes._POINTERPICK;
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1328. get: function () {
  1329. return PointerEventTypes._POINTERTAP;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1335. get: function () {
  1336. return PointerEventTypes._POINTERDOUBLETAP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. PointerEventTypes._POINTERDOWN = 0x01;
  1342. PointerEventTypes._POINTERUP = 0x02;
  1343. PointerEventTypes._POINTERMOVE = 0x04;
  1344. PointerEventTypes._POINTERWHEEL = 0x08;
  1345. PointerEventTypes._POINTERPICK = 0x10;
  1346. PointerEventTypes._POINTERTAP = 0x20;
  1347. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1348. return PointerEventTypes;
  1349. }());
  1350. BABYLON.PointerEventTypes = PointerEventTypes;
  1351. var PointerInfoBase = /** @class */ (function () {
  1352. function PointerInfoBase(type, event) {
  1353. this.type = type;
  1354. this.event = event;
  1355. }
  1356. return PointerInfoBase;
  1357. }());
  1358. BABYLON.PointerInfoBase = PointerInfoBase;
  1359. /**
  1360. * This class is used to store pointer related info for the onPrePointerObservable event.
  1361. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1362. */
  1363. var PointerInfoPre = /** @class */ (function (_super) {
  1364. __extends(PointerInfoPre, _super);
  1365. function PointerInfoPre(type, event, localX, localY) {
  1366. var _this = _super.call(this, type, event) || this;
  1367. /**
  1368. * Ray from a pointer if availible (eg. 6dof controller)
  1369. */
  1370. _this.ray = null;
  1371. _this.skipOnPointerObservable = false;
  1372. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1373. return _this;
  1374. }
  1375. return PointerInfoPre;
  1376. }(PointerInfoBase));
  1377. BABYLON.PointerInfoPre = PointerInfoPre;
  1378. /**
  1379. * This type contains all the data related to a pointer event in Babylon.js.
  1380. * 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.
  1381. */
  1382. var PointerInfo = /** @class */ (function (_super) {
  1383. __extends(PointerInfo, _super);
  1384. function PointerInfo(type, event, pickInfo) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.pickInfo = pickInfo;
  1387. return _this;
  1388. }
  1389. return PointerInfo;
  1390. }(PointerInfoBase));
  1391. BABYLON.PointerInfo = PointerInfo;
  1392. })(BABYLON || (BABYLON = {}));
  1393. //# sourceMappingURL=babylon.pointerEvents.js.map
  1394. var BABYLON;
  1395. (function (BABYLON) {
  1396. BABYLON.ToGammaSpace = 1 / 2.2;
  1397. BABYLON.ToLinearSpace = 2.2;
  1398. BABYLON.Epsilon = 0.001;
  1399. /**
  1400. * Class used to hold a RBG color
  1401. */
  1402. var Color3 = /** @class */ (function () {
  1403. /**
  1404. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1405. * @param r defines the red component (between 0 and 1, default is 0)
  1406. * @param g defines the green component (between 0 and 1, default is 0)
  1407. * @param b defines the blue component (between 0 and 1, default is 0)
  1408. */
  1409. function Color3(
  1410. /**
  1411. * Defines the red component (between 0 and 1, default is 0)
  1412. */
  1413. r,
  1414. /**
  1415. * Defines the green component (between 0 and 1, default is 0)
  1416. */
  1417. g,
  1418. /**
  1419. * Defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. b) {
  1422. if (r === void 0) { r = 0; }
  1423. if (g === void 0) { g = 0; }
  1424. if (b === void 0) { b = 0; }
  1425. this.r = r;
  1426. this.g = g;
  1427. this.b = b;
  1428. }
  1429. /**
  1430. * Creates a string with the Color3 current values
  1431. * @returns the string representation of the Color3 object
  1432. */
  1433. Color3.prototype.toString = function () {
  1434. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1435. };
  1436. /**
  1437. * Returns the string "Color3"
  1438. * @returns "Color3"
  1439. */
  1440. Color3.prototype.getClassName = function () {
  1441. return "Color3";
  1442. };
  1443. /**
  1444. * Compute the Color3 hash code
  1445. * @returns an unique number that can be used to hash Color3 objects
  1446. */
  1447. Color3.prototype.getHashCode = function () {
  1448. var hash = this.r || 0;
  1449. hash = (hash * 397) ^ (this.g || 0);
  1450. hash = (hash * 397) ^ (this.b || 0);
  1451. return hash;
  1452. };
  1453. // Operators
  1454. /**
  1455. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1456. * @param array defines the array where to store the r,g,b components
  1457. * @param index defines an optional index in the target array to define where to start storing values
  1458. * @returns the current Color3 object
  1459. */
  1460. Color3.prototype.toArray = function (array, index) {
  1461. if (index === undefined) {
  1462. index = 0;
  1463. }
  1464. array[index] = this.r;
  1465. array[index + 1] = this.g;
  1466. array[index + 2] = this.b;
  1467. return this;
  1468. };
  1469. /**
  1470. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1471. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1472. * @returns a new {BABYLON.Color4} object
  1473. */
  1474. Color3.prototype.toColor4 = function (alpha) {
  1475. if (alpha === void 0) { alpha = 1; }
  1476. return new Color4(this.r, this.g, this.b, alpha);
  1477. };
  1478. /**
  1479. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1480. * @returns the new array
  1481. */
  1482. Color3.prototype.asArray = function () {
  1483. var result = new Array();
  1484. this.toArray(result, 0);
  1485. return result;
  1486. };
  1487. /**
  1488. * Returns the luminance value
  1489. * @returns a float value
  1490. */
  1491. Color3.prototype.toLuminance = function () {
  1492. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1493. };
  1494. /**
  1495. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1496. * @param otherColor defines the second operand
  1497. * @returns the new Color3 object
  1498. */
  1499. Color3.prototype.multiply = function (otherColor) {
  1500. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1501. };
  1502. /**
  1503. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1504. * @param otherColor defines the second operand
  1505. * @param result defines the Color3 object where to store the result
  1506. * @returns the current Color3
  1507. */
  1508. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1509. result.r = this.r * otherColor.r;
  1510. result.g = this.g * otherColor.g;
  1511. result.b = this.b * otherColor.b;
  1512. return this;
  1513. };
  1514. /**
  1515. * Determines equality between Color3 objects
  1516. * @param otherColor defines the second operand
  1517. * @returns true if the rgb values are equal to the given ones
  1518. */
  1519. Color3.prototype.equals = function (otherColor) {
  1520. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1521. };
  1522. /**
  1523. * Determines equality between the current Color3 object and a set of r,b,g values
  1524. * @param r defines the red component to check
  1525. * @param g defines the green component to check
  1526. * @param b defines the blue component to check
  1527. * @returns true if the rgb values are equal to the given ones
  1528. */
  1529. Color3.prototype.equalsFloats = function (r, g, b) {
  1530. return this.r === r && this.g === g && this.b === b;
  1531. };
  1532. /**
  1533. * Multiplies in place each rgb value by scale
  1534. * @param scale defines the scaling factor
  1535. * @returns the updated Color3
  1536. */
  1537. Color3.prototype.scale = function (scale) {
  1538. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1539. };
  1540. /**
  1541. * Multiplies the rgb values by scale and stores the result into "result"
  1542. * @param scale defines the scaling factor
  1543. * @param result defines the Color3 object where to store the result
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.scaleToRef = function (scale, result) {
  1547. result.r = this.r * scale;
  1548. result.g = this.g * scale;
  1549. result.b = this.b * scale;
  1550. return this;
  1551. };
  1552. /**
  1553. * Scale the current Color3 values by a factor and add the result to a given Color3
  1554. * @param scale defines the scale factor
  1555. * @param result defines color to store the result into
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1559. result.r += this.r * scale;
  1560. result.g += this.g * scale;
  1561. result.b += this.b * scale;
  1562. return this;
  1563. };
  1564. /**
  1565. * Clamps the rgb values by the min and max values and stores the result into "result"
  1566. * @param min defines minimum clamping value (default is 0)
  1567. * @param max defines maximum clamping value (default is 1)
  1568. * @param result defines color to store the result into
  1569. * @returns the original Color3
  1570. */
  1571. Color3.prototype.clampToRef = function (min, max, result) {
  1572. if (min === void 0) { min = 0; }
  1573. if (max === void 0) { max = 1; }
  1574. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1575. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1576. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1577. return this;
  1578. };
  1579. /**
  1580. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1581. * @param otherColor defines the second operand
  1582. * @returns the new Color3
  1583. */
  1584. Color3.prototype.add = function (otherColor) {
  1585. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1586. };
  1587. /**
  1588. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1589. * @param otherColor defines the second operand
  1590. * @param result defines Color3 object to store the result into
  1591. * @returns the unmodified current Color3
  1592. */
  1593. Color3.prototype.addToRef = function (otherColor, result) {
  1594. result.r = this.r + otherColor.r;
  1595. result.g = this.g + otherColor.g;
  1596. result.b = this.b + otherColor.b;
  1597. return this;
  1598. };
  1599. /**
  1600. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1601. * @param otherColor defines the second operand
  1602. * @returns the new Color3
  1603. */
  1604. Color3.prototype.subtract = function (otherColor) {
  1605. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1606. };
  1607. /**
  1608. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1609. * @param otherColor defines the second operand
  1610. * @param result defines Color3 object to store the result into
  1611. * @returns the unmodified current Color3
  1612. */
  1613. Color3.prototype.subtractToRef = function (otherColor, result) {
  1614. result.r = this.r - otherColor.r;
  1615. result.g = this.g - otherColor.g;
  1616. result.b = this.b - otherColor.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Copy the current object
  1621. * @returns a new Color3 copied the current one
  1622. */
  1623. Color3.prototype.clone = function () {
  1624. return new Color3(this.r, this.g, this.b);
  1625. };
  1626. /**
  1627. * Copies the rgb values from the source in the current Color3
  1628. * @param source defines the source Color3 object
  1629. * @returns the updated Color3 object
  1630. */
  1631. Color3.prototype.copyFrom = function (source) {
  1632. this.r = source.r;
  1633. this.g = source.g;
  1634. this.b = source.b;
  1635. return this;
  1636. };
  1637. /**
  1638. * Updates the Color3 rgb values from the given floats
  1639. * @param r defines the red component to read from
  1640. * @param g defines the green component to read from
  1641. * @param b defines the blue component to read from
  1642. * @returns the current Color3 object
  1643. */
  1644. Color3.prototype.copyFromFloats = function (r, g, b) {
  1645. this.r = r;
  1646. this.g = g;
  1647. this.b = b;
  1648. return this;
  1649. };
  1650. /**
  1651. * Updates the Color3 rgb values from the given floats
  1652. * @param r defines the red component to read from
  1653. * @param g defines the green component to read from
  1654. * @param b defines the blue component to read from
  1655. * @returns the current Color3 object
  1656. */
  1657. Color3.prototype.set = function (r, g, b) {
  1658. return this.copyFromFloats(r, g, b);
  1659. };
  1660. /**
  1661. * Compute the Color3 hexadecimal code as a string
  1662. * @returns a string containing the hexadecimal representation of the Color3 object
  1663. */
  1664. Color3.prototype.toHexString = function () {
  1665. var intR = (this.r * 255) | 0;
  1666. var intG = (this.g * 255) | 0;
  1667. var intB = (this.b * 255) | 0;
  1668. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1669. };
  1670. /**
  1671. * Computes a new Color3 converted from the current one to linear space
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.prototype.toLinearSpace = function () {
  1675. var convertedColor = new Color3();
  1676. this.toLinearSpaceToRef(convertedColor);
  1677. return convertedColor;
  1678. };
  1679. /**
  1680. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1681. * @param convertedColor defines the Color3 object where to store the linear space version
  1682. * @returns the unmodified Color3
  1683. */
  1684. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1685. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1686. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1687. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1688. return this;
  1689. };
  1690. /**
  1691. * Computes a new Color3 converted from the current one to gamma space
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.prototype.toGammaSpace = function () {
  1695. var convertedColor = new Color3();
  1696. this.toGammaSpaceToRef(convertedColor);
  1697. return convertedColor;
  1698. };
  1699. /**
  1700. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1701. * @param convertedColor defines the Color3 object where to store the gamma space version
  1702. * @returns the unmodified Color3
  1703. */
  1704. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1705. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1706. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1707. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1708. return this;
  1709. };
  1710. // Statics
  1711. /**
  1712. * Creates a new Color3 from the string containing valid hexadecimal values
  1713. * @param hex defines a string containing valid hexadecimal values
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromHexString = function (hex) {
  1717. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1718. return new Color3(0, 0, 0);
  1719. }
  1720. var r = parseInt(hex.substring(1, 3), 16);
  1721. var g = parseInt(hex.substring(3, 5), 16);
  1722. var b = parseInt(hex.substring(5, 7), 16);
  1723. return Color3.FromInts(r, g, b);
  1724. };
  1725. /**
  1726. * Creates a new Vector3 from the starting index of the given array
  1727. * @param array defines the source array
  1728. * @param offset defines an offset in the source array
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.FromArray = function (array, offset) {
  1732. if (offset === void 0) { offset = 0; }
  1733. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1734. };
  1735. /**
  1736. * Creates a new Color3 from integer values (< 256)
  1737. * @param r defines the red component to read from (value between 0 and 255)
  1738. * @param g defines the green component to read from (value between 0 and 255)
  1739. * @param b defines the blue component to read from (value between 0 and 255)
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.FromInts = function (r, g, b) {
  1743. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1744. };
  1745. /**
  1746. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1747. * @param start defines the start Color3 value
  1748. * @param end defines the end Color3 value
  1749. * @param amount defines the gradient value between start and end
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.Lerp = function (start, end, amount) {
  1753. var result = new Color3(0.0, 0.0, 0.0);
  1754. Color3.LerpToRef(start, end, amount, result);
  1755. return result;
  1756. };
  1757. /**
  1758. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1759. * @param left defines the start value
  1760. * @param right defines the end value
  1761. * @param amount defines the gradient factor
  1762. * @param result defines the Color3 object where to store the result
  1763. */
  1764. Color3.LerpToRef = function (left, right, amount, result) {
  1765. result.r = left.r + ((right.r - left.r) * amount);
  1766. result.g = left.g + ((right.g - left.g) * amount);
  1767. result.b = left.b + ((right.b - left.b) * amount);
  1768. };
  1769. /**
  1770. * Returns a Color3 value containing a red color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Red = function () { return new Color3(1, 0, 0); };
  1774. /**
  1775. * Returns a Color3 value containing a green color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Green = function () { return new Color3(0, 1, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a blue color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a black color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Black = function () { return new Color3(0, 0, 0); };
  1789. /**
  1790. * Returns a Color3 value containing a white color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.White = function () { return new Color3(1, 1, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a purple color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1799. /**
  1800. * Returns a Color3 value containing a magenta color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1804. /**
  1805. * Returns a Color3 value containing a yellow color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1809. /**
  1810. * Returns a Color3 value containing a gray color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1814. /**
  1815. * Returns a Color3 value containing a teal color
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1819. /**
  1820. * Returns a Color3 value containing a random color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1824. return Color3;
  1825. }());
  1826. BABYLON.Color3 = Color3;
  1827. /**
  1828. * Class used to hold a RBGA color
  1829. */
  1830. var Color4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1833. * @param r defines the red component (between 0 and 1, default is 0)
  1834. * @param g defines the green component (between 0 and 1, default is 0)
  1835. * @param b defines the blue component (between 0 and 1, default is 0)
  1836. * @param a defines the alpha component (between 0 and 1, default is 1)
  1837. */
  1838. function Color4(
  1839. /**
  1840. * Defines the red component (between 0 and 1, default is 0)
  1841. */
  1842. r,
  1843. /**
  1844. * Defines the green component (between 0 and 1, default is 0)
  1845. */
  1846. g,
  1847. /**
  1848. * Defines the blue component (between 0 and 1, default is 0)
  1849. */
  1850. b,
  1851. /**
  1852. * Defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. a) {
  1855. if (r === void 0) { r = 0; }
  1856. if (g === void 0) { g = 0; }
  1857. if (b === void 0) { b = 0; }
  1858. if (a === void 0) { a = 1; }
  1859. this.r = r;
  1860. this.g = g;
  1861. this.b = b;
  1862. this.a = a;
  1863. }
  1864. // Operators
  1865. /**
  1866. * Adds in place the given Color4 values to the current Color4 object
  1867. * @param right defines the second operand
  1868. * @returns the current updated Color4 object
  1869. */
  1870. Color4.prototype.addInPlace = function (right) {
  1871. this.r += right.r;
  1872. this.g += right.g;
  1873. this.b += right.b;
  1874. this.a += right.a;
  1875. return this;
  1876. };
  1877. /**
  1878. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1879. * @returns the new array
  1880. */
  1881. Color4.prototype.asArray = function () {
  1882. var result = new Array();
  1883. this.toArray(result, 0);
  1884. return result;
  1885. };
  1886. /**
  1887. * Stores from the starting index in the given array the Color4 successive values
  1888. * @param array defines the array where to store the r,g,b components
  1889. * @param index defines an optional index in the target array to define where to start storing values
  1890. * @returns the current Color4 object
  1891. */
  1892. Color4.prototype.toArray = function (array, index) {
  1893. if (index === undefined) {
  1894. index = 0;
  1895. }
  1896. array[index] = this.r;
  1897. array[index + 1] = this.g;
  1898. array[index + 2] = this.b;
  1899. array[index + 3] = this.a;
  1900. return this;
  1901. };
  1902. /**
  1903. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1904. * @param right defines the second operand
  1905. * @returns a new Color4 object
  1906. */
  1907. Color4.prototype.add = function (right) {
  1908. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1909. };
  1910. /**
  1911. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1912. * @param right defines the second operand
  1913. * @returns a new Color4 object
  1914. */
  1915. Color4.prototype.subtract = function (right) {
  1916. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1917. };
  1918. /**
  1919. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1920. * @param right defines the second operand
  1921. * @param result defines the Color4 object where to store the result
  1922. * @returns the current Color4 object
  1923. */
  1924. Color4.prototype.subtractToRef = function (right, result) {
  1925. result.r = this.r - right.r;
  1926. result.g = this.g - right.g;
  1927. result.b = this.b - right.b;
  1928. result.a = this.a - right.a;
  1929. return this;
  1930. };
  1931. /**
  1932. * Creates a new Color4 with the current Color4 values multiplied by scale
  1933. * @param scale defines the scaling factor to apply
  1934. * @returns a new Color4 object
  1935. */
  1936. Color4.prototype.scale = function (scale) {
  1937. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1938. };
  1939. /**
  1940. * Multiplies the current Color4 values by scale and stores the result in "result"
  1941. * @param scale defines the scaling factor to apply
  1942. * @param result defines the Color4 object where to store the result
  1943. * @returns the current unmodified Color4
  1944. */
  1945. Color4.prototype.scaleToRef = function (scale, result) {
  1946. result.r = this.r * scale;
  1947. result.g = this.g * scale;
  1948. result.b = this.b * scale;
  1949. result.a = this.a * scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Scale the current Color4 values by a factor and add the result to a given Color4
  1954. * @param scale defines the scale factor
  1955. * @param result defines the Color4 object where to store the result
  1956. * @returns the unmodified current Color4
  1957. */
  1958. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1959. result.r += this.r * scale;
  1960. result.g += this.g * scale;
  1961. result.b += this.b * scale;
  1962. result.a += this.a * scale;
  1963. return this;
  1964. };
  1965. /**
  1966. * Clamps the rgb values by the min and max values and stores the result into "result"
  1967. * @param min defines minimum clamping value (default is 0)
  1968. * @param max defines maximum clamping value (default is 1)
  1969. * @param result defines color to store the result into.
  1970. * @returns the cuurent Color4
  1971. */
  1972. Color4.prototype.clampToRef = function (min, max, result) {
  1973. if (min === void 0) { min = 0; }
  1974. if (max === void 0) { max = 1; }
  1975. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1976. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1977. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1978. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1979. return this;
  1980. };
  1981. /**
  1982. * Multipy an Color4 value by another and return a new Color4 object
  1983. * @param color defines the Color4 value to multiply by
  1984. * @returns a new Color4 object
  1985. */
  1986. Color4.prototype.multiply = function (color) {
  1987. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1988. };
  1989. /**
  1990. * Multipy a Color4 value by another and push the result in a reference value
  1991. * @param color defines the Color4 value to multiply by
  1992. * @param result defines the Color4 to fill the result in
  1993. * @returns the result Color4
  1994. */
  1995. Color4.prototype.multiplyToRef = function (color, result) {
  1996. result.r = this.r * color.r;
  1997. result.g = this.g * color.g;
  1998. result.b = this.b * color.b;
  1999. result.a = this.a * color.a;
  2000. return result;
  2001. };
  2002. /**
  2003. * Creates a string with the Color4 current values
  2004. * @returns the string representation of the Color4 object
  2005. */
  2006. Color4.prototype.toString = function () {
  2007. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2008. };
  2009. /**
  2010. * Returns the string "Color4"
  2011. * @returns "Color4"
  2012. */
  2013. Color4.prototype.getClassName = function () {
  2014. return "Color4";
  2015. };
  2016. /**
  2017. * Compute the Color4 hash code
  2018. * @returns an unique number that can be used to hash Color4 objects
  2019. */
  2020. Color4.prototype.getHashCode = function () {
  2021. var hash = this.r || 0;
  2022. hash = (hash * 397) ^ (this.g || 0);
  2023. hash = (hash * 397) ^ (this.b || 0);
  2024. hash = (hash * 397) ^ (this.a || 0);
  2025. return hash;
  2026. };
  2027. /**
  2028. * Creates a new Color4 copied from the current one
  2029. * @returns a new Color4 object
  2030. */
  2031. Color4.prototype.clone = function () {
  2032. return new Color4(this.r, this.g, this.b, this.a);
  2033. };
  2034. /**
  2035. * Copies the given Color4 values into the current one
  2036. * @param source defines the source Color4 object
  2037. * @returns the current updated Color4 object
  2038. */
  2039. Color4.prototype.copyFrom = function (source) {
  2040. this.r = source.r;
  2041. this.g = source.g;
  2042. this.b = source.b;
  2043. this.a = source.a;
  2044. return this;
  2045. };
  2046. /**
  2047. * Copies the given float values into the current one
  2048. * @param r defines the red component to read from
  2049. * @param g defines the green component to read from
  2050. * @param b defines the blue component to read from
  2051. * @param a defines the alpha component to read from
  2052. * @returns the current updated Color4 object
  2053. */
  2054. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2055. this.r = r;
  2056. this.g = g;
  2057. this.b = b;
  2058. this.a = a;
  2059. return this;
  2060. };
  2061. /**
  2062. * Copies the given float values into the current one
  2063. * @param r defines the red component to read from
  2064. * @param g defines the green component to read from
  2065. * @param b defines the blue component to read from
  2066. * @param a defines the alpha component to read from
  2067. * @returns the current updated Color4 object
  2068. */
  2069. Color4.prototype.set = function (r, g, b, a) {
  2070. return this.copyFromFloats(r, g, b, a);
  2071. };
  2072. /**
  2073. * Compute the Color4 hexadecimal code as a string
  2074. * @returns a string containing the hexadecimal representation of the Color4 object
  2075. */
  2076. Color4.prototype.toHexString = function () {
  2077. var intR = (this.r * 255) | 0;
  2078. var intG = (this.g * 255) | 0;
  2079. var intB = (this.b * 255) | 0;
  2080. var intA = (this.a * 255) | 0;
  2081. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2082. };
  2083. /**
  2084. * Computes a new Color4 converted from the current one to linear space
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.prototype.toLinearSpace = function () {
  2088. var convertedColor = new Color4();
  2089. this.toLinearSpaceToRef(convertedColor);
  2090. return convertedColor;
  2091. };
  2092. /**
  2093. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2094. * @param convertedColor defines the Color4 object where to store the linear space version
  2095. * @returns the unmodified Color4
  2096. */
  2097. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2098. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2099. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2100. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2101. convertedColor.a = this.a;
  2102. return this;
  2103. };
  2104. /**
  2105. * Computes a new Color4 converted from the current one to gamma space
  2106. * @returns a new Color4 object
  2107. */
  2108. Color4.prototype.toGammaSpace = function () {
  2109. var convertedColor = new Color4();
  2110. this.toGammaSpaceToRef(convertedColor);
  2111. return convertedColor;
  2112. };
  2113. /**
  2114. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2115. * @param convertedColor defines the Color4 object where to store the gamma space version
  2116. * @returns the unmodified Color4
  2117. */
  2118. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2119. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2120. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2121. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2122. convertedColor.a = this.a;
  2123. return this;
  2124. };
  2125. // Statics
  2126. /**
  2127. * Creates a new Color4 from the string containing valid hexadecimal values
  2128. * @param hex defines a string containing valid hexadecimal values
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.FromHexString = function (hex) {
  2132. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2133. return new Color4(0.0, 0.0, 0.0, 0.0);
  2134. }
  2135. var r = parseInt(hex.substring(1, 3), 16);
  2136. var g = parseInt(hex.substring(3, 5), 16);
  2137. var b = parseInt(hex.substring(5, 7), 16);
  2138. var a = parseInt(hex.substring(7, 9), 16);
  2139. return Color4.FromInts(r, g, b, a);
  2140. };
  2141. /**
  2142. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2143. * @param left defines the start value
  2144. * @param right defines the end value
  2145. * @param amount defines the gradient factor
  2146. * @returns a new Color4 object
  2147. */
  2148. Color4.Lerp = function (left, right, amount) {
  2149. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2150. Color4.LerpToRef(left, right, amount, result);
  2151. return result;
  2152. };
  2153. /**
  2154. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2155. * @param left defines the start value
  2156. * @param right defines the end value
  2157. * @param amount defines the gradient factor
  2158. * @param result defines the Color4 object where to store data
  2159. */
  2160. Color4.LerpToRef = function (left, right, amount, result) {
  2161. result.r = left.r + (right.r - left.r) * amount;
  2162. result.g = left.g + (right.g - left.g) * amount;
  2163. result.b = left.b + (right.b - left.b) * amount;
  2164. result.a = left.a + (right.a - left.a) * amount;
  2165. };
  2166. /**
  2167. * Creates a new Color4 from a Color3 and an alpha value
  2168. * @param color3 defines the source Color3 to read from
  2169. * @param alpha defines the alpha component (1.0 by default)
  2170. * @returns a new Color4 object
  2171. */
  2172. Color4.FromColor3 = function (color3, alpha) {
  2173. if (alpha === void 0) { alpha = 1.0; }
  2174. return new Color4(color3.r, color3.g, color3.b, alpha);
  2175. };
  2176. /**
  2177. * Creates a new Color4 from the starting index element of the given array
  2178. * @param array defines the source array to read from
  2179. * @param offset defines the offset in the source array
  2180. * @returns a new Color4 object
  2181. */
  2182. Color4.FromArray = function (array, offset) {
  2183. if (offset === void 0) { offset = 0; }
  2184. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2185. };
  2186. /**
  2187. * Creates a new Color3 from integer values (< 256)
  2188. * @param r defines the red component to read from (value between 0 and 255)
  2189. * @param g defines the green component to read from (value between 0 and 255)
  2190. * @param b defines the blue component to read from (value between 0 and 255)
  2191. * @param a defines the alpha component to read from (value between 0 and 255)
  2192. * @returns a new Color3 object
  2193. */
  2194. Color4.FromInts = function (r, g, b, a) {
  2195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2196. };
  2197. /**
  2198. * Check the content of a given array and convert it to an array containing RGBA data
  2199. * If the original array was already containing count * 4 values then it is returned directly
  2200. * @param colors defines the array to check
  2201. * @param count defines the number of RGBA data to expect
  2202. * @returns an array containing count * 4 values (RGBA)
  2203. */
  2204. Color4.CheckColors4 = function (colors, count) {
  2205. // Check if color3 was used
  2206. if (colors.length === count * 3) {
  2207. var colors4 = [];
  2208. for (var index = 0; index < colors.length; index += 3) {
  2209. var newIndex = (index / 3) * 4;
  2210. colors4[newIndex] = colors[index];
  2211. colors4[newIndex + 1] = colors[index + 1];
  2212. colors4[newIndex + 2] = colors[index + 2];
  2213. colors4[newIndex + 3] = 1.0;
  2214. }
  2215. return colors4;
  2216. }
  2217. return colors;
  2218. };
  2219. return Color4;
  2220. }());
  2221. BABYLON.Color4 = Color4;
  2222. /**
  2223. * Class representing a vector containing 2 coordinates
  2224. */
  2225. var Vector2 = /** @class */ (function () {
  2226. /**
  2227. * Creates a new Vector2 from the given x and y coordinates
  2228. * @param x defines the first coordinate
  2229. * @param y defines the second coordinate
  2230. */
  2231. function Vector2(
  2232. /** defines the first coordinate */
  2233. x,
  2234. /** defines the second coordinate */
  2235. y) {
  2236. if (x === void 0) { x = 0; }
  2237. if (y === void 0) { y = 0; }
  2238. this.x = x;
  2239. this.y = y;
  2240. }
  2241. /**
  2242. * Gets a string with the Vector2 coordinates
  2243. * @returns a string with the Vector2 coordinates
  2244. */
  2245. Vector2.prototype.toString = function () {
  2246. return "{X: " + this.x + " Y:" + this.y + "}";
  2247. };
  2248. /**
  2249. * Gets class name
  2250. * @returns the string "Vector2"
  2251. */
  2252. Vector2.prototype.getClassName = function () {
  2253. return "Vector2";
  2254. };
  2255. /**
  2256. * Gets current vector hash code
  2257. * @returns the Vector2 hash code as a number
  2258. */
  2259. Vector2.prototype.getHashCode = function () {
  2260. var hash = this.x || 0;
  2261. hash = (hash * 397) ^ (this.y || 0);
  2262. return hash;
  2263. };
  2264. // Operators
  2265. /**
  2266. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2267. * @param array defines the source array
  2268. * @param index defines the offset in source array
  2269. * @returns the current Vector2
  2270. */
  2271. Vector2.prototype.toArray = function (array, index) {
  2272. if (index === void 0) { index = 0; }
  2273. array[index] = this.x;
  2274. array[index + 1] = this.y;
  2275. return this;
  2276. };
  2277. /**
  2278. * Copy the current vector to an array
  2279. * @returns a new array with 2 elements: the Vector2 coordinates.
  2280. */
  2281. Vector2.prototype.asArray = function () {
  2282. var result = new Array();
  2283. this.toArray(result, 0);
  2284. return result;
  2285. };
  2286. /**
  2287. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2288. * @param source defines the source Vector2
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.copyFrom = function (source) {
  2292. this.x = source.x;
  2293. this.y = source.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Sets the Vector2 coordinates with the given floats
  2298. * @param x defines the first coordinate
  2299. * @param y defines the second coordinate
  2300. * @returns the current updated Vector2
  2301. */
  2302. Vector2.prototype.copyFromFloats = function (x, y) {
  2303. this.x = x;
  2304. this.y = y;
  2305. return this;
  2306. };
  2307. /**
  2308. * Sets the Vector2 coordinates with the given floats
  2309. * @param x defines the first coordinate
  2310. * @param y defines the second coordinate
  2311. * @returns the current updated Vector2
  2312. */
  2313. Vector2.prototype.set = function (x, y) {
  2314. return this.copyFromFloats(x, y);
  2315. };
  2316. /**
  2317. * Add another vector with the current one
  2318. * @param otherVector defines the other vector
  2319. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2320. */
  2321. Vector2.prototype.add = function (otherVector) {
  2322. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2323. };
  2324. /**
  2325. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2326. * @param otherVector defines the other vector
  2327. * @param result defines the target vector
  2328. * @returns the unmodified current Vector2
  2329. */
  2330. Vector2.prototype.addToRef = function (otherVector, result) {
  2331. result.x = this.x + otherVector.x;
  2332. result.y = this.y + otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.addInPlace = function (otherVector) {
  2341. this.x += otherVector.x;
  2342. this.y += otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.addVector3 = function (otherVector) {
  2351. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2352. };
  2353. /**
  2354. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2355. * @param otherVector defines the other vector
  2356. * @returns a new Vector2
  2357. */
  2358. Vector2.prototype.subtract = function (otherVector) {
  2359. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2360. };
  2361. /**
  2362. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2363. * @param otherVector defines the other vector
  2364. * @param result defines the target vector
  2365. * @returns the unmodified current Vector2
  2366. */
  2367. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2368. result.x = this.x - otherVector.x;
  2369. result.y = this.y - otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns the current updated Vector2
  2376. */
  2377. Vector2.prototype.subtractInPlace = function (otherVector) {
  2378. this.x -= otherVector.x;
  2379. this.y -= otherVector.y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Multiplies in place the current Vector2 coordinates by the given ones
  2384. * @param otherVector defines the other vector
  2385. * @returns the current updated Vector2
  2386. */
  2387. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2388. this.x *= otherVector.x;
  2389. this.y *= otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2394. * @param otherVector defines the other vector
  2395. * @returns a new Vector2
  2396. */
  2397. Vector2.prototype.multiply = function (otherVector) {
  2398. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2399. };
  2400. /**
  2401. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2402. * @param otherVector defines the other vector
  2403. * @param result defines the target vector
  2404. * @returns the unmodified current Vector2
  2405. */
  2406. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2407. result.x = this.x * otherVector.x;
  2408. result.y = this.y * otherVector.y;
  2409. return this;
  2410. };
  2411. /**
  2412. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2413. * @param x defines the first coordinate
  2414. * @param y defines the second coordinate
  2415. * @returns a new Vector2
  2416. */
  2417. Vector2.prototype.multiplyByFloats = function (x, y) {
  2418. return new Vector2(this.x * x, this.y * y);
  2419. };
  2420. /**
  2421. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.divide = function (otherVector) {
  2426. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2427. };
  2428. /**
  2429. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2430. * @param otherVector defines the other vector
  2431. * @param result defines the target vector
  2432. * @returns the unmodified current Vector2
  2433. */
  2434. Vector2.prototype.divideToRef = function (otherVector, result) {
  2435. result.x = this.x / otherVector.x;
  2436. result.y = this.y / otherVector.y;
  2437. return this;
  2438. };
  2439. /**
  2440. * Divides the current Vector2 coordinates by the given ones
  2441. * @param otherVector defines the other vector
  2442. * @returns the current updated Vector2
  2443. */
  2444. Vector2.prototype.divideInPlace = function (otherVector) {
  2445. return this.divideToRef(otherVector, this);
  2446. };
  2447. /**
  2448. * Gets a new Vector2 with current Vector2 negated coordinates
  2449. * @returns a new Vector2
  2450. */
  2451. Vector2.prototype.negate = function () {
  2452. return new Vector2(-this.x, -this.y);
  2453. };
  2454. /**
  2455. * Multiply the Vector2 coordinates by scale
  2456. * @param scale defines the scaling factor
  2457. * @returns the current updated Vector2
  2458. */
  2459. Vector2.prototype.scaleInPlace = function (scale) {
  2460. this.x *= scale;
  2461. this.y *= scale;
  2462. return this;
  2463. };
  2464. /**
  2465. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2466. * @param scale defines the scaling factor
  2467. * @returns a new Vector2
  2468. */
  2469. Vector2.prototype.scale = function (scale) {
  2470. var result = new Vector2(0, 0);
  2471. this.scaleToRef(scale, result);
  2472. return result;
  2473. };
  2474. /**
  2475. * Scale the current Vector2 values by a factor to a given Vector2
  2476. * @param scale defines the scale factor
  2477. * @param result defines the Vector2 object where to store the result
  2478. * @returns the unmodified current Vector2
  2479. */
  2480. Vector2.prototype.scaleToRef = function (scale, result) {
  2481. result.x = this.x * scale;
  2482. result.y = this.y * scale;
  2483. return this;
  2484. };
  2485. /**
  2486. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2487. * @param scale defines the scale factor
  2488. * @param result defines the Vector2 object where to store the result
  2489. * @returns the unmodified current Vector2
  2490. */
  2491. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2492. result.x += this.x * scale;
  2493. result.y += this.y * scale;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a boolean if two vectors are equals
  2498. * @param otherVector defines the other vector
  2499. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2500. */
  2501. Vector2.prototype.equals = function (otherVector) {
  2502. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2503. };
  2504. /**
  2505. * Gets a boolean if two vectors are equals (using an epsilon value)
  2506. * @param otherVector defines the other vector
  2507. * @param epsilon defines the minimal distance to consider equality
  2508. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2509. */
  2510. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2511. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2512. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2513. };
  2514. /**
  2515. * Gets a new Vector2 from current Vector2 floored values
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.prototype.floor = function () {
  2519. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2520. };
  2521. /**
  2522. * Gets a new Vector2 from current Vector2 floored values
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.fract = function () {
  2526. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2527. };
  2528. // Properties
  2529. /**
  2530. * Gets the length of the vector
  2531. * @returns the vector length (float)
  2532. */
  2533. Vector2.prototype.length = function () {
  2534. return Math.sqrt(this.x * this.x + this.y * this.y);
  2535. };
  2536. /**
  2537. * Gets the vector squared length
  2538. * @returns the vector squared length (float)
  2539. */
  2540. Vector2.prototype.lengthSquared = function () {
  2541. return (this.x * this.x + this.y * this.y);
  2542. };
  2543. // Methods
  2544. /**
  2545. * Normalize the vector
  2546. * @returns the current updated Vector2
  2547. */
  2548. Vector2.prototype.normalize = function () {
  2549. var len = this.length();
  2550. if (len === 0)
  2551. return this;
  2552. var num = 1.0 / len;
  2553. this.x *= num;
  2554. this.y *= num;
  2555. return this;
  2556. };
  2557. /**
  2558. * Gets a new Vector2 copied from the Vector2
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.prototype.clone = function () {
  2562. return new Vector2(this.x, this.y);
  2563. };
  2564. // Statics
  2565. /**
  2566. * Gets a new Vector2(0, 0)
  2567. * @returns a new Vector2
  2568. */
  2569. Vector2.Zero = function () {
  2570. return new Vector2(0, 0);
  2571. };
  2572. /**
  2573. * Gets a new Vector2(1, 1)
  2574. * @returns a new Vector2
  2575. */
  2576. Vector2.One = function () {
  2577. return new Vector2(1, 1);
  2578. };
  2579. /**
  2580. * Gets a new Vector2 set from the given index element of the given array
  2581. * @param array defines the data source
  2582. * @param offset defines the offset in the data source
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.FromArray = function (array, offset) {
  2586. if (offset === void 0) { offset = 0; }
  2587. return new Vector2(array[offset], array[offset + 1]);
  2588. };
  2589. /**
  2590. * Sets "result" from the given index element of the given array
  2591. * @param array defines the data source
  2592. * @param offset defines the offset in the data source
  2593. * @param result defines the target vector
  2594. */
  2595. Vector2.FromArrayToRef = function (array, offset, result) {
  2596. result.x = array[offset];
  2597. result.y = array[offset + 1];
  2598. };
  2599. /**
  2600. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2601. * @param value1 defines 1st point of control
  2602. * @param value2 defines 2nd point of control
  2603. * @param value3 defines 3rd point of control
  2604. * @param value4 defines 4th point of control
  2605. * @param amount defines the interpolation factor
  2606. * @returns a new Vector2
  2607. */
  2608. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2609. var squared = amount * amount;
  2610. var cubed = amount * squared;
  2611. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2612. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2613. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2614. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2615. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2616. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * 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".
  2621. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2622. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2623. * @param value defines the value to clamp
  2624. * @param min defines the lower limit
  2625. * @param max defines the upper limit
  2626. * @returns a new Vector2
  2627. */
  2628. Vector2.Clamp = function (value, min, max) {
  2629. var x = value.x;
  2630. x = (x > max.x) ? max.x : x;
  2631. x = (x < min.x) ? min.x : x;
  2632. var y = value.y;
  2633. y = (y > max.y) ? max.y : y;
  2634. y = (y < min.y) ? min.y : y;
  2635. return new Vector2(x, y);
  2636. };
  2637. /**
  2638. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2639. * @param value1 defines the 1st control point
  2640. * @param tangent1 defines the outgoing tangent
  2641. * @param value2 defines the 2nd control point
  2642. * @param tangent2 defines the incoming tangent
  2643. * @param amount defines the interpolation factor
  2644. * @returns a new Vector2
  2645. */
  2646. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2647. var squared = amount * amount;
  2648. var cubed = amount * squared;
  2649. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2650. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2651. var part3 = (cubed - (2.0 * squared)) + amount;
  2652. var part4 = cubed - squared;
  2653. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2654. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2655. return new Vector2(x, y);
  2656. };
  2657. /**
  2658. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2659. * @param start defines the start vector
  2660. * @param end defines the end vector
  2661. * @param amount defines the interpolation factor
  2662. * @returns a new Vector2
  2663. */
  2664. Vector2.Lerp = function (start, end, amount) {
  2665. var x = start.x + ((end.x - start.x) * amount);
  2666. var y = start.y + ((end.y - start.y) * amount);
  2667. return new Vector2(x, y);
  2668. };
  2669. /**
  2670. * Gets the dot product of the vector "left" and the vector "right"
  2671. * @param left defines first vector
  2672. * @param right defines second vector
  2673. * @returns the dot product (float)
  2674. */
  2675. Vector2.Dot = function (left, right) {
  2676. return left.x * right.x + left.y * right.y;
  2677. };
  2678. /**
  2679. * Returns a new Vector2 equal to the normalized given vector
  2680. * @param vector defines the vector to normalize
  2681. * @returns a new Vector2
  2682. */
  2683. Vector2.Normalize = function (vector) {
  2684. var newVector = vector.clone();
  2685. newVector.normalize();
  2686. return newVector;
  2687. };
  2688. /**
  2689. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2690. * @param left defines 1st vector
  2691. * @param right defines 2nd vector
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Minimize = function (left, right) {
  2695. var x = (left.x < right.x) ? left.x : right.x;
  2696. var y = (left.y < right.y) ? left.y : right.y;
  2697. return new Vector2(x, y);
  2698. };
  2699. /**
  2700. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2701. * @param left defines 1st vector
  2702. * @param right defines 2nd vector
  2703. * @returns a new Vector2
  2704. */
  2705. Vector2.Maximize = function (left, right) {
  2706. var x = (left.x > right.x) ? left.x : right.x;
  2707. var y = (left.y > right.y) ? left.y : right.y;
  2708. return new Vector2(x, y);
  2709. };
  2710. /**
  2711. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2712. * @param vector defines the vector to transform
  2713. * @param transformation defines the matrix to apply
  2714. * @returns a new Vector2
  2715. */
  2716. Vector2.Transform = function (vector, transformation) {
  2717. var r = Vector2.Zero();
  2718. Vector2.TransformToRef(vector, transformation, r);
  2719. return r;
  2720. };
  2721. /**
  2722. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2723. * @param vector defines the vector to transform
  2724. * @param transformation defines the matrix to apply
  2725. * @param result defines the target vector
  2726. */
  2727. Vector2.TransformToRef = function (vector, transformation, result) {
  2728. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2729. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2730. result.x = x;
  2731. result.y = y;
  2732. };
  2733. /**
  2734. * Determines if a given vector is included in a triangle
  2735. * @param p defines the vector to test
  2736. * @param p0 defines 1st triangle point
  2737. * @param p1 defines 2nd triangle point
  2738. * @param p2 defines 3rd triangle point
  2739. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2740. */
  2741. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2742. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2743. var sign = a < 0 ? -1 : 1;
  2744. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2745. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2746. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2747. };
  2748. /**
  2749. * Gets the distance between the vectors "value1" and "value2"
  2750. * @param value1 defines first vector
  2751. * @param value2 defines second vector
  2752. * @returns the distance between vectors
  2753. */
  2754. Vector2.Distance = function (value1, value2) {
  2755. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2756. };
  2757. /**
  2758. * Returns the squared distance between the vectors "value1" and "value2"
  2759. * @param value1 defines first vector
  2760. * @param value2 defines second vector
  2761. * @returns the squared distance between vectors
  2762. */
  2763. Vector2.DistanceSquared = function (value1, value2) {
  2764. var x = value1.x - value2.x;
  2765. var y = value1.y - value2.y;
  2766. return (x * x) + (y * y);
  2767. };
  2768. /**
  2769. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2770. * @param value1 defines first vector
  2771. * @param value2 defines second vector
  2772. * @returns a new Vector2
  2773. */
  2774. Vector2.Center = function (value1, value2) {
  2775. var center = value1.add(value2);
  2776. center.scaleInPlace(0.5);
  2777. return center;
  2778. };
  2779. /**
  2780. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2781. * @param p defines the middle point
  2782. * @param segA defines one point of the segment
  2783. * @param segB defines the other point of the segment
  2784. * @returns the shortest distance
  2785. */
  2786. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2787. var l2 = Vector2.DistanceSquared(segA, segB);
  2788. if (l2 === 0.0) {
  2789. return Vector2.Distance(p, segA);
  2790. }
  2791. var v = segB.subtract(segA);
  2792. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2793. var proj = segA.add(v.multiplyByFloats(t, t));
  2794. return Vector2.Distance(p, proj);
  2795. };
  2796. return Vector2;
  2797. }());
  2798. BABYLON.Vector2 = Vector2;
  2799. /**
  2800. * Classed used to store (x,y,z) vector representation
  2801. * A Vector3 is the main object used in 3D geometry
  2802. * It can represent etiher the coordinates of a point the space, either a direction
  2803. * Reminder: Babylon.js uses a left handed forward facing system
  2804. */
  2805. var Vector3 = /** @class */ (function () {
  2806. /**
  2807. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2808. * @param x defines the first coordinates (on X axis)
  2809. * @param y defines the second coordinates (on Y axis)
  2810. * @param z defines the third coordinates (on Z axis)
  2811. */
  2812. function Vector3(
  2813. /**
  2814. * Defines the first coordinates (on X axis)
  2815. */
  2816. x,
  2817. /**
  2818. * Defines the second coordinates (on Y axis)
  2819. */
  2820. y,
  2821. /**
  2822. * Defines the third coordinates (on Z axis)
  2823. */
  2824. z) {
  2825. if (x === void 0) { x = 0; }
  2826. if (y === void 0) { y = 0; }
  2827. if (z === void 0) { z = 0; }
  2828. this.x = x;
  2829. this.y = y;
  2830. this.z = z;
  2831. }
  2832. /**
  2833. * Creates a string representation of the Vector3
  2834. * @returns a string with the Vector3 coordinates.
  2835. */
  2836. Vector3.prototype.toString = function () {
  2837. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2838. };
  2839. /**
  2840. * Gets the class name
  2841. * @returns the string "Vector3"
  2842. */
  2843. Vector3.prototype.getClassName = function () {
  2844. return "Vector3";
  2845. };
  2846. /**
  2847. * Creates the Vector3 hash code
  2848. * @returns a number which tends to be unique between Vector3 instances
  2849. */
  2850. Vector3.prototype.getHashCode = function () {
  2851. var hash = this.x || 0;
  2852. hash = (hash * 397) ^ (this.y || 0);
  2853. hash = (hash * 397) ^ (this.z || 0);
  2854. return hash;
  2855. };
  2856. // Operators
  2857. /**
  2858. * Creates an array containing three elements : the coordinates of the Vector3
  2859. * @returns a new array of numbers
  2860. */
  2861. Vector3.prototype.asArray = function () {
  2862. var result = [];
  2863. this.toArray(result, 0);
  2864. return result;
  2865. };
  2866. /**
  2867. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2868. * @param array defines the destination array
  2869. * @param index defines the offset in the destination array
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.toArray = function (array, index) {
  2873. if (index === void 0) { index = 0; }
  2874. array[index] = this.x;
  2875. array[index + 1] = this.y;
  2876. array[index + 2] = this.z;
  2877. return this;
  2878. };
  2879. /**
  2880. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2881. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2882. */
  2883. Vector3.prototype.toQuaternion = function () {
  2884. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2885. };
  2886. /**
  2887. * Adds the given vector to the current Vector3
  2888. * @param otherVector defines the second operand
  2889. * @returns the current updated Vector3
  2890. */
  2891. Vector3.prototype.addInPlace = function (otherVector) {
  2892. this.x += otherVector.x;
  2893. this.y += otherVector.y;
  2894. this.z += otherVector.z;
  2895. return this;
  2896. };
  2897. /**
  2898. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2899. * @param otherVector defines the second operand
  2900. * @returns the resulting Vector3
  2901. */
  2902. Vector3.prototype.add = function (otherVector) {
  2903. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2904. };
  2905. /**
  2906. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2907. * @param otherVector defines the second operand
  2908. * @param result defines the Vector3 object where to store the result
  2909. * @returns the current Vector3
  2910. */
  2911. Vector3.prototype.addToRef = function (otherVector, result) {
  2912. result.x = this.x + otherVector.x;
  2913. result.y = this.y + otherVector.y;
  2914. result.z = this.z + otherVector.z;
  2915. return this;
  2916. };
  2917. /**
  2918. * Subtract the given vector from the current Vector3
  2919. * @param otherVector defines the second operand
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.subtractInPlace = function (otherVector) {
  2923. this.x -= otherVector.x;
  2924. this.y -= otherVector.y;
  2925. this.z -= otherVector.z;
  2926. return this;
  2927. };
  2928. /**
  2929. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2930. * @param otherVector defines the second operand
  2931. * @returns the resulting Vector3
  2932. */
  2933. Vector3.prototype.subtract = function (otherVector) {
  2934. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2935. };
  2936. /**
  2937. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2938. * @param otherVector defines the second operand
  2939. * @param result defines the Vector3 object where to store the result
  2940. * @returns the current Vector3
  2941. */
  2942. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2943. result.x = this.x - otherVector.x;
  2944. result.y = this.y - otherVector.y;
  2945. result.z = this.z - otherVector.z;
  2946. return this;
  2947. };
  2948. /**
  2949. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2950. * @param x defines the x coordinate of the operand
  2951. * @param y defines the y coordinate of the operand
  2952. * @param z defines the z coordinate of the operand
  2953. * @returns the resulting Vector3
  2954. */
  2955. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2956. return new Vector3(this.x - x, this.y - y, this.z - z);
  2957. };
  2958. /**
  2959. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2960. * @param x defines the x coordinate of the operand
  2961. * @param y defines the y coordinate of the operand
  2962. * @param z defines the z coordinate of the operand
  2963. * @param result defines the Vector3 object where to store the result
  2964. * @returns the current Vector3
  2965. */
  2966. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2967. result.x = this.x - x;
  2968. result.y = this.y - y;
  2969. result.z = this.z - z;
  2970. return this;
  2971. };
  2972. /**
  2973. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2974. * @returns a new Vector3
  2975. */
  2976. Vector3.prototype.negate = function () {
  2977. return new Vector3(-this.x, -this.y, -this.z);
  2978. };
  2979. /**
  2980. * Multiplies the Vector3 coordinates by the float "scale"
  2981. * @param scale defines the multiplier factor
  2982. * @returns the current updated Vector3
  2983. */
  2984. Vector3.prototype.scaleInPlace = function (scale) {
  2985. this.x *= scale;
  2986. this.y *= scale;
  2987. this.z *= scale;
  2988. return this;
  2989. };
  2990. /**
  2991. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2992. * @param scale defines the multiplier factor
  2993. * @returns a new Vector3
  2994. */
  2995. Vector3.prototype.scale = function (scale) {
  2996. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2997. };
  2998. /**
  2999. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3000. * @param scale defines the multiplier factor
  3001. * @param result defines the Vector3 object where to store the result
  3002. * @returns the current Vector3
  3003. */
  3004. Vector3.prototype.scaleToRef = function (scale, result) {
  3005. result.x = this.x * scale;
  3006. result.y = this.y * scale;
  3007. result.z = this.z * scale;
  3008. return this;
  3009. };
  3010. /**
  3011. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3012. * @param scale defines the scale factor
  3013. * @param result defines the Vector3 object where to store the result
  3014. * @returns the unmodified current Vector3
  3015. */
  3016. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3017. result.x += this.x * scale;
  3018. result.y += this.y * scale;
  3019. result.z += this.z * scale;
  3020. return this;
  3021. };
  3022. /**
  3023. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3024. * @param otherVector defines the second operand
  3025. * @returns true if both vectors are equals
  3026. */
  3027. Vector3.prototype.equals = function (otherVector) {
  3028. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3029. };
  3030. /**
  3031. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3032. * @param otherVector defines the second operand
  3033. * @param epsilon defines the minimal distance to define values as equals
  3034. * @returns true if both vectors are distant less than epsilon
  3035. */
  3036. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3037. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3038. 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);
  3039. };
  3040. /**
  3041. * Returns true if the current Vector3 coordinates equals the given floats
  3042. * @param x defines the x coordinate of the operand
  3043. * @param y defines the y coordinate of the operand
  3044. * @param z defines the z coordinate of the operand
  3045. * @returns true if both vectors are equals
  3046. */
  3047. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3048. return this.x === x && this.y === y && this.z === z;
  3049. };
  3050. /**
  3051. * Multiplies the current Vector3 coordinates by the given ones
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3056. this.x *= otherVector.x;
  3057. this.y *= otherVector.y;
  3058. this.z *= otherVector.z;
  3059. return this;
  3060. };
  3061. /**
  3062. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3063. * @param otherVector defines the second operand
  3064. * @returns the new Vector3
  3065. */
  3066. Vector3.prototype.multiply = function (otherVector) {
  3067. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3068. };
  3069. /**
  3070. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3071. * @param otherVector defines the second operand
  3072. * @param result defines the Vector3 object where to store the result
  3073. * @returns the current Vector3
  3074. */
  3075. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3076. result.x = this.x * otherVector.x;
  3077. result.y = this.y * otherVector.y;
  3078. result.z = this.z * otherVector.z;
  3079. return this;
  3080. };
  3081. /**
  3082. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3083. * @param x defines the x coordinate of the operand
  3084. * @param y defines the y coordinate of the operand
  3085. * @param z defines the z coordinate of the operand
  3086. * @returns the new Vector3
  3087. */
  3088. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3089. return new Vector3(this.x * x, this.y * y, this.z * z);
  3090. };
  3091. /**
  3092. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3093. * @param otherVector defines the second operand
  3094. * @returns the new Vector3
  3095. */
  3096. Vector3.prototype.divide = function (otherVector) {
  3097. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3098. };
  3099. /**
  3100. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3101. * @param otherVector defines the second operand
  3102. * @param result defines the Vector3 object where to store the result
  3103. * @returns the current Vector3
  3104. */
  3105. Vector3.prototype.divideToRef = function (otherVector, result) {
  3106. result.x = this.x / otherVector.x;
  3107. result.y = this.y / otherVector.y;
  3108. result.z = this.z / otherVector.z;
  3109. return this;
  3110. };
  3111. /**
  3112. * Divides the current Vector3 coordinates by the given ones.
  3113. * @param otherVector defines the second operand
  3114. * @returns the current updated Vector3
  3115. */
  3116. Vector3.prototype.divideInPlace = function (otherVector) {
  3117. return this.divideToRef(otherVector, this);
  3118. };
  3119. /**
  3120. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3121. * @param other defines the second operand
  3122. * @returns the current updated Vector3
  3123. */
  3124. Vector3.prototype.minimizeInPlace = function (other) {
  3125. if (other.x < this.x)
  3126. this.x = other.x;
  3127. if (other.y < this.y)
  3128. this.y = other.y;
  3129. if (other.z < this.z)
  3130. this.z = other.z;
  3131. return this;
  3132. };
  3133. /**
  3134. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3135. * @param other defines the second operand
  3136. * @returns the current updated Vector3
  3137. */
  3138. Vector3.prototype.maximizeInPlace = function (other) {
  3139. if (other.x > this.x)
  3140. this.x = other.x;
  3141. if (other.y > this.y)
  3142. this.y = other.y;
  3143. if (other.z > this.z)
  3144. this.z = other.z;
  3145. return this;
  3146. };
  3147. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3148. /**
  3149. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3150. */
  3151. get: function () {
  3152. var absX = Math.abs(this.x);
  3153. var absY = Math.abs(this.y);
  3154. if (absX !== absY) {
  3155. return true;
  3156. }
  3157. var absZ = Math.abs(this.z);
  3158. if (absX !== absZ) {
  3159. return true;
  3160. }
  3161. if (absY !== absZ) {
  3162. return true;
  3163. }
  3164. return false;
  3165. },
  3166. enumerable: true,
  3167. configurable: true
  3168. });
  3169. /**
  3170. * Gets a new Vector3 from current Vector3 floored values
  3171. * @returns a new Vector3
  3172. */
  3173. Vector3.prototype.floor = function () {
  3174. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3175. };
  3176. /**
  3177. * Gets a new Vector3 from current Vector3 floored values
  3178. * @returns a new Vector3
  3179. */
  3180. Vector3.prototype.fract = function () {
  3181. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3182. };
  3183. // Properties
  3184. /**
  3185. * Gets the length of the Vector3
  3186. * @returns the length of the Vecto3
  3187. */
  3188. Vector3.prototype.length = function () {
  3189. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3190. };
  3191. /**
  3192. * Gets the squared length of the Vector3
  3193. * @returns squared length of the Vector3
  3194. */
  3195. Vector3.prototype.lengthSquared = function () {
  3196. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3197. };
  3198. /**
  3199. * Normalize the current Vector3.
  3200. * Please note that this is an in place operation.
  3201. * @returns the current updated Vector3
  3202. */
  3203. Vector3.prototype.normalize = function () {
  3204. var len = this.length();
  3205. if (len === 0 || len === 1.0)
  3206. return this;
  3207. var num = 1.0 / len;
  3208. this.x *= num;
  3209. this.y *= num;
  3210. this.z *= num;
  3211. return this;
  3212. };
  3213. /**
  3214. * Normalize the current Vector3 to a new vector
  3215. * @returns the new Vector3
  3216. */
  3217. Vector3.prototype.normalizeToNew = function () {
  3218. var normalized = new Vector3(0, 0, 0);
  3219. this.normalizeToRef(normalized);
  3220. return normalized;
  3221. };
  3222. /**
  3223. * Normalize the current Vector3 to the reference
  3224. * @param reference define the Vector3 to update
  3225. * @returns the updated Vector3
  3226. */
  3227. Vector3.prototype.normalizeToRef = function (reference) {
  3228. var len = this.length();
  3229. if (len === 0 || len === 1.0) {
  3230. reference.set(this.x, this.y, this.z);
  3231. return reference;
  3232. }
  3233. var scale = 1.0 / len;
  3234. this.scaleToRef(scale, reference);
  3235. return reference;
  3236. };
  3237. /**
  3238. * Creates a new Vector3 copied from the current Vector3
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.prototype.clone = function () {
  3242. return new Vector3(this.x, this.y, this.z);
  3243. };
  3244. /**
  3245. * Copies the given vector coordinates to the current Vector3 ones
  3246. * @param source defines the source Vector3
  3247. * @returns the current updated Vector3
  3248. */
  3249. Vector3.prototype.copyFrom = function (source) {
  3250. this.x = source.x;
  3251. this.y = source.y;
  3252. this.z = source.z;
  3253. return this;
  3254. };
  3255. /**
  3256. * Copies the given floats to the current Vector3 coordinates
  3257. * @param x defines the x coordinate of the operand
  3258. * @param y defines the y coordinate of the operand
  3259. * @param z defines the z coordinate of the operand
  3260. * @returns the current updated Vector3
  3261. */
  3262. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3263. this.x = x;
  3264. this.y = y;
  3265. this.z = z;
  3266. return this;
  3267. };
  3268. /**
  3269. * Copies the given floats to the current Vector3 coordinates
  3270. * @param x defines the x coordinate of the operand
  3271. * @param y defines the y coordinate of the operand
  3272. * @param z defines the z coordinate of the operand
  3273. * @returns the current updated Vector3
  3274. */
  3275. Vector3.prototype.set = function (x, y, z) {
  3276. return this.copyFromFloats(x, y, z);
  3277. };
  3278. // Statics
  3279. /**
  3280. * Get the clip factor between two vectors
  3281. * @param vector0 defines the first operand
  3282. * @param vector1 defines the second operand
  3283. * @param axis defines the axis to use
  3284. * @param size defines the size along the axis
  3285. * @returns the clip factor
  3286. */
  3287. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3288. var d0 = Vector3.Dot(vector0, axis) - size;
  3289. var d1 = Vector3.Dot(vector1, axis) - size;
  3290. var s = d0 / (d0 - d1);
  3291. return s;
  3292. };
  3293. /**
  3294. * Get angle between two vectors
  3295. * @param vector0 angle between vector0 and vector1
  3296. * @param vector1 angle between vector0 and vector1
  3297. * @param normal direction of the normal
  3298. * @return the angle between vector0 and vector1
  3299. */
  3300. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3301. var v0 = vector0.clone().normalize();
  3302. var v1 = vector1.clone().normalize();
  3303. var dot = Vector3.Dot(v0, v1);
  3304. var n = Vector3.Cross(v0, v1);
  3305. if (Vector3.Dot(n, normal) > 0) {
  3306. return Math.acos(dot);
  3307. }
  3308. return -Math.acos(dot);
  3309. };
  3310. /**
  3311. * Returns a new Vector3 set from the index "offset" of the given array
  3312. * @param array defines the source array
  3313. * @param offset defines the offset in the source array
  3314. * @returns the new Vector3
  3315. */
  3316. Vector3.FromArray = function (array, offset) {
  3317. if (!offset) {
  3318. offset = 0;
  3319. }
  3320. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3324. * This function is deprecated. Use FromArray instead
  3325. * @param array defines the source array
  3326. * @param offset defines the offset in the source array
  3327. * @returns the new Vector3
  3328. */
  3329. Vector3.FromFloatArray = function (array, offset) {
  3330. return Vector3.FromArray(array, offset);
  3331. };
  3332. /**
  3333. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3334. * @param array defines the source array
  3335. * @param offset defines the offset in the source array
  3336. * @param result defines the Vector3 where to store the result
  3337. */
  3338. Vector3.FromArrayToRef = function (array, offset, result) {
  3339. result.x = array[offset];
  3340. result.y = array[offset + 1];
  3341. result.z = array[offset + 2];
  3342. };
  3343. /**
  3344. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3345. * This function is deprecated. Use FromArrayToRef instead.
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @param result defines the Vector3 where to store the result
  3349. */
  3350. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3351. return Vector3.FromArrayToRef(array, offset, result);
  3352. };
  3353. /**
  3354. * Sets the given vector "result" with the given floats.
  3355. * @param x defines the x coordinate of the source
  3356. * @param y defines the y coordinate of the source
  3357. * @param z defines the z coordinate of the source
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3361. result.x = x;
  3362. result.y = y;
  3363. result.z = z;
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3367. * @returns a new empty Vector3
  3368. */
  3369. Vector3.Zero = function () {
  3370. return new Vector3(0.0, 0.0, 0.0);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3374. * @returns a new unit Vector3
  3375. */
  3376. Vector3.One = function () {
  3377. return new Vector3(1.0, 1.0, 1.0);
  3378. };
  3379. /**
  3380. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3381. * @returns a new up Vector3
  3382. */
  3383. Vector3.Up = function () {
  3384. return new Vector3(0.0, 1.0, 0.0);
  3385. };
  3386. /**
  3387. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3388. * @returns a new down Vector3
  3389. */
  3390. Vector3.Down = function () {
  3391. return new Vector3(0.0, -1.0, 0.0);
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3395. * @returns a new forward Vector3
  3396. */
  3397. Vector3.Forward = function () {
  3398. return new Vector3(0.0, 0.0, 1.0);
  3399. };
  3400. /**
  3401. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3402. * @returns a new right Vector3
  3403. */
  3404. Vector3.Right = function () {
  3405. return new Vector3(1.0, 0.0, 0.0);
  3406. };
  3407. /**
  3408. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3409. * @returns a new left Vector3
  3410. */
  3411. Vector3.Left = function () {
  3412. return new Vector3(-1.0, 0.0, 0.0);
  3413. };
  3414. /**
  3415. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3416. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3417. * @param vector defines the Vector3 to transform
  3418. * @param transformation defines the transformation matrix
  3419. * @returns the transformed Vector3
  3420. */
  3421. Vector3.TransformCoordinates = function (vector, transformation) {
  3422. var result = Vector3.Zero();
  3423. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3424. return result;
  3425. };
  3426. /**
  3427. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3428. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3429. * @param vector defines the Vector3 to transform
  3430. * @param transformation defines the transformation matrix
  3431. * @param result defines the Vector3 where to store the result
  3432. */
  3433. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3434. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3435. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3436. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3437. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3438. result.x = x / w;
  3439. result.y = y / w;
  3440. result.z = z / w;
  3441. };
  3442. /**
  3443. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3444. * This method computes tranformed coordinates only, not transformed direction vectors
  3445. * @param x define the x coordinate of the source vector
  3446. * @param y define the y coordinate of the source vector
  3447. * @param z define the z coordinate of the source vector
  3448. * @param transformation defines the transformation matrix
  3449. * @param result defines the Vector3 where to store the result
  3450. */
  3451. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3452. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3453. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3454. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3455. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3456. result.x = rx / rw;
  3457. result.y = ry / rw;
  3458. result.z = rz / rw;
  3459. };
  3460. /**
  3461. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3462. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3463. * @param vector defines the Vector3 to transform
  3464. * @param transformation defines the transformation matrix
  3465. * @returns the new Vector3
  3466. */
  3467. Vector3.TransformNormal = function (vector, transformation) {
  3468. var result = Vector3.Zero();
  3469. Vector3.TransformNormalToRef(vector, transformation, result);
  3470. return result;
  3471. };
  3472. /**
  3473. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3474. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3475. * @param vector defines the Vector3 to transform
  3476. * @param transformation defines the transformation matrix
  3477. * @param result defines the Vector3 where to store the result
  3478. */
  3479. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3480. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3481. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3482. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3483. result.x = x;
  3484. result.y = y;
  3485. result.z = z;
  3486. };
  3487. /**
  3488. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3489. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3490. * @param x define the x coordinate of the source vector
  3491. * @param y define the y coordinate of the source vector
  3492. * @param z define the z coordinate of the source vector
  3493. * @param transformation defines the transformation matrix
  3494. * @param result defines the Vector3 where to store the result
  3495. */
  3496. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3497. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3498. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3499. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3500. };
  3501. /**
  3502. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3503. * @param value1 defines the first control point
  3504. * @param value2 defines the second control point
  3505. * @param value3 defines the third control point
  3506. * @param value4 defines the fourth control point
  3507. * @param amount defines the amount on the spline to use
  3508. * @returns the new Vector3
  3509. */
  3510. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3511. var squared = amount * amount;
  3512. var cubed = amount * squared;
  3513. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3514. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3515. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3516. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3517. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3518. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3519. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3520. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3521. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3522. return new Vector3(x, y, z);
  3523. };
  3524. /**
  3525. * 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"
  3526. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3527. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3528. * @param value defines the current value
  3529. * @param min defines the lower range value
  3530. * @param max defines the upper range value
  3531. * @returns the new Vector3
  3532. */
  3533. Vector3.Clamp = function (value, min, max) {
  3534. var x = value.x;
  3535. x = (x > max.x) ? max.x : x;
  3536. x = (x < min.x) ? min.x : x;
  3537. var y = value.y;
  3538. y = (y > max.y) ? max.y : y;
  3539. y = (y < min.y) ? min.y : y;
  3540. var z = value.z;
  3541. z = (z > max.z) ? max.z : z;
  3542. z = (z < min.z) ? min.z : z;
  3543. return new Vector3(x, y, z);
  3544. };
  3545. /**
  3546. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3547. * @param value1 defines the first control point
  3548. * @param tangent1 defines the first tangent vector
  3549. * @param value2 defines the second control point
  3550. * @param tangent2 defines the second tangent vector
  3551. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3555. var squared = amount * amount;
  3556. var cubed = amount * squared;
  3557. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3558. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3559. var part3 = (cubed - (2.0 * squared)) + amount;
  3560. var part4 = cubed - squared;
  3561. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3562. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3563. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3564. return new Vector3(x, y, z);
  3565. };
  3566. /**
  3567. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3568. * @param start defines the start value
  3569. * @param end defines the end value
  3570. * @param amount max defines amount between both (between 0 and 1)
  3571. * @returns the new Vector3
  3572. */
  3573. Vector3.Lerp = function (start, end, amount) {
  3574. var result = new Vector3(0, 0, 0);
  3575. Vector3.LerpToRef(start, end, amount, result);
  3576. return result;
  3577. };
  3578. /**
  3579. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3580. * @param start defines the start value
  3581. * @param end defines the end value
  3582. * @param amount max defines amount between both (between 0 and 1)
  3583. * @param result defines the Vector3 where to store the result
  3584. */
  3585. Vector3.LerpToRef = function (start, end, amount, result) {
  3586. result.x = start.x + ((end.x - start.x) * amount);
  3587. result.y = start.y + ((end.y - start.y) * amount);
  3588. result.z = start.z + ((end.z - start.z) * amount);
  3589. };
  3590. /**
  3591. * Returns the dot product (float) between the vectors "left" and "right"
  3592. * @param left defines the left operand
  3593. * @param right defines the right operand
  3594. * @returns the dot product
  3595. */
  3596. Vector3.Dot = function (left, right) {
  3597. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3598. };
  3599. /**
  3600. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3601. * The cross product is then orthogonal to both "left" and "right"
  3602. * @param left defines the left operand
  3603. * @param right defines the right operand
  3604. * @returns the cross product
  3605. */
  3606. Vector3.Cross = function (left, right) {
  3607. var result = Vector3.Zero();
  3608. Vector3.CrossToRef(left, right, result);
  3609. return result;
  3610. };
  3611. /**
  3612. * Sets the given vector "result" with the cross product of "left" and "right"
  3613. * The cross product is then orthogonal to both "left" and "right"
  3614. * @param left defines the left operand
  3615. * @param right defines the right operand
  3616. * @param result defines the Vector3 where to store the result
  3617. */
  3618. Vector3.CrossToRef = function (left, right, result) {
  3619. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3620. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3621. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3622. result.copyFrom(MathTmp.Vector3[0]);
  3623. };
  3624. /**
  3625. * Returns a new Vector3 as the normalization of the given vector
  3626. * @param vector defines the Vector3 to normalize
  3627. * @returns the new Vector3
  3628. */
  3629. Vector3.Normalize = function (vector) {
  3630. var result = Vector3.Zero();
  3631. Vector3.NormalizeToRef(vector, result);
  3632. return result;
  3633. };
  3634. /**
  3635. * Sets the given vector "result" with the normalization of the given first vector
  3636. * @param vector defines the Vector3 to normalize
  3637. * @param result defines the Vector3 where to store the result
  3638. */
  3639. Vector3.NormalizeToRef = function (vector, result) {
  3640. result.copyFrom(vector);
  3641. result.normalize();
  3642. };
  3643. /**
  3644. * Project a Vector3 onto screen space
  3645. * @param vector defines the Vector3 to project
  3646. * @param world defines the world matrix to use
  3647. * @param transform defines the transform (view x projection) matrix to use
  3648. * @param viewport defines the screen viewport to use
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.Project = function (vector, world, transform, viewport) {
  3652. var cw = viewport.width;
  3653. var ch = viewport.height;
  3654. var cx = viewport.x;
  3655. var cy = viewport.y;
  3656. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3657. 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);
  3658. var matrix = MathTmp.Matrix[0];
  3659. world.multiplyToRef(transform, matrix);
  3660. matrix.multiplyToRef(viewportMatrix, matrix);
  3661. return Vector3.TransformCoordinates(vector, matrix);
  3662. };
  3663. /**
  3664. * Unproject from screen space to object space
  3665. * @param source defines the screen space Vector3 to use
  3666. * @param viewportWidth defines the current width of the viewport
  3667. * @param viewportHeight defines the current height of the viewport
  3668. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3669. * @param transform defines the transform (view x projection) matrix to use
  3670. * @returns the new Vector3
  3671. */
  3672. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3673. var matrix = MathTmp.Matrix[0];
  3674. world.multiplyToRef(transform, matrix);
  3675. matrix.invert();
  3676. source.x = source.x / viewportWidth * 2 - 1;
  3677. source.y = -(source.y / viewportHeight * 2 - 1);
  3678. var vector = Vector3.TransformCoordinates(source, matrix);
  3679. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3680. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3681. vector = vector.scale(1.0 / num);
  3682. }
  3683. return vector;
  3684. };
  3685. /**
  3686. * Unproject from screen space to object space
  3687. * @param source defines the screen space Vector3 to use
  3688. * @param viewportWidth defines the current width of the viewport
  3689. * @param viewportHeight defines the current height of the viewport
  3690. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3691. * @param view defines the view matrix to use
  3692. * @param projection defines the projection matrix to use
  3693. * @returns the new Vector3
  3694. */
  3695. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3696. var result = Vector3.Zero();
  3697. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3698. return result;
  3699. };
  3700. /**
  3701. * Unproject from screen space to object space
  3702. * @param source defines the screen space Vector3 to use
  3703. * @param viewportWidth defines the current width of the viewport
  3704. * @param viewportHeight defines the current height of the viewport
  3705. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3706. * @param view defines the view matrix to use
  3707. * @param projection defines the projection matrix to use
  3708. * @param result defines the Vector3 where to store the result
  3709. */
  3710. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3711. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3712. };
  3713. /**
  3714. * Unproject from screen space to object space
  3715. * @param sourceX defines the screen space x coordinate to use
  3716. * @param sourceY defines the screen space y coordinate to use
  3717. * @param sourceZ defines the screen space z coordinate to use
  3718. * @param viewportWidth defines the current width of the viewport
  3719. * @param viewportHeight defines the current height of the viewport
  3720. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3721. * @param view defines the view matrix to use
  3722. * @param projection defines the projection matrix to use
  3723. * @param result defines the Vector3 where to store the result
  3724. */
  3725. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3726. var matrix = MathTmp.Matrix[0];
  3727. world.multiplyToRef(view, matrix);
  3728. matrix.multiplyToRef(projection, matrix);
  3729. matrix.invert();
  3730. var screenSource = MathTmp.Vector3[0];
  3731. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3732. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3733. screenSource.z = 2 * sourceZ - 1.0;
  3734. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3735. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3736. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3737. result.scaleInPlace(1.0 / num);
  3738. }
  3739. };
  3740. /**
  3741. * Gets the minimal coordinate values between two Vector3
  3742. * @param left defines the first operand
  3743. * @param right defines the second operand
  3744. * @returns the new Vector3
  3745. */
  3746. Vector3.Minimize = function (left, right) {
  3747. var min = left.clone();
  3748. min.minimizeInPlace(right);
  3749. return min;
  3750. };
  3751. /**
  3752. * Gets the maximal coordinate values between two Vector3
  3753. * @param left defines the first operand
  3754. * @param right defines the second operand
  3755. * @returns the new Vector3
  3756. */
  3757. Vector3.Maximize = function (left, right) {
  3758. var max = left.clone();
  3759. max.maximizeInPlace(right);
  3760. return max;
  3761. };
  3762. /**
  3763. * Returns the distance between the vectors "value1" and "value2"
  3764. * @param value1 defines the first operand
  3765. * @param value2 defines the second operand
  3766. * @returns the distance
  3767. */
  3768. Vector3.Distance = function (value1, value2) {
  3769. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3770. };
  3771. /**
  3772. * Returns the squared distance between the vectors "value1" and "value2"
  3773. * @param value1 defines the first operand
  3774. * @param value2 defines the second operand
  3775. * @returns the squared distance
  3776. */
  3777. Vector3.DistanceSquared = function (value1, value2) {
  3778. var x = value1.x - value2.x;
  3779. var y = value1.y - value2.y;
  3780. var z = value1.z - value2.z;
  3781. return (x * x) + (y * y) + (z * z);
  3782. };
  3783. /**
  3784. * Returns a new Vector3 located at the center between "value1" and "value2"
  3785. * @param value1 defines the first operand
  3786. * @param value2 defines the second operand
  3787. * @returns the new Vector3
  3788. */
  3789. Vector3.Center = function (value1, value2) {
  3790. var center = value1.add(value2);
  3791. center.scaleInPlace(0.5);
  3792. return center;
  3793. };
  3794. /**
  3795. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3796. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3797. * to something in order to rotate it from its local system to the given target system
  3798. * Note: axis1, axis2 and axis3 are normalized during this operation
  3799. * @param axis1 defines the first axis
  3800. * @param axis2 defines the second axis
  3801. * @param axis3 defines the third axis
  3802. * @returns a new Vector3
  3803. */
  3804. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3805. var rotation = Vector3.Zero();
  3806. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3807. return rotation;
  3808. };
  3809. /**
  3810. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3811. * @param axis1 defines the first axis
  3812. * @param axis2 defines the second axis
  3813. * @param axis3 defines the third axis
  3814. * @param ref defines the Vector3 where to store the result
  3815. */
  3816. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3817. var quat = MathTmp.Quaternion[0];
  3818. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3819. quat.toEulerAnglesToRef(ref);
  3820. };
  3821. return Vector3;
  3822. }());
  3823. BABYLON.Vector3 = Vector3;
  3824. //Vector4 class created for EulerAngle class conversion to Quaternion
  3825. var Vector4 = /** @class */ (function () {
  3826. /**
  3827. * Creates a Vector4 object from the given floats.
  3828. */
  3829. function Vector4(x, y, z, w) {
  3830. this.x = x;
  3831. this.y = y;
  3832. this.z = z;
  3833. this.w = w;
  3834. }
  3835. /**
  3836. * Returns the string with the Vector4 coordinates.
  3837. */
  3838. Vector4.prototype.toString = function () {
  3839. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3840. };
  3841. /**
  3842. * Returns the string "Vector4".
  3843. */
  3844. Vector4.prototype.getClassName = function () {
  3845. return "Vector4";
  3846. };
  3847. /**
  3848. * Returns the Vector4 hash code.
  3849. */
  3850. Vector4.prototype.getHashCode = function () {
  3851. var hash = this.x || 0;
  3852. hash = (hash * 397) ^ (this.y || 0);
  3853. hash = (hash * 397) ^ (this.z || 0);
  3854. hash = (hash * 397) ^ (this.w || 0);
  3855. return hash;
  3856. };
  3857. // Operators
  3858. /**
  3859. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3860. */
  3861. Vector4.prototype.asArray = function () {
  3862. var result = new Array();
  3863. this.toArray(result, 0);
  3864. return result;
  3865. };
  3866. /**
  3867. * Populates the given array from the given index with the Vector4 coordinates.
  3868. * Returns the Vector4.
  3869. */
  3870. Vector4.prototype.toArray = function (array, index) {
  3871. if (index === undefined) {
  3872. index = 0;
  3873. }
  3874. array[index] = this.x;
  3875. array[index + 1] = this.y;
  3876. array[index + 2] = this.z;
  3877. array[index + 3] = this.w;
  3878. return this;
  3879. };
  3880. /**
  3881. * Adds the given vector to the current Vector4.
  3882. * Returns the updated Vector4.
  3883. */
  3884. Vector4.prototype.addInPlace = function (otherVector) {
  3885. this.x += otherVector.x;
  3886. this.y += otherVector.y;
  3887. this.z += otherVector.z;
  3888. this.w += otherVector.w;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3893. */
  3894. Vector4.prototype.add = function (otherVector) {
  3895. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3896. };
  3897. /**
  3898. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3899. * Returns the current Vector4.
  3900. */
  3901. Vector4.prototype.addToRef = function (otherVector, result) {
  3902. result.x = this.x + otherVector.x;
  3903. result.y = this.y + otherVector.y;
  3904. result.z = this.z + otherVector.z;
  3905. result.w = this.w + otherVector.w;
  3906. return this;
  3907. };
  3908. /**
  3909. * Subtract in place the given vector from the current Vector4.
  3910. * Returns the updated Vector4.
  3911. */
  3912. Vector4.prototype.subtractInPlace = function (otherVector) {
  3913. this.x -= otherVector.x;
  3914. this.y -= otherVector.y;
  3915. this.z -= otherVector.z;
  3916. this.w -= otherVector.w;
  3917. return this;
  3918. };
  3919. /**
  3920. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3921. */
  3922. Vector4.prototype.subtract = function (otherVector) {
  3923. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3924. };
  3925. /**
  3926. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3927. * Returns the current Vector4.
  3928. */
  3929. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3930. result.x = this.x - otherVector.x;
  3931. result.y = this.y - otherVector.y;
  3932. result.z = this.z - otherVector.z;
  3933. result.w = this.w - otherVector.w;
  3934. return this;
  3935. };
  3936. /**
  3937. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3938. */
  3939. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3940. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3941. };
  3942. /**
  3943. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3944. * Returns the current Vector4.
  3945. */
  3946. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3947. result.x = this.x - x;
  3948. result.y = this.y - y;
  3949. result.z = this.z - z;
  3950. result.w = this.w - w;
  3951. return this;
  3952. };
  3953. /**
  3954. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3955. */
  3956. Vector4.prototype.negate = function () {
  3957. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3958. };
  3959. /**
  3960. * Multiplies the current Vector4 coordinates by scale (float).
  3961. * Returns the updated Vector4.
  3962. */
  3963. Vector4.prototype.scaleInPlace = function (scale) {
  3964. this.x *= scale;
  3965. this.y *= scale;
  3966. this.z *= scale;
  3967. this.w *= scale;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3972. */
  3973. Vector4.prototype.scale = function (scale) {
  3974. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3975. };
  3976. /**
  3977. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.scaleToRef = function (scale, result) {
  3981. result.x = this.x * scale;
  3982. result.y = this.y * scale;
  3983. result.z = this.z * scale;
  3984. result.w = this.w * scale;
  3985. return this;
  3986. };
  3987. /**
  3988. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3989. * @param scale defines the scale factor
  3990. * @param result defines the Vector4 object where to store the result
  3991. * @returns the unmodified current Vector4
  3992. */
  3993. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3994. result.x += this.x * scale;
  3995. result.y += this.y * scale;
  3996. result.z += this.z * scale;
  3997. result.w += this.w * scale;
  3998. return this;
  3999. };
  4000. /**
  4001. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4002. */
  4003. Vector4.prototype.equals = function (otherVector) {
  4004. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4005. };
  4006. /**
  4007. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4008. */
  4009. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4010. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4011. return otherVector
  4012. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4013. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4014. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4015. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4016. };
  4017. /**
  4018. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4019. */
  4020. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4021. return this.x === x && this.y === y && this.z === z && this.w === w;
  4022. };
  4023. /**
  4024. * Multiplies in place the current Vector4 by the given one.
  4025. * Returns the updated Vector4.
  4026. */
  4027. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4028. this.x *= otherVector.x;
  4029. this.y *= otherVector.y;
  4030. this.z *= otherVector.z;
  4031. this.w *= otherVector.w;
  4032. return this;
  4033. };
  4034. /**
  4035. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4036. */
  4037. Vector4.prototype.multiply = function (otherVector) {
  4038. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4039. };
  4040. /**
  4041. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4042. * Returns the current Vector4.
  4043. */
  4044. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4045. result.x = this.x * otherVector.x;
  4046. result.y = this.y * otherVector.y;
  4047. result.z = this.z * otherVector.z;
  4048. result.w = this.w * otherVector.w;
  4049. return this;
  4050. };
  4051. /**
  4052. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4053. */
  4054. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4055. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4056. };
  4057. /**
  4058. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4059. */
  4060. Vector4.prototype.divide = function (otherVector) {
  4061. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4062. };
  4063. /**
  4064. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4065. * Returns the current Vector4.
  4066. */
  4067. Vector4.prototype.divideToRef = function (otherVector, result) {
  4068. result.x = this.x / otherVector.x;
  4069. result.y = this.y / otherVector.y;
  4070. result.z = this.z / otherVector.z;
  4071. result.w = this.w / otherVector.w;
  4072. return this;
  4073. };
  4074. /**
  4075. * Divides the current Vector3 coordinates by the given ones.
  4076. * @returns the updated Vector3.
  4077. */
  4078. Vector4.prototype.divideInPlace = function (otherVector) {
  4079. return this.divideToRef(otherVector, this);
  4080. };
  4081. /**
  4082. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4083. * @param other defines the second operand
  4084. * @returns the current updated Vector4
  4085. */
  4086. Vector4.prototype.minimizeInPlace = function (other) {
  4087. if (other.x < this.x)
  4088. this.x = other.x;
  4089. if (other.y < this.y)
  4090. this.y = other.y;
  4091. if (other.z < this.z)
  4092. this.z = other.z;
  4093. if (other.w < this.w)
  4094. this.w = other.w;
  4095. return this;
  4096. };
  4097. /**
  4098. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4099. * @param other defines the second operand
  4100. * @returns the current updated Vector4
  4101. */
  4102. Vector4.prototype.maximizeInPlace = function (other) {
  4103. if (other.x > this.x)
  4104. this.x = other.x;
  4105. if (other.y > this.y)
  4106. this.y = other.y;
  4107. if (other.z > this.z)
  4108. this.z = other.z;
  4109. if (other.w > this.w)
  4110. this.w = other.w;
  4111. return this;
  4112. };
  4113. /**
  4114. * Gets a new Vector4 from current Vector4 floored values
  4115. * @returns a new Vector4
  4116. */
  4117. Vector4.prototype.floor = function () {
  4118. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4119. };
  4120. /**
  4121. * Gets a new Vector4 from current Vector3 floored values
  4122. * @returns a new Vector4
  4123. */
  4124. Vector4.prototype.fract = function () {
  4125. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4126. };
  4127. // Properties
  4128. /**
  4129. * Returns the Vector4 length (float).
  4130. */
  4131. Vector4.prototype.length = function () {
  4132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4133. };
  4134. /**
  4135. * Returns the Vector4 squared length (float).
  4136. */
  4137. Vector4.prototype.lengthSquared = function () {
  4138. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4139. };
  4140. // Methods
  4141. /**
  4142. * Normalizes in place the Vector4.
  4143. * Returns the updated Vector4.
  4144. */
  4145. Vector4.prototype.normalize = function () {
  4146. var len = this.length();
  4147. if (len === 0)
  4148. return this;
  4149. var num = 1.0 / len;
  4150. this.x *= num;
  4151. this.y *= num;
  4152. this.z *= num;
  4153. this.w *= num;
  4154. return this;
  4155. };
  4156. /**
  4157. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4158. */
  4159. Vector4.prototype.toVector3 = function () {
  4160. return new Vector3(this.x, this.y, this.z);
  4161. };
  4162. /**
  4163. * Returns a new Vector4 copied from the current one.
  4164. */
  4165. Vector4.prototype.clone = function () {
  4166. return new Vector4(this.x, this.y, this.z, this.w);
  4167. };
  4168. /**
  4169. * Updates the current Vector4 with the given one coordinates.
  4170. * Returns the updated Vector4.
  4171. */
  4172. Vector4.prototype.copyFrom = function (source) {
  4173. this.x = source.x;
  4174. this.y = source.y;
  4175. this.z = source.z;
  4176. this.w = source.w;
  4177. return this;
  4178. };
  4179. /**
  4180. * Updates the current Vector4 coordinates with the given floats.
  4181. * Returns the updated Vector4.
  4182. */
  4183. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4184. this.x = x;
  4185. this.y = y;
  4186. this.z = z;
  4187. this.w = w;
  4188. return this;
  4189. };
  4190. /**
  4191. * Updates the current Vector4 coordinates with the given floats.
  4192. * Returns the updated Vector4.
  4193. */
  4194. Vector4.prototype.set = function (x, y, z, w) {
  4195. return this.copyFromFloats(x, y, z, w);
  4196. };
  4197. // Statics
  4198. /**
  4199. * Returns a new Vector4 set from the starting index of the given array.
  4200. */
  4201. Vector4.FromArray = function (array, offset) {
  4202. if (!offset) {
  4203. offset = 0;
  4204. }
  4205. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4206. };
  4207. /**
  4208. * Updates the given vector "result" from the starting index of the given array.
  4209. */
  4210. Vector4.FromArrayToRef = function (array, offset, result) {
  4211. result.x = array[offset];
  4212. result.y = array[offset + 1];
  4213. result.z = array[offset + 2];
  4214. result.w = array[offset + 3];
  4215. };
  4216. /**
  4217. * Updates the given vector "result" from the starting index of the given Float32Array.
  4218. */
  4219. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4220. Vector4.FromArrayToRef(array, offset, result);
  4221. };
  4222. /**
  4223. * Updates the given vector "result" coordinates from the given floats.
  4224. */
  4225. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4226. result.x = x;
  4227. result.y = y;
  4228. result.z = z;
  4229. result.w = w;
  4230. };
  4231. /**
  4232. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4233. */
  4234. Vector4.Zero = function () {
  4235. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4236. };
  4237. /**
  4238. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4239. */
  4240. Vector4.One = function () {
  4241. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4242. };
  4243. /**
  4244. * Returns a new normalized Vector4 from the given one.
  4245. */
  4246. Vector4.Normalize = function (vector) {
  4247. var result = Vector4.Zero();
  4248. Vector4.NormalizeToRef(vector, result);
  4249. return result;
  4250. };
  4251. /**
  4252. * Updates the given vector "result" from the normalization of the given one.
  4253. */
  4254. Vector4.NormalizeToRef = function (vector, result) {
  4255. result.copyFrom(vector);
  4256. result.normalize();
  4257. };
  4258. Vector4.Minimize = function (left, right) {
  4259. var min = left.clone();
  4260. min.minimizeInPlace(right);
  4261. return min;
  4262. };
  4263. Vector4.Maximize = function (left, right) {
  4264. var max = left.clone();
  4265. max.maximizeInPlace(right);
  4266. return max;
  4267. };
  4268. /**
  4269. * Returns the distance (float) between the vectors "value1" and "value2".
  4270. */
  4271. Vector4.Distance = function (value1, value2) {
  4272. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4273. };
  4274. /**
  4275. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4276. */
  4277. Vector4.DistanceSquared = function (value1, value2) {
  4278. var x = value1.x - value2.x;
  4279. var y = value1.y - value2.y;
  4280. var z = value1.z - value2.z;
  4281. var w = value1.w - value2.w;
  4282. return (x * x) + (y * y) + (z * z) + (w * w);
  4283. };
  4284. /**
  4285. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4286. */
  4287. Vector4.Center = function (value1, value2) {
  4288. var center = value1.add(value2);
  4289. center.scaleInPlace(0.5);
  4290. return center;
  4291. };
  4292. /**
  4293. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4294. * This methods computes transformed normalized direction vectors only.
  4295. */
  4296. Vector4.TransformNormal = function (vector, transformation) {
  4297. var result = Vector4.Zero();
  4298. Vector4.TransformNormalToRef(vector, transformation, result);
  4299. return result;
  4300. };
  4301. /**
  4302. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4303. * This methods computes transformed normalized direction vectors only.
  4304. */
  4305. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4306. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4307. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4308. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4309. result.x = x;
  4310. result.y = y;
  4311. result.z = z;
  4312. result.w = vector.w;
  4313. };
  4314. /**
  4315. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4316. * This methods computes transformed normalized direction vectors only.
  4317. */
  4318. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4319. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4320. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4321. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4322. result.w = w;
  4323. };
  4324. return Vector4;
  4325. }());
  4326. BABYLON.Vector4 = Vector4;
  4327. var Size = /** @class */ (function () {
  4328. /**
  4329. * Creates a Size object from the given width and height (floats).
  4330. */
  4331. function Size(width, height) {
  4332. this.width = width;
  4333. this.height = height;
  4334. }
  4335. // Returns a string with the Size width and height.
  4336. Size.prototype.toString = function () {
  4337. return "{W: " + this.width + ", H: " + this.height + "}";
  4338. };
  4339. /**
  4340. * Returns the string "Size"
  4341. */
  4342. Size.prototype.getClassName = function () {
  4343. return "Size";
  4344. };
  4345. /**
  4346. * Returns the Size hash code.
  4347. */
  4348. Size.prototype.getHashCode = function () {
  4349. var hash = this.width || 0;
  4350. hash = (hash * 397) ^ (this.height || 0);
  4351. return hash;
  4352. };
  4353. /**
  4354. * Updates the current size from the given one.
  4355. * Returns the updated Size.
  4356. */
  4357. Size.prototype.copyFrom = function (src) {
  4358. this.width = src.width;
  4359. this.height = src.height;
  4360. };
  4361. /**
  4362. * Updates in place the current Size from the given floats.
  4363. * Returns the updated Size.
  4364. */
  4365. Size.prototype.copyFromFloats = function (width, height) {
  4366. this.width = width;
  4367. this.height = height;
  4368. return this;
  4369. };
  4370. /**
  4371. * Updates in place the current Size from the given floats.
  4372. * Returns the updated Size.
  4373. */
  4374. Size.prototype.set = function (width, height) {
  4375. return this.copyFromFloats(width, height);
  4376. };
  4377. /**
  4378. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4379. */
  4380. Size.prototype.multiplyByFloats = function (w, h) {
  4381. return new Size(this.width * w, this.height * h);
  4382. };
  4383. /**
  4384. * Returns a new Size copied from the given one.
  4385. */
  4386. Size.prototype.clone = function () {
  4387. return new Size(this.width, this.height);
  4388. };
  4389. /**
  4390. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4391. */
  4392. Size.prototype.equals = function (other) {
  4393. if (!other) {
  4394. return false;
  4395. }
  4396. return (this.width === other.width) && (this.height === other.height);
  4397. };
  4398. Object.defineProperty(Size.prototype, "surface", {
  4399. /**
  4400. * Returns the surface of the Size : width * height (float).
  4401. */
  4402. get: function () {
  4403. return this.width * this.height;
  4404. },
  4405. enumerable: true,
  4406. configurable: true
  4407. });
  4408. /**
  4409. * Returns a new Size set to (0.0, 0.0)
  4410. */
  4411. Size.Zero = function () {
  4412. return new Size(0.0, 0.0);
  4413. };
  4414. /**
  4415. * Returns a new Size set as the addition result of the current Size and the given one.
  4416. */
  4417. Size.prototype.add = function (otherSize) {
  4418. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4419. return r;
  4420. };
  4421. /**
  4422. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4423. */
  4424. Size.prototype.subtract = function (otherSize) {
  4425. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4426. return r;
  4427. };
  4428. /**
  4429. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4430. */
  4431. Size.Lerp = function (start, end, amount) {
  4432. var w = start.width + ((end.width - start.width) * amount);
  4433. var h = start.height + ((end.height - start.height) * amount);
  4434. return new Size(w, h);
  4435. };
  4436. return Size;
  4437. }());
  4438. BABYLON.Size = Size;
  4439. /**
  4440. * Class used to store quaternion data
  4441. * @see https://en.wikipedia.org/wiki/Quaternion
  4442. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4443. */
  4444. var Quaternion = /** @class */ (function () {
  4445. /**
  4446. * Creates a new Quaternion from the given floats
  4447. * @param x defines the first component (0 by default)
  4448. * @param y defines the second component (0 by default)
  4449. * @param z defines the third component (0 by default)
  4450. * @param w defines the fourth component (1.0 by default)
  4451. */
  4452. function Quaternion(
  4453. /** defines the first component (0 by default) */
  4454. x,
  4455. /** defines the second component (0 by default) */
  4456. y,
  4457. /** defines the third component (0 by default) */
  4458. z,
  4459. /** defines the fourth component (1.0 by default) */
  4460. w) {
  4461. if (x === void 0) { x = 0.0; }
  4462. if (y === void 0) { y = 0.0; }
  4463. if (z === void 0) { z = 0.0; }
  4464. if (w === void 0) { w = 1.0; }
  4465. this.x = x;
  4466. this.y = y;
  4467. this.z = z;
  4468. this.w = w;
  4469. }
  4470. /**
  4471. * Gets a string representation for the current quaternion
  4472. * @returns a string with the Quaternion coordinates
  4473. */
  4474. Quaternion.prototype.toString = function () {
  4475. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4476. };
  4477. /**
  4478. * Gets the class name of the quaternion
  4479. * @returns the string "Quaternion"
  4480. */
  4481. Quaternion.prototype.getClassName = function () {
  4482. return "Quaternion";
  4483. };
  4484. /**
  4485. * Gets a hash code for this quaternion
  4486. * @returns the quaternion hash code
  4487. */
  4488. Quaternion.prototype.getHashCode = function () {
  4489. var hash = this.x || 0;
  4490. hash = (hash * 397) ^ (this.y || 0);
  4491. hash = (hash * 397) ^ (this.z || 0);
  4492. hash = (hash * 397) ^ (this.w || 0);
  4493. return hash;
  4494. };
  4495. /**
  4496. * Copy the quaternion to an array
  4497. * @returns a new array populated with 4 elements from the quaternion coordinates
  4498. */
  4499. Quaternion.prototype.asArray = function () {
  4500. return [this.x, this.y, this.z, this.w];
  4501. };
  4502. /**
  4503. * Check if two quaternions are equals
  4504. * @param otherQuaternion defines the second operand
  4505. * @return true if the current quaternion and the given one coordinates are strictly equals
  4506. */
  4507. Quaternion.prototype.equals = function (otherQuaternion) {
  4508. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4509. };
  4510. /**
  4511. * Clone the current quaternion
  4512. * @returns a new quaternion copied from the current one
  4513. */
  4514. Quaternion.prototype.clone = function () {
  4515. return new Quaternion(this.x, this.y, this.z, this.w);
  4516. };
  4517. /**
  4518. * Copy a quaternion to the current one
  4519. * @param other defines the other quaternion
  4520. * @returns the updated current quaternion
  4521. */
  4522. Quaternion.prototype.copyFrom = function (other) {
  4523. this.x = other.x;
  4524. this.y = other.y;
  4525. this.z = other.z;
  4526. this.w = other.w;
  4527. return this;
  4528. };
  4529. /**
  4530. * Updates the current quaternion with the given float coordinates
  4531. * @param x defines the x coordinate
  4532. * @param y defines the y coordinate
  4533. * @param z defines the z coordinate
  4534. * @param w defines the w coordinate
  4535. * @returns the updated current quaternion
  4536. */
  4537. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4538. this.x = x;
  4539. this.y = y;
  4540. this.z = z;
  4541. this.w = w;
  4542. return this;
  4543. };
  4544. /**
  4545. * Updates the current quaternion from the given float coordinates
  4546. * @param x defines the x coordinate
  4547. * @param y defines the y coordinate
  4548. * @param z defines the z coordinate
  4549. * @param w defines the w coordinate
  4550. * @returns the updated current quaternion
  4551. */
  4552. Quaternion.prototype.set = function (x, y, z, w) {
  4553. return this.copyFromFloats(x, y, z, w);
  4554. };
  4555. /**
  4556. * Adds two quaternions
  4557. * @param other defines the second operand
  4558. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4559. */
  4560. Quaternion.prototype.add = function (other) {
  4561. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4562. };
  4563. /**
  4564. * Add a quaternion to the current one
  4565. * @param other defines the quaternion to add
  4566. * @returns the current quaternion
  4567. */
  4568. Quaternion.prototype.addInPlace = function (other) {
  4569. this.x += other.x;
  4570. this.y += other.y;
  4571. this.z += other.z;
  4572. this.w += other.w;
  4573. return this;
  4574. };
  4575. /**
  4576. * Subtract two quaternions
  4577. * @param other defines the second operand
  4578. * @returns a new quaternion as the subtraction result of the given one from the current one
  4579. */
  4580. Quaternion.prototype.subtract = function (other) {
  4581. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4582. };
  4583. /**
  4584. * Multiplies the current quaternion by a scale factor
  4585. * @param value defines the scale factor
  4586. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4587. */
  4588. Quaternion.prototype.scale = function (value) {
  4589. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4590. };
  4591. /**
  4592. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4593. * @param scale defines the scale factor
  4594. * @param result defines the Quaternion object where to store the result
  4595. * @returns the unmodified current quaternion
  4596. */
  4597. Quaternion.prototype.scaleToRef = function (scale, result) {
  4598. result.x = this.x * scale;
  4599. result.y = this.y * scale;
  4600. result.z = this.z * scale;
  4601. result.w = this.w * scale;
  4602. return this;
  4603. };
  4604. /**
  4605. * Multiplies in place the current quaternion by a scale factor
  4606. * @param value defines the scale factor
  4607. * @returns the current modified quaternion
  4608. */
  4609. Quaternion.prototype.scaleInPlace = function (value) {
  4610. this.x *= value;
  4611. this.y *= value;
  4612. this.z *= value;
  4613. this.w *= value;
  4614. return this;
  4615. };
  4616. /**
  4617. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4618. * @param scale defines the scale factor
  4619. * @param result defines the Quaternion object where to store the result
  4620. * @returns the unmodified current quaternion
  4621. */
  4622. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4623. result.x += this.x * scale;
  4624. result.y += this.y * scale;
  4625. result.z += this.z * scale;
  4626. result.w += this.w * scale;
  4627. return this;
  4628. };
  4629. /**
  4630. * Multiplies two quaternions
  4631. * @param q1 defines the second operand
  4632. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4633. */
  4634. Quaternion.prototype.multiply = function (q1) {
  4635. var result = new Quaternion(0, 0, 0, 1.0);
  4636. this.multiplyToRef(q1, result);
  4637. return result;
  4638. };
  4639. /**
  4640. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4641. * @param q1 defines the second operand
  4642. * @param result defines the target quaternion
  4643. * @returns the current quaternion
  4644. */
  4645. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4646. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4647. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4648. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4649. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4650. result.copyFromFloats(x, y, z, w);
  4651. return this;
  4652. };
  4653. /**
  4654. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4655. * @param q1 defines the second operand
  4656. * @returns the currentupdated quaternion
  4657. */
  4658. Quaternion.prototype.multiplyInPlace = function (q1) {
  4659. this.multiplyToRef(q1, this);
  4660. return this;
  4661. };
  4662. /**
  4663. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4664. * @param ref defines the target quaternion
  4665. * @returns the current quaternion
  4666. */
  4667. Quaternion.prototype.conjugateToRef = function (ref) {
  4668. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4669. return this;
  4670. };
  4671. /**
  4672. * Conjugates in place (1-q) the current quaternion
  4673. * @returns the current updated quaternion
  4674. */
  4675. Quaternion.prototype.conjugateInPlace = function () {
  4676. this.x *= -1;
  4677. this.y *= -1;
  4678. this.z *= -1;
  4679. return this;
  4680. };
  4681. /**
  4682. * Conjugates in place (1-q) the current quaternion
  4683. * @returns a new quaternion
  4684. */
  4685. Quaternion.prototype.conjugate = function () {
  4686. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4687. return result;
  4688. };
  4689. /**
  4690. * Gets length of current quaternion
  4691. * @returns the quaternion length (float)
  4692. */
  4693. Quaternion.prototype.length = function () {
  4694. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4695. };
  4696. /**
  4697. * Normalize in place the current quaternion
  4698. * @returns the current updated quaternion
  4699. */
  4700. Quaternion.prototype.normalize = function () {
  4701. var length = 1.0 / this.length();
  4702. this.x *= length;
  4703. this.y *= length;
  4704. this.z *= length;
  4705. this.w *= length;
  4706. return this;
  4707. };
  4708. /**
  4709. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4710. * @param order is a reserved parameter and is ignore for now
  4711. * @returns a new Vector3 containing the Euler angles
  4712. */
  4713. Quaternion.prototype.toEulerAngles = function (order) {
  4714. if (order === void 0) { order = "YZX"; }
  4715. var result = Vector3.Zero();
  4716. this.toEulerAnglesToRef(result, order);
  4717. return result;
  4718. };
  4719. /**
  4720. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4721. * @param result defines the vector which will be filled with the Euler angles
  4722. * @param order is a reserved parameter and is ignore for now
  4723. * @returns the current unchanged quaternion
  4724. */
  4725. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4726. if (order === void 0) { order = "YZX"; }
  4727. var qz = this.z;
  4728. var qx = this.x;
  4729. var qy = this.y;
  4730. var qw = this.w;
  4731. var sqw = qw * qw;
  4732. var sqz = qz * qz;
  4733. var sqx = qx * qx;
  4734. var sqy = qy * qy;
  4735. var zAxisY = qy * qz - qx * qw;
  4736. var limit = .4999999;
  4737. if (zAxisY < -limit) {
  4738. result.y = 2 * Math.atan2(qy, qw);
  4739. result.x = Math.PI / 2;
  4740. result.z = 0;
  4741. }
  4742. else if (zAxisY > limit) {
  4743. result.y = 2 * Math.atan2(qy, qw);
  4744. result.x = -Math.PI / 2;
  4745. result.z = 0;
  4746. }
  4747. else {
  4748. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4749. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4750. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4751. }
  4752. return this;
  4753. };
  4754. /**
  4755. * Updates the given rotation matrix with the current quaternion values
  4756. * @param result defines the target matrix
  4757. * @returns the current unchanged quaternion
  4758. */
  4759. Quaternion.prototype.toRotationMatrix = function (result) {
  4760. var xx = this.x * this.x;
  4761. var yy = this.y * this.y;
  4762. var zz = this.z * this.z;
  4763. var xy = this.x * this.y;
  4764. var zw = this.z * this.w;
  4765. var zx = this.z * this.x;
  4766. var yw = this.y * this.w;
  4767. var yz = this.y * this.z;
  4768. var xw = this.x * this.w;
  4769. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4770. result.m[1] = 2.0 * (xy + zw);
  4771. result.m[2] = 2.0 * (zx - yw);
  4772. result.m[3] = 0;
  4773. result.m[4] = 2.0 * (xy - zw);
  4774. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4775. result.m[6] = 2.0 * (yz + xw);
  4776. result.m[7] = 0;
  4777. result.m[8] = 2.0 * (zx + yw);
  4778. result.m[9] = 2.0 * (yz - xw);
  4779. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4780. result.m[11] = 0;
  4781. result.m[12] = 0;
  4782. result.m[13] = 0;
  4783. result.m[14] = 0;
  4784. result.m[15] = 1.0;
  4785. result._markAsUpdated();
  4786. return this;
  4787. };
  4788. /**
  4789. * Updates the current quaternion from the given rotation matrix values
  4790. * @param matrix defines the source matrix
  4791. * @returns the current updated quaternion
  4792. */
  4793. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4794. Quaternion.FromRotationMatrixToRef(matrix, this);
  4795. return this;
  4796. };
  4797. // Statics
  4798. /**
  4799. * Creates a new quaternion from a rotation matrix
  4800. * @param matrix defines the source matrix
  4801. * @returns a new quaternion created from the given rotation matrix values
  4802. */
  4803. Quaternion.FromRotationMatrix = function (matrix) {
  4804. var result = new Quaternion();
  4805. Quaternion.FromRotationMatrixToRef(matrix, result);
  4806. return result;
  4807. };
  4808. /**
  4809. * Updates the given quaternion with the given rotation matrix values
  4810. * @param matrix defines the source matrix
  4811. * @param result defines the target quaternion
  4812. */
  4813. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4814. var data = matrix.m;
  4815. var m11 = data[0], m12 = data[4], m13 = data[8];
  4816. var m21 = data[1], m22 = data[5], m23 = data[9];
  4817. var m31 = data[2], m32 = data[6], m33 = data[10];
  4818. var trace = m11 + m22 + m33;
  4819. var s;
  4820. if (trace > 0) {
  4821. s = 0.5 / Math.sqrt(trace + 1.0);
  4822. result.w = 0.25 / s;
  4823. result.x = (m32 - m23) * s;
  4824. result.y = (m13 - m31) * s;
  4825. result.z = (m21 - m12) * s;
  4826. }
  4827. else if (m11 > m22 && m11 > m33) {
  4828. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4829. result.w = (m32 - m23) / s;
  4830. result.x = 0.25 * s;
  4831. result.y = (m12 + m21) / s;
  4832. result.z = (m13 + m31) / s;
  4833. }
  4834. else if (m22 > m33) {
  4835. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4836. result.w = (m13 - m31) / s;
  4837. result.x = (m12 + m21) / s;
  4838. result.y = 0.25 * s;
  4839. result.z = (m23 + m32) / s;
  4840. }
  4841. else {
  4842. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4843. result.w = (m21 - m12) / s;
  4844. result.x = (m13 + m31) / s;
  4845. result.y = (m23 + m32) / s;
  4846. result.z = 0.25 * s;
  4847. }
  4848. };
  4849. /**
  4850. * Returns the dot product (float) between the quaternions "left" and "right"
  4851. * @param left defines the left operand
  4852. * @param right defines the right operand
  4853. * @returns the dot product
  4854. */
  4855. Quaternion.Dot = function (left, right) {
  4856. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4857. };
  4858. /**
  4859. * Checks if the two quaternions are close to each other
  4860. * @param quat0 defines the first quaternion to check
  4861. * @param quat1 defines the second quaternion to check
  4862. * @returns true if the two quaternions are close to each other
  4863. */
  4864. Quaternion.AreClose = function (quat0, quat1) {
  4865. var dot = Quaternion.Dot(quat0, quat1);
  4866. return dot >= 0;
  4867. };
  4868. /**
  4869. * Creates an empty quaternion
  4870. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4871. */
  4872. Quaternion.Zero = function () {
  4873. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4874. };
  4875. /**
  4876. * Inverse a given quaternion
  4877. * @param q defines the source quaternion
  4878. * @returns a new quaternion as the inverted current quaternion
  4879. */
  4880. Quaternion.Inverse = function (q) {
  4881. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4882. };
  4883. /**
  4884. * Creates an identity quaternion
  4885. * @returns the identity quaternion
  4886. */
  4887. Quaternion.Identity = function () {
  4888. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4889. };
  4890. /**
  4891. * Gets a boolean indicating if the given quaternion is identity
  4892. * @param quaternion defines the quaternion to check
  4893. * @returns true if the quaternion is identity
  4894. */
  4895. Quaternion.IsIdentity = function (quaternion) {
  4896. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4897. };
  4898. /**
  4899. * Creates a quaternion from a rotation around an axis
  4900. * @param axis defines the axis to use
  4901. * @param angle defines the angle to use
  4902. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4903. */
  4904. Quaternion.RotationAxis = function (axis, angle) {
  4905. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4906. };
  4907. /**
  4908. * Creates a rotation around an axis and stores it into the given quaternion
  4909. * @param axis defines the axis to use
  4910. * @param angle defines the angle to use
  4911. * @param result defines the target quaternion
  4912. * @returns the target quaternion
  4913. */
  4914. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4915. var sin = Math.sin(angle / 2);
  4916. axis.normalize();
  4917. result.w = Math.cos(angle / 2);
  4918. result.x = axis.x * sin;
  4919. result.y = axis.y * sin;
  4920. result.z = axis.z * sin;
  4921. return result;
  4922. };
  4923. /**
  4924. * Creates a new quaternion from data stored into an array
  4925. * @param array defines the data source
  4926. * @param offset defines the offset in the source array where the data starts
  4927. * @returns a new quaternion
  4928. */
  4929. Quaternion.FromArray = function (array, offset) {
  4930. if (!offset) {
  4931. offset = 0;
  4932. }
  4933. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4934. };
  4935. /**
  4936. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4937. * @param yaw defines the rotation around Y axis
  4938. * @param pitch defines the rotation around X axis
  4939. * @param roll defines the rotation around Z axis
  4940. * @returns the new quaternion
  4941. */
  4942. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4943. var q = new Quaternion();
  4944. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4945. return q;
  4946. };
  4947. /**
  4948. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4949. * @param yaw defines the rotation around Y axis
  4950. * @param pitch defines the rotation around X axis
  4951. * @param roll defines the rotation around Z axis
  4952. * @param result defines the target quaternion
  4953. */
  4954. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4955. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4956. var halfRoll = roll * 0.5;
  4957. var halfPitch = pitch * 0.5;
  4958. var halfYaw = yaw * 0.5;
  4959. var sinRoll = Math.sin(halfRoll);
  4960. var cosRoll = Math.cos(halfRoll);
  4961. var sinPitch = Math.sin(halfPitch);
  4962. var cosPitch = Math.cos(halfPitch);
  4963. var sinYaw = Math.sin(halfYaw);
  4964. var cosYaw = Math.cos(halfYaw);
  4965. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4966. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4967. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4968. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4969. };
  4970. /**
  4971. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4972. * @param alpha defines the rotation around first axis
  4973. * @param beta defines the rotation around second axis
  4974. * @param gamma defines the rotation around third axis
  4975. * @returns the new quaternion
  4976. */
  4977. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4978. var result = new Quaternion();
  4979. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4980. return result;
  4981. };
  4982. /**
  4983. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4984. * @param alpha defines the rotation around first axis
  4985. * @param beta defines the rotation around second axis
  4986. * @param gamma defines the rotation around third axis
  4987. * @param result defines the target quaternion
  4988. */
  4989. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4990. // Produces a quaternion from Euler angles in the z-x-z orientation
  4991. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4992. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4993. var halfBeta = beta * 0.5;
  4994. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4995. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4996. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4997. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4998. };
  4999. /**
  5000. * 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)
  5001. * @param axis1 defines the first axis
  5002. * @param axis2 defines the second axis
  5003. * @param axis3 defines the third axis
  5004. * @returns the new quaternion
  5005. */
  5006. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5007. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5008. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5009. return quat;
  5010. };
  5011. /**
  5012. * 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
  5013. * @param axis1 defines the first axis
  5014. * @param axis2 defines the second axis
  5015. * @param axis3 defines the third axis
  5016. * @param ref defines the target quaternion
  5017. */
  5018. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5019. var rotMat = MathTmp.Matrix[0];
  5020. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5021. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5022. };
  5023. /**
  5024. * Interpolates between two quaternions
  5025. * @param left defines first quaternion
  5026. * @param right defines second quaternion
  5027. * @param amount defines the gradient to use
  5028. * @returns the new interpolated quaternion
  5029. */
  5030. Quaternion.Slerp = function (left, right, amount) {
  5031. var result = Quaternion.Identity();
  5032. Quaternion.SlerpToRef(left, right, amount, result);
  5033. return result;
  5034. };
  5035. /**
  5036. * Interpolates between two quaternions and stores it into a target quaternion
  5037. * @param left defines first quaternion
  5038. * @param right defines second quaternion
  5039. * @param amount defines the gradient to use
  5040. * @param result defines the target quaternion
  5041. */
  5042. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5043. var num2;
  5044. var num3;
  5045. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5046. var flag = false;
  5047. if (num4 < 0) {
  5048. flag = true;
  5049. num4 = -num4;
  5050. }
  5051. if (num4 > 0.999999) {
  5052. num3 = 1 - amount;
  5053. num2 = flag ? -amount : amount;
  5054. }
  5055. else {
  5056. var num5 = Math.acos(num4);
  5057. var num6 = (1.0 / Math.sin(num5));
  5058. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5059. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5060. }
  5061. result.x = (num3 * left.x) + (num2 * right.x);
  5062. result.y = (num3 * left.y) + (num2 * right.y);
  5063. result.z = (num3 * left.z) + (num2 * right.z);
  5064. result.w = (num3 * left.w) + (num2 * right.w);
  5065. };
  5066. /**
  5067. * Interpolate between two quaternions using Hermite interpolation
  5068. * @param value1 defines first quaternion
  5069. * @param tangent1 defines the incoming tangent
  5070. * @param value2 defines second quaternion
  5071. * @param tangent2 defines the outgoing tangent
  5072. * @param amount defines the target quaternion
  5073. * @returns the new interpolated quaternion
  5074. */
  5075. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5076. var squared = amount * amount;
  5077. var cubed = amount * squared;
  5078. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5079. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5080. var part3 = (cubed - (2.0 * squared)) + amount;
  5081. var part4 = cubed - squared;
  5082. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5083. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5084. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5085. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5086. return new Quaternion(x, y, z, w);
  5087. };
  5088. return Quaternion;
  5089. }());
  5090. BABYLON.Quaternion = Quaternion;
  5091. /**
  5092. * Class used to store matrix data (4x4)
  5093. */
  5094. var Matrix = /** @class */ (function () {
  5095. /**
  5096. * Creates an empty matrix (filled with zeros)
  5097. */
  5098. function Matrix() {
  5099. this._isIdentity = false;
  5100. this._isIdentityDirty = true;
  5101. /**
  5102. * Gets or sets the internal data of the matrix
  5103. */
  5104. this.m = new Float32Array(16);
  5105. this._markAsUpdated();
  5106. }
  5107. /** @hidden */
  5108. Matrix.prototype._markAsUpdated = function () {
  5109. this.updateFlag = Matrix._updateFlagSeed++;
  5110. this._isIdentityDirty = true;
  5111. };
  5112. // Properties
  5113. /**
  5114. * Check if the current matrix is indentity
  5115. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5116. * @returns true is the matrix is the identity matrix
  5117. */
  5118. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5119. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5120. if (this._isIdentityDirty) {
  5121. this._isIdentityDirty = false;
  5122. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5123. this._isIdentity = false;
  5124. }
  5125. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5126. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5127. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5128. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5129. this._isIdentity = false;
  5130. }
  5131. else {
  5132. this._isIdentity = true;
  5133. }
  5134. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5135. this._isIdentity = false;
  5136. }
  5137. }
  5138. return this._isIdentity;
  5139. };
  5140. /**
  5141. * Gets the determinant of the matrix
  5142. * @returns the matrix determinant
  5143. */
  5144. Matrix.prototype.determinant = function () {
  5145. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5146. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5147. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5148. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5149. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5150. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5151. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5152. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5153. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5154. };
  5155. // Methods
  5156. /**
  5157. * Returns the matrix as a Float32Array
  5158. * @returns the matrix underlying array
  5159. */
  5160. Matrix.prototype.toArray = function () {
  5161. return this.m;
  5162. };
  5163. /**
  5164. * Returns the matrix as a Float32Array
  5165. * @returns the matrix underlying array.
  5166. */
  5167. Matrix.prototype.asArray = function () {
  5168. return this.toArray();
  5169. };
  5170. /**
  5171. * Inverts the current matrix in place
  5172. * @returns the current inverted matrix
  5173. */
  5174. Matrix.prototype.invert = function () {
  5175. this.invertToRef(this);
  5176. return this;
  5177. };
  5178. /**
  5179. * Sets all the matrix elements to zero
  5180. * @returns the current matrix
  5181. */
  5182. Matrix.prototype.reset = function () {
  5183. for (var index = 0; index < 16; index++) {
  5184. this.m[index] = 0.0;
  5185. }
  5186. this._markAsUpdated();
  5187. return this;
  5188. };
  5189. /**
  5190. * Adds the current matrix with a second one
  5191. * @param other defines the matrix to add
  5192. * @returns a new matrix as the addition of the current matrix and the given one
  5193. */
  5194. Matrix.prototype.add = function (other) {
  5195. var result = new Matrix();
  5196. this.addToRef(other, result);
  5197. return result;
  5198. };
  5199. /**
  5200. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5201. * @param other defines the matrix to add
  5202. * @param result defines the target matrix
  5203. * @returns the current matrix
  5204. */
  5205. Matrix.prototype.addToRef = function (other, result) {
  5206. for (var index = 0; index < 16; index++) {
  5207. result.m[index] = this.m[index] + other.m[index];
  5208. }
  5209. result._markAsUpdated();
  5210. return this;
  5211. };
  5212. /**
  5213. * Adds in place the given matrix to the current matrix
  5214. * @param other defines the second operand
  5215. * @returns the current updated matrix
  5216. */
  5217. Matrix.prototype.addToSelf = function (other) {
  5218. for (var index = 0; index < 16; index++) {
  5219. this.m[index] += other.m[index];
  5220. }
  5221. this._markAsUpdated();
  5222. return this;
  5223. };
  5224. /**
  5225. * Sets the given matrix to the current inverted Matrix
  5226. * @param other defines the target matrix
  5227. * @returns the unmodified current matrix
  5228. */
  5229. Matrix.prototype.invertToRef = function (other) {
  5230. var l1 = this.m[0];
  5231. var l2 = this.m[1];
  5232. var l3 = this.m[2];
  5233. var l4 = this.m[3];
  5234. var l5 = this.m[4];
  5235. var l6 = this.m[5];
  5236. var l7 = this.m[6];
  5237. var l8 = this.m[7];
  5238. var l9 = this.m[8];
  5239. var l10 = this.m[9];
  5240. var l11 = this.m[10];
  5241. var l12 = this.m[11];
  5242. var l13 = this.m[12];
  5243. var l14 = this.m[13];
  5244. var l15 = this.m[14];
  5245. var l16 = this.m[15];
  5246. var l17 = (l11 * l16) - (l12 * l15);
  5247. var l18 = (l10 * l16) - (l12 * l14);
  5248. var l19 = (l10 * l15) - (l11 * l14);
  5249. var l20 = (l9 * l16) - (l12 * l13);
  5250. var l21 = (l9 * l15) - (l11 * l13);
  5251. var l22 = (l9 * l14) - (l10 * l13);
  5252. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5253. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5254. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5255. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5256. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5257. var l28 = (l7 * l16) - (l8 * l15);
  5258. var l29 = (l6 * l16) - (l8 * l14);
  5259. var l30 = (l6 * l15) - (l7 * l14);
  5260. var l31 = (l5 * l16) - (l8 * l13);
  5261. var l32 = (l5 * l15) - (l7 * l13);
  5262. var l33 = (l5 * l14) - (l6 * l13);
  5263. var l34 = (l7 * l12) - (l8 * l11);
  5264. var l35 = (l6 * l12) - (l8 * l10);
  5265. var l36 = (l6 * l11) - (l7 * l10);
  5266. var l37 = (l5 * l12) - (l8 * l9);
  5267. var l38 = (l5 * l11) - (l7 * l9);
  5268. var l39 = (l5 * l10) - (l6 * l9);
  5269. other.m[0] = l23 * l27;
  5270. other.m[4] = l24 * l27;
  5271. other.m[8] = l25 * l27;
  5272. other.m[12] = l26 * l27;
  5273. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5274. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5275. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5276. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5277. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5278. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5279. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5280. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5281. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5282. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5283. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5284. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5285. other._markAsUpdated();
  5286. return this;
  5287. };
  5288. /**
  5289. * Inserts the translation vector (using 3 floats) in the current matrix
  5290. * @param x defines the 1st component of the translation
  5291. * @param y defines the 2nd component of the translation
  5292. * @param z defines the 3rd component of the translation
  5293. * @returns the current updated matrix
  5294. */
  5295. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5296. this.m[12] = x;
  5297. this.m[13] = y;
  5298. this.m[14] = z;
  5299. this._markAsUpdated();
  5300. return this;
  5301. };
  5302. /**
  5303. * Inserts the translation vector in the current matrix
  5304. * @param vector3 defines the translation to insert
  5305. * @returns the current updated matrix
  5306. */
  5307. Matrix.prototype.setTranslation = function (vector3) {
  5308. this.m[12] = vector3.x;
  5309. this.m[13] = vector3.y;
  5310. this.m[14] = vector3.z;
  5311. this._markAsUpdated();
  5312. return this;
  5313. };
  5314. /**
  5315. * Gets the translation value of the current matrix
  5316. * @returns a new Vector3 as the extracted translation from the matrix
  5317. */
  5318. Matrix.prototype.getTranslation = function () {
  5319. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5320. };
  5321. /**
  5322. * Fill a Vector3 with the extracted translation from the matrix
  5323. * @param result defines the Vector3 where to store the translation
  5324. * @returns the current matrix
  5325. */
  5326. Matrix.prototype.getTranslationToRef = function (result) {
  5327. result.x = this.m[12];
  5328. result.y = this.m[13];
  5329. result.z = this.m[14];
  5330. return this;
  5331. };
  5332. /**
  5333. * Remove rotation and scaling part from the matrix
  5334. * @returns the updated matrix
  5335. */
  5336. Matrix.prototype.removeRotationAndScaling = function () {
  5337. this.setRowFromFloats(0, 1, 0, 0, 0);
  5338. this.setRowFromFloats(1, 0, 1, 0, 0);
  5339. this.setRowFromFloats(2, 0, 0, 1, 0);
  5340. return this;
  5341. };
  5342. /**
  5343. * Multiply two matrices
  5344. * @param other defines the second operand
  5345. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5346. */
  5347. Matrix.prototype.multiply = function (other) {
  5348. var result = new Matrix();
  5349. this.multiplyToRef(other, result);
  5350. return result;
  5351. };
  5352. /**
  5353. * Copy the current matrix from the given one
  5354. * @param other defines the source matrix
  5355. * @returns the current updated matrix
  5356. */
  5357. Matrix.prototype.copyFrom = function (other) {
  5358. for (var index = 0; index < 16; index++) {
  5359. this.m[index] = other.m[index];
  5360. }
  5361. this._markAsUpdated();
  5362. return this;
  5363. };
  5364. /**
  5365. * Populates the given array from the starting index with the current matrix values
  5366. * @param array defines the target array
  5367. * @param offset defines the offset in the target array where to start storing values
  5368. * @returns the current matrix
  5369. */
  5370. Matrix.prototype.copyToArray = function (array, offset) {
  5371. if (offset === void 0) { offset = 0; }
  5372. for (var index = 0; index < 16; index++) {
  5373. array[offset + index] = this.m[index];
  5374. }
  5375. return this;
  5376. };
  5377. /**
  5378. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5379. * @param other defines the second operand
  5380. * @param result defines the matrix where to store the multiplication
  5381. * @returns the current matrix
  5382. */
  5383. Matrix.prototype.multiplyToRef = function (other, result) {
  5384. this.multiplyToArray(other, result.m, 0);
  5385. result._markAsUpdated();
  5386. return this;
  5387. };
  5388. /**
  5389. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5390. * @param other defines the second operand
  5391. * @param result defines the array where to store the multiplication
  5392. * @param offset defines the offset in the target array where to start storing values
  5393. * @returns the current matrix
  5394. */
  5395. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5396. var tm0 = this.m[0];
  5397. var tm1 = this.m[1];
  5398. var tm2 = this.m[2];
  5399. var tm3 = this.m[3];
  5400. var tm4 = this.m[4];
  5401. var tm5 = this.m[5];
  5402. var tm6 = this.m[6];
  5403. var tm7 = this.m[7];
  5404. var tm8 = this.m[8];
  5405. var tm9 = this.m[9];
  5406. var tm10 = this.m[10];
  5407. var tm11 = this.m[11];
  5408. var tm12 = this.m[12];
  5409. var tm13 = this.m[13];
  5410. var tm14 = this.m[14];
  5411. var tm15 = this.m[15];
  5412. var om0 = other.m[0];
  5413. var om1 = other.m[1];
  5414. var om2 = other.m[2];
  5415. var om3 = other.m[3];
  5416. var om4 = other.m[4];
  5417. var om5 = other.m[5];
  5418. var om6 = other.m[6];
  5419. var om7 = other.m[7];
  5420. var om8 = other.m[8];
  5421. var om9 = other.m[9];
  5422. var om10 = other.m[10];
  5423. var om11 = other.m[11];
  5424. var om12 = other.m[12];
  5425. var om13 = other.m[13];
  5426. var om14 = other.m[14];
  5427. var om15 = other.m[15];
  5428. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5429. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5430. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5431. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5432. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5433. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5434. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5435. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5436. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5437. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5438. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5439. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5440. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5441. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5442. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5443. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5444. return this;
  5445. };
  5446. /**
  5447. * Check equality between this matrix and a second one
  5448. * @param value defines the second matrix to compare
  5449. * @returns true is the current matrix and the given one values are strictly equal
  5450. */
  5451. Matrix.prototype.equals = function (value) {
  5452. return value &&
  5453. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5454. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5455. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5456. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5457. };
  5458. /**
  5459. * Clone the current matrix
  5460. * @returns a new matrix from the current matrix
  5461. */
  5462. Matrix.prototype.clone = function () {
  5463. 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]);
  5464. };
  5465. /**
  5466. * Returns the name of the current matrix class
  5467. * @returns the string "Matrix"
  5468. */
  5469. Matrix.prototype.getClassName = function () {
  5470. return "Matrix";
  5471. };
  5472. /**
  5473. * Gets the hash code of the current matrix
  5474. * @returns the hash code
  5475. */
  5476. Matrix.prototype.getHashCode = function () {
  5477. var hash = this.m[0] || 0;
  5478. for (var i = 1; i < 16; i++) {
  5479. hash = (hash * 397) ^ (this.m[i] || 0);
  5480. }
  5481. return hash;
  5482. };
  5483. /**
  5484. * Decomposes the current Matrix into a translation, rotation and scaling components
  5485. * @param scale defines the scale vector3 given as a reference to update
  5486. * @param rotation defines the rotation quaternion given as a reference to update
  5487. * @param translation defines the translation vector3 given as a reference to update
  5488. * @returns true if operation was successful
  5489. */
  5490. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5491. if (translation) {
  5492. translation.x = this.m[12];
  5493. translation.y = this.m[13];
  5494. translation.z = this.m[14];
  5495. }
  5496. scale = scale || MathTmp.Vector3[0];
  5497. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5498. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5499. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5500. if (this.determinant() <= 0) {
  5501. scale.y *= -1;
  5502. }
  5503. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5504. if (rotation) {
  5505. rotation.x = 0;
  5506. rotation.y = 0;
  5507. rotation.z = 0;
  5508. rotation.w = 1;
  5509. }
  5510. return false;
  5511. }
  5512. if (rotation) {
  5513. 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]);
  5514. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5515. }
  5516. return true;
  5517. };
  5518. /**
  5519. * Gets specific row of the matrix
  5520. * @param index defines the number of the row to get
  5521. * @returns the index-th row of the current matrix as a new Vector4
  5522. */
  5523. Matrix.prototype.getRow = function (index) {
  5524. if (index < 0 || index > 3) {
  5525. return null;
  5526. }
  5527. var i = index * 4;
  5528. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5529. };
  5530. /**
  5531. * Sets the index-th row of the current matrix to the vector4 values
  5532. * @param index defines the number of the row to set
  5533. * @param row defines the target vector4
  5534. * @returns the updated current matrix
  5535. */
  5536. Matrix.prototype.setRow = function (index, row) {
  5537. if (index < 0 || index > 3) {
  5538. return this;
  5539. }
  5540. var i = index * 4;
  5541. this.m[i + 0] = row.x;
  5542. this.m[i + 1] = row.y;
  5543. this.m[i + 2] = row.z;
  5544. this.m[i + 3] = row.w;
  5545. this._markAsUpdated();
  5546. return this;
  5547. };
  5548. /**
  5549. * Compute the transpose of the matrix
  5550. * @returns the new transposed matrix
  5551. */
  5552. Matrix.prototype.transpose = function () {
  5553. return Matrix.Transpose(this);
  5554. };
  5555. /**
  5556. * Compute the transpose of the matrix and store it in a given matrix
  5557. * @param result defines the target matrix
  5558. * @returns the current matrix
  5559. */
  5560. Matrix.prototype.transposeToRef = function (result) {
  5561. Matrix.TransposeToRef(this, result);
  5562. return this;
  5563. };
  5564. /**
  5565. * Sets the index-th row of the current matrix with the given 4 x float values
  5566. * @param index defines the row index
  5567. * @param x defines the x component to set
  5568. * @param y defines the y component to set
  5569. * @param z defines the z component to set
  5570. * @param w defines the w component to set
  5571. * @returns the updated current matrix
  5572. */
  5573. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5574. if (index < 0 || index > 3) {
  5575. return this;
  5576. }
  5577. var i = index * 4;
  5578. this.m[i + 0] = x;
  5579. this.m[i + 1] = y;
  5580. this.m[i + 2] = z;
  5581. this.m[i + 3] = w;
  5582. this._markAsUpdated();
  5583. return this;
  5584. };
  5585. /**
  5586. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5587. * @param scale defines the scale factor
  5588. * @returns a new matrix
  5589. */
  5590. Matrix.prototype.scale = function (scale) {
  5591. var result = new Matrix();
  5592. this.scaleToRef(scale, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * Scale the current matrix values by a factor to a given result matrix
  5597. * @param scale defines the scale factor
  5598. * @param result defines the matrix to store the result
  5599. * @returns the current matrix
  5600. */
  5601. Matrix.prototype.scaleToRef = function (scale, result) {
  5602. for (var index = 0; index < 16; index++) {
  5603. result.m[index] = this.m[index] * scale;
  5604. }
  5605. result._markAsUpdated();
  5606. return this;
  5607. };
  5608. /**
  5609. * Scale the current matrix values by a factor and add the result to a given matrix
  5610. * @param scale defines the scale factor
  5611. * @param result defines the Matrix to store the result
  5612. * @returns the current matrix
  5613. */
  5614. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5615. for (var index = 0; index < 16; index++) {
  5616. result.m[index] += this.m[index] * scale;
  5617. }
  5618. result._markAsUpdated();
  5619. return this;
  5620. };
  5621. /**
  5622. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5623. * @param ref matrix to store the result
  5624. */
  5625. Matrix.prototype.toNormalMatrix = function (ref) {
  5626. this.invertToRef(ref);
  5627. ref.transpose();
  5628. var m = ref.m;
  5629. 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);
  5630. };
  5631. /**
  5632. * Gets only rotation part of the current matrix
  5633. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5634. */
  5635. Matrix.prototype.getRotationMatrix = function () {
  5636. var result = Matrix.Identity();
  5637. this.getRotationMatrixToRef(result);
  5638. return result;
  5639. };
  5640. /**
  5641. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5642. * @param result defines the target matrix to store data to
  5643. * @returns the current matrix
  5644. */
  5645. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5646. var m = this.m;
  5647. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5648. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5649. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5650. if (this.determinant() <= 0) {
  5651. sy *= -1;
  5652. }
  5653. if (sx === 0 || sy === 0 || sz === 0) {
  5654. Matrix.IdentityToRef(result);
  5655. }
  5656. else {
  5657. 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);
  5658. }
  5659. return this;
  5660. };
  5661. // Statics
  5662. /**
  5663. * Creates a matrix from an array
  5664. * @param array defines the source array
  5665. * @param offset defines an offset in the source array
  5666. * @returns a new Matrix set from the starting index of the given array
  5667. */
  5668. Matrix.FromArray = function (array, offset) {
  5669. var result = new Matrix();
  5670. if (!offset) {
  5671. offset = 0;
  5672. }
  5673. Matrix.FromArrayToRef(array, offset, result);
  5674. return result;
  5675. };
  5676. /**
  5677. * Copy the content of an array into a given matrix
  5678. * @param array defines the source array
  5679. * @param offset defines an offset in the source array
  5680. * @param result defines the target matrix
  5681. */
  5682. Matrix.FromArrayToRef = function (array, offset, result) {
  5683. for (var index = 0; index < 16; index++) {
  5684. result.m[index] = array[index + offset];
  5685. }
  5686. result._markAsUpdated();
  5687. };
  5688. /**
  5689. * Stores an array into a matrix after having multiplied each component by a given factor
  5690. * @param array defines the source array
  5691. * @param offset defines the offset in the source array
  5692. * @param scale defines the scaling factor
  5693. * @param result defines the target matrix
  5694. */
  5695. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5696. for (var index = 0; index < 16; index++) {
  5697. result.m[index] = array[index + offset] * scale;
  5698. }
  5699. result._markAsUpdated();
  5700. };
  5701. /**
  5702. * Stores a list of values (16) inside a given matrix
  5703. * @param initialM11 defines 1st value of 1st row
  5704. * @param initialM12 defines 2nd value of 1st row
  5705. * @param initialM13 defines 3rd value of 1st row
  5706. * @param initialM14 defines 4th value of 1st row
  5707. * @param initialM21 defines 1st value of 2nd row
  5708. * @param initialM22 defines 2nd value of 2nd row
  5709. * @param initialM23 defines 3rd value of 2nd row
  5710. * @param initialM24 defines 4th value of 2nd row
  5711. * @param initialM31 defines 1st value of 3rd row
  5712. * @param initialM32 defines 2nd value of 3rd row
  5713. * @param initialM33 defines 3rd value of 3rd row
  5714. * @param initialM34 defines 4th value of 3rd row
  5715. * @param initialM41 defines 1st value of 4th row
  5716. * @param initialM42 defines 2nd value of 4th row
  5717. * @param initialM43 defines 3rd value of 4th row
  5718. * @param initialM44 defines 4th value of 4th row
  5719. * @param result defines the target matrix
  5720. */
  5721. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5722. result.m[0] = initialM11;
  5723. result.m[1] = initialM12;
  5724. result.m[2] = initialM13;
  5725. result.m[3] = initialM14;
  5726. result.m[4] = initialM21;
  5727. result.m[5] = initialM22;
  5728. result.m[6] = initialM23;
  5729. result.m[7] = initialM24;
  5730. result.m[8] = initialM31;
  5731. result.m[9] = initialM32;
  5732. result.m[10] = initialM33;
  5733. result.m[11] = initialM34;
  5734. result.m[12] = initialM41;
  5735. result.m[13] = initialM42;
  5736. result.m[14] = initialM43;
  5737. result.m[15] = initialM44;
  5738. result._markAsUpdated();
  5739. };
  5740. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5741. /**
  5742. * Gets an identity matrix that must not be updated
  5743. */
  5744. get: function () {
  5745. return Matrix._identityReadOnly;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. /**
  5751. * Creates new matrix from a list of values (16)
  5752. * @param initialM11 defines 1st value of 1st row
  5753. * @param initialM12 defines 2nd value of 1st row
  5754. * @param initialM13 defines 3rd value of 1st row
  5755. * @param initialM14 defines 4th value of 1st row
  5756. * @param initialM21 defines 1st value of 2nd row
  5757. * @param initialM22 defines 2nd value of 2nd row
  5758. * @param initialM23 defines 3rd value of 2nd row
  5759. * @param initialM24 defines 4th value of 2nd row
  5760. * @param initialM31 defines 1st value of 3rd row
  5761. * @param initialM32 defines 2nd value of 3rd row
  5762. * @param initialM33 defines 3rd value of 3rd row
  5763. * @param initialM34 defines 4th value of 3rd row
  5764. * @param initialM41 defines 1st value of 4th row
  5765. * @param initialM42 defines 2nd value of 4th row
  5766. * @param initialM43 defines 3rd value of 4th row
  5767. * @param initialM44 defines 4th value of 4th row
  5768. * @returns the new matrix
  5769. */
  5770. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5771. var result = new Matrix();
  5772. result.m[0] = initialM11;
  5773. result.m[1] = initialM12;
  5774. result.m[2] = initialM13;
  5775. result.m[3] = initialM14;
  5776. result.m[4] = initialM21;
  5777. result.m[5] = initialM22;
  5778. result.m[6] = initialM23;
  5779. result.m[7] = initialM24;
  5780. result.m[8] = initialM31;
  5781. result.m[9] = initialM32;
  5782. result.m[10] = initialM33;
  5783. result.m[11] = initialM34;
  5784. result.m[12] = initialM41;
  5785. result.m[13] = initialM42;
  5786. result.m[14] = initialM43;
  5787. result.m[15] = initialM44;
  5788. return result;
  5789. };
  5790. /**
  5791. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5792. * @param scale defines the scale vector3
  5793. * @param rotation defines the rotation quaternion
  5794. * @param translation defines the translation vector3
  5795. * @returns a new matrix
  5796. */
  5797. Matrix.Compose = function (scale, rotation, translation) {
  5798. var result = Matrix.Identity();
  5799. Matrix.ComposeToRef(scale, rotation, translation, result);
  5800. return result;
  5801. };
  5802. /**
  5803. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5804. * @param scale defines the scale vector3
  5805. * @param rotation defines the rotation quaternion
  5806. * @param translation defines the translation vector3
  5807. * @param result defines the target matrix
  5808. */
  5809. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5810. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5811. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5812. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5813. result.setTranslation(translation);
  5814. };
  5815. /**
  5816. * Creates a new identity matrix
  5817. * @returns a new identity matrix
  5818. */
  5819. Matrix.Identity = function () {
  5820. 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);
  5821. };
  5822. /**
  5823. * Creates a new identity matrix and stores the result in a given matrix
  5824. * @param result defines the target matrix
  5825. */
  5826. Matrix.IdentityToRef = function (result) {
  5827. 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);
  5828. };
  5829. /**
  5830. * Creates a new zero matrix
  5831. * @returns a new zero matrix
  5832. */
  5833. Matrix.Zero = function () {
  5834. 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);
  5835. };
  5836. /**
  5837. * Creates a new rotation matrix for "angle" radians around the X axis
  5838. * @param angle defines the angle (in radians) to use
  5839. * @return the new matrix
  5840. */
  5841. Matrix.RotationX = function (angle) {
  5842. var result = new Matrix();
  5843. Matrix.RotationXToRef(angle, result);
  5844. return result;
  5845. };
  5846. /**
  5847. * Creates a new matrix as the invert of a given matrix
  5848. * @param source defines the source matrix
  5849. * @returns the new matrix
  5850. */
  5851. Matrix.Invert = function (source) {
  5852. var result = new Matrix();
  5853. source.invertToRef(result);
  5854. return result;
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5858. * @param angle defines the angle (in radians) to use
  5859. * @param result defines the target matrix
  5860. */
  5861. Matrix.RotationXToRef = function (angle, result) {
  5862. var s = Math.sin(angle);
  5863. var c = Math.cos(angle);
  5864. result.m[0] = 1.0;
  5865. result.m[15] = 1.0;
  5866. result.m[5] = c;
  5867. result.m[10] = c;
  5868. result.m[9] = -s;
  5869. result.m[6] = s;
  5870. result.m[1] = 0.0;
  5871. result.m[2] = 0.0;
  5872. result.m[3] = 0.0;
  5873. result.m[4] = 0.0;
  5874. result.m[7] = 0.0;
  5875. result.m[8] = 0.0;
  5876. result.m[11] = 0.0;
  5877. result.m[12] = 0.0;
  5878. result.m[13] = 0.0;
  5879. result.m[14] = 0.0;
  5880. result._markAsUpdated();
  5881. };
  5882. /**
  5883. * Creates a new rotation matrix for "angle" radians around the Y axis
  5884. * @param angle defines the angle (in radians) to use
  5885. * @return the new matrix
  5886. */
  5887. Matrix.RotationY = function (angle) {
  5888. var result = new Matrix();
  5889. Matrix.RotationYToRef(angle, result);
  5890. return result;
  5891. };
  5892. /**
  5893. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5894. * @param angle defines the angle (in radians) to use
  5895. * @param result defines the target matrix
  5896. */
  5897. Matrix.RotationYToRef = function (angle, result) {
  5898. var s = Math.sin(angle);
  5899. var c = Math.cos(angle);
  5900. result.m[5] = 1.0;
  5901. result.m[15] = 1.0;
  5902. result.m[0] = c;
  5903. result.m[2] = -s;
  5904. result.m[8] = s;
  5905. result.m[10] = c;
  5906. result.m[1] = 0.0;
  5907. result.m[3] = 0.0;
  5908. result.m[4] = 0.0;
  5909. result.m[6] = 0.0;
  5910. result.m[7] = 0.0;
  5911. result.m[9] = 0.0;
  5912. result.m[11] = 0.0;
  5913. result.m[12] = 0.0;
  5914. result.m[13] = 0.0;
  5915. result.m[14] = 0.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Creates a new rotation matrix for "angle" radians around the Z axis
  5920. * @param angle defines the angle (in radians) to use
  5921. * @return the new matrix
  5922. */
  5923. Matrix.RotationZ = function (angle) {
  5924. var result = new Matrix();
  5925. Matrix.RotationZToRef(angle, result);
  5926. return result;
  5927. };
  5928. /**
  5929. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5930. * @param angle defines the angle (in radians) to use
  5931. * @param result defines the target matrix
  5932. */
  5933. Matrix.RotationZToRef = function (angle, result) {
  5934. var s = Math.sin(angle);
  5935. var c = Math.cos(angle);
  5936. result.m[10] = 1.0;
  5937. result.m[15] = 1.0;
  5938. result.m[0] = c;
  5939. result.m[1] = s;
  5940. result.m[4] = -s;
  5941. result.m[5] = c;
  5942. result.m[2] = 0.0;
  5943. result.m[3] = 0.0;
  5944. result.m[6] = 0.0;
  5945. result.m[7] = 0.0;
  5946. result.m[8] = 0.0;
  5947. result.m[9] = 0.0;
  5948. result.m[11] = 0.0;
  5949. result.m[12] = 0.0;
  5950. result.m[13] = 0.0;
  5951. result.m[14] = 0.0;
  5952. result._markAsUpdated();
  5953. };
  5954. /**
  5955. * Creates a new rotation matrix for "angle" radians around the given axis
  5956. * @param axis defines the axis to use
  5957. * @param angle defines the angle (in radians) to use
  5958. * @return the new matrix
  5959. */
  5960. Matrix.RotationAxis = function (axis, angle) {
  5961. var result = Matrix.Zero();
  5962. Matrix.RotationAxisToRef(axis, angle, result);
  5963. return result;
  5964. };
  5965. /**
  5966. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5967. * @param axis defines the axis to use
  5968. * @param angle defines the angle (in radians) to use
  5969. * @param result defines the target matrix
  5970. */
  5971. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5972. var s = Math.sin(-angle);
  5973. var c = Math.cos(-angle);
  5974. var c1 = 1 - c;
  5975. axis.normalize();
  5976. result.m[0] = (axis.x * axis.x) * c1 + c;
  5977. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5978. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5979. result.m[3] = 0.0;
  5980. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5981. result.m[5] = (axis.y * axis.y) * c1 + c;
  5982. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5983. result.m[7] = 0.0;
  5984. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5985. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5986. result.m[10] = (axis.z * axis.z) * c1 + c;
  5987. result.m[11] = 0.0;
  5988. result.m[15] = 1.0;
  5989. result._markAsUpdated();
  5990. };
  5991. /**
  5992. * Creates a rotation matrix
  5993. * @param yaw defines the yaw angle in radians (Y axis)
  5994. * @param pitch defines the pitch angle in radians (X axis)
  5995. * @param roll defines the roll angle in radians (X axis)
  5996. * @returns the new rotation matrix
  5997. */
  5998. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5999. var result = new Matrix();
  6000. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6001. return result;
  6002. };
  6003. /**
  6004. * Creates a rotation matrix and stores it in a given matrix
  6005. * @param yaw defines the yaw angle in radians (Y axis)
  6006. * @param pitch defines the pitch angle in radians (X axis)
  6007. * @param roll defines the roll angle in radians (X axis)
  6008. * @param result defines the target matrix
  6009. */
  6010. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6011. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6012. this._tempQuaternion.toRotationMatrix(result);
  6013. };
  6014. /**
  6015. * Creates a scaling matrix
  6016. * @param x defines the scale factor on X axis
  6017. * @param y defines the scale factor on Y axis
  6018. * @param z defines the scale factor on Z axis
  6019. * @returns the new matrix
  6020. */
  6021. Matrix.Scaling = function (x, y, z) {
  6022. var result = Matrix.Zero();
  6023. Matrix.ScalingToRef(x, y, z, result);
  6024. return result;
  6025. };
  6026. /**
  6027. * Creates a scaling matrix and stores it in a given matrix
  6028. * @param x defines the scale factor on X axis
  6029. * @param y defines the scale factor on Y axis
  6030. * @param z defines the scale factor on Z axis
  6031. * @param result defines the target matrix
  6032. */
  6033. Matrix.ScalingToRef = function (x, y, z, result) {
  6034. result.m[0] = x;
  6035. result.m[1] = 0.0;
  6036. result.m[2] = 0.0;
  6037. result.m[3] = 0.0;
  6038. result.m[4] = 0.0;
  6039. result.m[5] = y;
  6040. result.m[6] = 0.0;
  6041. result.m[7] = 0.0;
  6042. result.m[8] = 0.0;
  6043. result.m[9] = 0.0;
  6044. result.m[10] = z;
  6045. result.m[11] = 0.0;
  6046. result.m[12] = 0.0;
  6047. result.m[13] = 0.0;
  6048. result.m[14] = 0.0;
  6049. result.m[15] = 1.0;
  6050. result._markAsUpdated();
  6051. };
  6052. /**
  6053. * Creates a translation matrix
  6054. * @param x defines the translation on X axis
  6055. * @param y defines the translation on Y axis
  6056. * @param z defines the translationon Z axis
  6057. * @returns the new matrix
  6058. */
  6059. Matrix.Translation = function (x, y, z) {
  6060. var result = Matrix.Identity();
  6061. Matrix.TranslationToRef(x, y, z, result);
  6062. return result;
  6063. };
  6064. /**
  6065. * Creates a translation matrix and stores it in a given matrix
  6066. * @param x defines the translation on X axis
  6067. * @param y defines the translation on Y axis
  6068. * @param z defines the translationon Z axis
  6069. * @param result defines the target matrix
  6070. */
  6071. Matrix.TranslationToRef = function (x, y, z, result) {
  6072. 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);
  6073. };
  6074. /**
  6075. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6076. * @param startValue defines the start value
  6077. * @param endValue defines the end value
  6078. * @param gradient defines the gradient factor
  6079. * @returns the new matrix
  6080. */
  6081. Matrix.Lerp = function (startValue, endValue, gradient) {
  6082. var result = Matrix.Zero();
  6083. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6084. return result;
  6085. };
  6086. /**
  6087. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6088. * @param startValue defines the start value
  6089. * @param endValue defines the end value
  6090. * @param gradient defines the gradient factor
  6091. * @param result defines the Matrix object where to store data
  6092. */
  6093. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6094. for (var index = 0; index < 16; index++) {
  6095. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6096. }
  6097. result._markAsUpdated();
  6098. };
  6099. /**
  6100. * Builds a new matrix whose values are computed by:
  6101. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6102. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6103. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6104. * @param startValue defines the first matrix
  6105. * @param endValue defines the second matrix
  6106. * @param gradient defines the gradient between the two matrices
  6107. * @returns the new matrix
  6108. */
  6109. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6110. var result = Matrix.Zero();
  6111. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6112. return result;
  6113. };
  6114. /**
  6115. * Update a matrix to values which are computed by:
  6116. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6117. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6118. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6119. * @param startValue defines the first matrix
  6120. * @param endValue defines the second matrix
  6121. * @param gradient defines the gradient between the two matrices
  6122. * @param result defines the target matrix
  6123. */
  6124. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6125. var startScale = MathTmp.Vector3[0];
  6126. var startRotation = MathTmp.Quaternion[0];
  6127. var startTranslation = MathTmp.Vector3[1];
  6128. startValue.decompose(startScale, startRotation, startTranslation);
  6129. var endScale = MathTmp.Vector3[2];
  6130. var endRotation = MathTmp.Quaternion[1];
  6131. var endTranslation = MathTmp.Vector3[3];
  6132. endValue.decompose(endScale, endRotation, endTranslation);
  6133. var resultScale = MathTmp.Vector3[4];
  6134. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6135. var resultRotation = MathTmp.Quaternion[2];
  6136. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6137. var resultTranslation = MathTmp.Vector3[5];
  6138. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6139. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6140. };
  6141. /**
  6142. * 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"
  6143. * This function works in left handed mode
  6144. * @param eye defines the final position of the entity
  6145. * @param target defines where the entity should look at
  6146. * @param up defines the up vector for the entity
  6147. * @returns the new matrix
  6148. */
  6149. Matrix.LookAtLH = function (eye, target, up) {
  6150. var result = Matrix.Zero();
  6151. Matrix.LookAtLHToRef(eye, target, up, result);
  6152. return result;
  6153. };
  6154. /**
  6155. * 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".
  6156. * This function works in left handed mode
  6157. * @param eye defines the final position of the entity
  6158. * @param target defines where the entity should look at
  6159. * @param up defines the up vector for the entity
  6160. * @param result defines the target matrix
  6161. */
  6162. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6163. // Z axis
  6164. target.subtractToRef(eye, this._zAxis);
  6165. this._zAxis.normalize();
  6166. // X axis
  6167. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6168. if (this._xAxis.lengthSquared() === 0) {
  6169. this._xAxis.x = 1.0;
  6170. }
  6171. else {
  6172. this._xAxis.normalize();
  6173. }
  6174. // Y axis
  6175. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6176. this._yAxis.normalize();
  6177. // Eye angles
  6178. var ex = -Vector3.Dot(this._xAxis, eye);
  6179. var ey = -Vector3.Dot(this._yAxis, eye);
  6180. var ez = -Vector3.Dot(this._zAxis, eye);
  6181. 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);
  6182. };
  6183. /**
  6184. * 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"
  6185. * This function works in right handed mode
  6186. * @param eye defines the final position of the entity
  6187. * @param target defines where the entity should look at
  6188. * @param up defines the up vector for the entity
  6189. * @returns the new matrix
  6190. */
  6191. Matrix.LookAtRH = function (eye, target, up) {
  6192. var result = Matrix.Zero();
  6193. Matrix.LookAtRHToRef(eye, target, up, result);
  6194. return result;
  6195. };
  6196. /**
  6197. * 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".
  6198. * This function works in right handed mode
  6199. * @param eye defines the final position of the entity
  6200. * @param target defines where the entity should look at
  6201. * @param up defines the up vector for the entity
  6202. * @param result defines the target matrix
  6203. */
  6204. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6205. // Z axis
  6206. eye.subtractToRef(target, this._zAxis);
  6207. this._zAxis.normalize();
  6208. // X axis
  6209. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6210. if (this._xAxis.lengthSquared() === 0) {
  6211. this._xAxis.x = 1.0;
  6212. }
  6213. else {
  6214. this._xAxis.normalize();
  6215. }
  6216. // Y axis
  6217. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6218. this._yAxis.normalize();
  6219. // Eye angles
  6220. var ex = -Vector3.Dot(this._xAxis, eye);
  6221. var ey = -Vector3.Dot(this._yAxis, eye);
  6222. var ez = -Vector3.Dot(this._zAxis, eye);
  6223. 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);
  6224. };
  6225. /**
  6226. * Create a left-handed orthographic projection matrix
  6227. * @param width defines the viewport width
  6228. * @param height defines the viewport height
  6229. * @param znear defines the near clip plane
  6230. * @param zfar defines the far clip plane
  6231. * @returns a new matrix as a left-handed orthographic projection matrix
  6232. */
  6233. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6234. var matrix = Matrix.Zero();
  6235. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6236. return matrix;
  6237. };
  6238. /**
  6239. * Store a left-handed orthographic projection to a given matrix
  6240. * @param width defines the viewport width
  6241. * @param height defines the viewport height
  6242. * @param znear defines the near clip plane
  6243. * @param zfar defines the far clip plane
  6244. * @param result defines the target matrix
  6245. */
  6246. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6247. var n = znear;
  6248. var f = zfar;
  6249. var a = 2.0 / width;
  6250. var b = 2.0 / height;
  6251. var c = 2.0 / (f - n);
  6252. var d = -(f + n) / (f - n);
  6253. 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);
  6254. };
  6255. /**
  6256. * Create a left-handed orthographic projection matrix
  6257. * @param left defines the viewport left coordinate
  6258. * @param right defines the viewport right coordinate
  6259. * @param bottom defines the viewport bottom coordinate
  6260. * @param top defines the viewport top coordinate
  6261. * @param znear defines the near clip plane
  6262. * @param zfar defines the far clip plane
  6263. * @returns a new matrix as a left-handed orthographic projection matrix
  6264. */
  6265. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6266. var matrix = Matrix.Zero();
  6267. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6268. return matrix;
  6269. };
  6270. /**
  6271. * Stores a left-handed orthographic projection into a given matrix
  6272. * @param left defines the viewport left coordinate
  6273. * @param right defines the viewport right coordinate
  6274. * @param bottom defines the viewport bottom coordinate
  6275. * @param top defines the viewport top coordinate
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @param result defines the target matrix
  6279. */
  6280. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6281. var n = znear;
  6282. var f = zfar;
  6283. var a = 2.0 / (right - left);
  6284. var b = 2.0 / (top - bottom);
  6285. var c = 2.0 / (f - n);
  6286. var d = -(f + n) / (f - n);
  6287. var i0 = (left + right) / (left - right);
  6288. var i1 = (top + bottom) / (bottom - top);
  6289. 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);
  6290. };
  6291. /**
  6292. * Creates a right-handed orthographic projection matrix
  6293. * @param left defines the viewport left coordinate
  6294. * @param right defines the viewport right coordinate
  6295. * @param bottom defines the viewport bottom coordinate
  6296. * @param top defines the viewport top coordinate
  6297. * @param znear defines the near clip plane
  6298. * @param zfar defines the far clip plane
  6299. * @returns a new matrix as a right-handed orthographic projection matrix
  6300. */
  6301. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6302. var matrix = Matrix.Zero();
  6303. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6304. return matrix;
  6305. };
  6306. /**
  6307. * Stores a right-handed orthographic projection into a given matrix
  6308. * @param left defines the viewport left coordinate
  6309. * @param right defines the viewport right coordinate
  6310. * @param bottom defines the viewport bottom coordinate
  6311. * @param top defines the viewport top coordinate
  6312. * @param znear defines the near clip plane
  6313. * @param zfar defines the far clip plane
  6314. * @param result defines the target matrix
  6315. */
  6316. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6317. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6318. result.m[10] *= -1.0;
  6319. };
  6320. /**
  6321. * Creates a left-handed perspective projection matrix
  6322. * @param width defines the viewport width
  6323. * @param height defines the viewport height
  6324. * @param znear defines the near clip plane
  6325. * @param zfar defines the far clip plane
  6326. * @returns a new matrix as a left-handed perspective projection matrix
  6327. */
  6328. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6329. var matrix = Matrix.Zero();
  6330. var n = znear;
  6331. var f = zfar;
  6332. var a = 2.0 * n / width;
  6333. var b = 2.0 * n / height;
  6334. var c = (f + n) / (f - n);
  6335. var d = -2.0 * f * n / (f - n);
  6336. 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);
  6337. return matrix;
  6338. };
  6339. /**
  6340. * Creates a left-handed perspective projection matrix
  6341. * @param fov defines the horizontal field of view
  6342. * @param aspect defines the aspect ratio
  6343. * @param znear defines the near clip plane
  6344. * @param zfar defines the far clip plane
  6345. * @returns a new matrix as a left-handed perspective projection matrix
  6346. */
  6347. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6348. var matrix = Matrix.Zero();
  6349. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6350. return matrix;
  6351. };
  6352. /**
  6353. * Stores a left-handed perspective projection into a given matrix
  6354. * @param fov defines the horizontal field of view
  6355. * @param aspect defines the aspect ratio
  6356. * @param znear defines the near clip plane
  6357. * @param zfar defines the far clip plane
  6358. * @param result defines the target matrix
  6359. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6360. */
  6361. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6362. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6363. var n = znear;
  6364. var f = zfar;
  6365. var t = 1.0 / (Math.tan(fov * 0.5));
  6366. var a = isVerticalFovFixed ? (t / aspect) : t;
  6367. var b = isVerticalFovFixed ? t : (t * aspect);
  6368. var c = (f + n) / (f - n);
  6369. var d = -2.0 * f * n / (f - n);
  6370. 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);
  6371. };
  6372. /**
  6373. * Creates a right-handed perspective projection matrix
  6374. * @param fov defines the horizontal field of view
  6375. * @param aspect defines the aspect ratio
  6376. * @param znear defines the near clip plane
  6377. * @param zfar defines the far clip plane
  6378. * @returns a new matrix as a right-handed perspective projection matrix
  6379. */
  6380. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6381. var matrix = Matrix.Zero();
  6382. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6383. return matrix;
  6384. };
  6385. /**
  6386. * Stores a right-handed perspective projection into a given matrix
  6387. * @param fov defines the horizontal field of view
  6388. * @param aspect defines the aspect ratio
  6389. * @param znear defines the near clip plane
  6390. * @param zfar defines the far clip plane
  6391. * @param result defines the target matrix
  6392. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6393. */
  6394. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6395. //alternatively this could be expressed as:
  6396. // m = PerspectiveFovLHToRef
  6397. // m[10] *= -1.0;
  6398. // m[11] *= -1.0;
  6399. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6400. var n = znear;
  6401. var f = zfar;
  6402. var t = 1.0 / (Math.tan(fov * 0.5));
  6403. var a = isVerticalFovFixed ? (t / aspect) : t;
  6404. var b = isVerticalFovFixed ? t : (t * aspect);
  6405. var c = -(f + n) / (f - n);
  6406. var d = -2 * f * n / (f - n);
  6407. 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);
  6408. };
  6409. /**
  6410. * Stores a perspective projection for WebVR info a given matrix
  6411. * @param fov defines the field of view
  6412. * @param znear defines the near clip plane
  6413. * @param zfar defines the far clip plane
  6414. * @param result defines the target matrix
  6415. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6416. */
  6417. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6418. if (rightHanded === void 0) { rightHanded = false; }
  6419. var rightHandedFactor = rightHanded ? -1 : 1;
  6420. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6421. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6422. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6423. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6424. var xScale = 2.0 / (leftTan + rightTan);
  6425. var yScale = 2.0 / (upTan + downTan);
  6426. result.m[0] = xScale;
  6427. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6428. result.m[5] = yScale;
  6429. result.m[6] = result.m[7] = 0.0;
  6430. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6431. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6432. result.m[10] = -zfar / (znear - zfar);
  6433. result.m[11] = 1.0 * rightHandedFactor;
  6434. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6435. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6436. result._markAsUpdated();
  6437. };
  6438. /**
  6439. * Computes a complete transformation matrix
  6440. * @param viewport defines the viewport to use
  6441. * @param world defines the world matrix
  6442. * @param view defines the view matrix
  6443. * @param projection defines the projection matrix
  6444. * @param zmin defines the near clip plane
  6445. * @param zmax defines the far clip plane
  6446. * @returns the transformation matrix
  6447. */
  6448. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6449. var cw = viewport.width;
  6450. var ch = viewport.height;
  6451. var cx = viewport.x;
  6452. var cy = viewport.y;
  6453. 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);
  6454. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6455. };
  6456. /**
  6457. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6458. * @param matrix defines the matrix to use
  6459. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6460. */
  6461. Matrix.GetAsMatrix2x2 = function (matrix) {
  6462. return new Float32Array([
  6463. matrix.m[0], matrix.m[1],
  6464. matrix.m[4], matrix.m[5]
  6465. ]);
  6466. };
  6467. /**
  6468. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6469. * @param matrix defines the matrix to use
  6470. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6471. */
  6472. Matrix.GetAsMatrix3x3 = function (matrix) {
  6473. return new Float32Array([
  6474. matrix.m[0], matrix.m[1], matrix.m[2],
  6475. matrix.m[4], matrix.m[5], matrix.m[6],
  6476. matrix.m[8], matrix.m[9], matrix.m[10]
  6477. ]);
  6478. };
  6479. /**
  6480. * Compute the transpose of a given matrix
  6481. * @param matrix defines the matrix to transpose
  6482. * @returns the new matrix
  6483. */
  6484. Matrix.Transpose = function (matrix) {
  6485. var result = new Matrix();
  6486. Matrix.TransposeToRef(matrix, result);
  6487. return result;
  6488. };
  6489. /**
  6490. * Compute the transpose of a matrix and store it in a target matrix
  6491. * @param matrix defines the matrix to transpose
  6492. * @param result defines the target matrix
  6493. */
  6494. Matrix.TransposeToRef = function (matrix, result) {
  6495. result.m[0] = matrix.m[0];
  6496. result.m[1] = matrix.m[4];
  6497. result.m[2] = matrix.m[8];
  6498. result.m[3] = matrix.m[12];
  6499. result.m[4] = matrix.m[1];
  6500. result.m[5] = matrix.m[5];
  6501. result.m[6] = matrix.m[9];
  6502. result.m[7] = matrix.m[13];
  6503. result.m[8] = matrix.m[2];
  6504. result.m[9] = matrix.m[6];
  6505. result.m[10] = matrix.m[10];
  6506. result.m[11] = matrix.m[14];
  6507. result.m[12] = matrix.m[3];
  6508. result.m[13] = matrix.m[7];
  6509. result.m[14] = matrix.m[11];
  6510. result.m[15] = matrix.m[15];
  6511. };
  6512. /**
  6513. * Computes a reflection matrix from a plane
  6514. * @param plane defines the reflection plane
  6515. * @returns a new matrix
  6516. */
  6517. Matrix.Reflection = function (plane) {
  6518. var matrix = new Matrix();
  6519. Matrix.ReflectionToRef(plane, matrix);
  6520. return matrix;
  6521. };
  6522. /**
  6523. * Computes a reflection matrix from a plane
  6524. * @param plane defines the reflection plane
  6525. * @param result defines the target matrix
  6526. */
  6527. Matrix.ReflectionToRef = function (plane, result) {
  6528. plane.normalize();
  6529. var x = plane.normal.x;
  6530. var y = plane.normal.y;
  6531. var z = plane.normal.z;
  6532. var temp = -2 * x;
  6533. var temp2 = -2 * y;
  6534. var temp3 = -2 * z;
  6535. result.m[0] = (temp * x) + 1;
  6536. result.m[1] = temp2 * x;
  6537. result.m[2] = temp3 * x;
  6538. result.m[3] = 0.0;
  6539. result.m[4] = temp * y;
  6540. result.m[5] = (temp2 * y) + 1;
  6541. result.m[6] = temp3 * y;
  6542. result.m[7] = 0.0;
  6543. result.m[8] = temp * z;
  6544. result.m[9] = temp2 * z;
  6545. result.m[10] = (temp3 * z) + 1;
  6546. result.m[11] = 0.0;
  6547. result.m[12] = temp * plane.d;
  6548. result.m[13] = temp2 * plane.d;
  6549. result.m[14] = temp3 * plane.d;
  6550. result.m[15] = 1.0;
  6551. result._markAsUpdated();
  6552. };
  6553. /**
  6554. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6555. * @param xaxis defines the value of the 1st axis
  6556. * @param yaxis defines the value of the 2nd axis
  6557. * @param zaxis defines the value of the 3rd axis
  6558. * @param result defines the target matrix
  6559. */
  6560. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6561. result.m[0] = xaxis.x;
  6562. result.m[1] = xaxis.y;
  6563. result.m[2] = xaxis.z;
  6564. result.m[3] = 0.0;
  6565. result.m[4] = yaxis.x;
  6566. result.m[5] = yaxis.y;
  6567. result.m[6] = yaxis.z;
  6568. result.m[7] = 0.0;
  6569. result.m[8] = zaxis.x;
  6570. result.m[9] = zaxis.y;
  6571. result.m[10] = zaxis.z;
  6572. result.m[11] = 0.0;
  6573. result.m[12] = 0.0;
  6574. result.m[13] = 0.0;
  6575. result.m[14] = 0.0;
  6576. result.m[15] = 1.0;
  6577. result._markAsUpdated();
  6578. };
  6579. /**
  6580. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6581. * @param quat defines the quaternion to use
  6582. * @param result defines the target matrix
  6583. */
  6584. Matrix.FromQuaternionToRef = function (quat, result) {
  6585. var xx = quat.x * quat.x;
  6586. var yy = quat.y * quat.y;
  6587. var zz = quat.z * quat.z;
  6588. var xy = quat.x * quat.y;
  6589. var zw = quat.z * quat.w;
  6590. var zx = quat.z * quat.x;
  6591. var yw = quat.y * quat.w;
  6592. var yz = quat.y * quat.z;
  6593. var xw = quat.x * quat.w;
  6594. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6595. result.m[1] = 2.0 * (xy + zw);
  6596. result.m[2] = 2.0 * (zx - yw);
  6597. result.m[3] = 0.0;
  6598. result.m[4] = 2.0 * (xy - zw);
  6599. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6600. result.m[6] = 2.0 * (yz + xw);
  6601. result.m[7] = 0.0;
  6602. result.m[8] = 2.0 * (zx + yw);
  6603. result.m[9] = 2.0 * (yz - xw);
  6604. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6605. result.m[11] = 0.0;
  6606. result.m[12] = 0.0;
  6607. result.m[13] = 0.0;
  6608. result.m[14] = 0.0;
  6609. result.m[15] = 1.0;
  6610. result._markAsUpdated();
  6611. };
  6612. Matrix._tempQuaternion = new Quaternion();
  6613. Matrix._xAxis = Vector3.Zero();
  6614. Matrix._yAxis = Vector3.Zero();
  6615. Matrix._zAxis = Vector3.Zero();
  6616. Matrix._updateFlagSeed = 0;
  6617. Matrix._identityReadOnly = Matrix.Identity();
  6618. return Matrix;
  6619. }());
  6620. BABYLON.Matrix = Matrix;
  6621. var Plane = /** @class */ (function () {
  6622. /**
  6623. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6624. */
  6625. function Plane(a, b, c, d) {
  6626. this.normal = new Vector3(a, b, c);
  6627. this.d = d;
  6628. }
  6629. /**
  6630. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6631. */
  6632. Plane.prototype.asArray = function () {
  6633. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6634. };
  6635. // Methods
  6636. /**
  6637. * Returns a new plane copied from the current Plane.
  6638. */
  6639. Plane.prototype.clone = function () {
  6640. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6641. };
  6642. /**
  6643. * Returns the string "Plane".
  6644. */
  6645. Plane.prototype.getClassName = function () {
  6646. return "Plane";
  6647. };
  6648. /**
  6649. * Returns the Plane hash code.
  6650. */
  6651. Plane.prototype.getHashCode = function () {
  6652. var hash = this.normal.getHashCode();
  6653. hash = (hash * 397) ^ (this.d || 0);
  6654. return hash;
  6655. };
  6656. /**
  6657. * Normalize the current Plane in place.
  6658. * Returns the updated Plane.
  6659. */
  6660. Plane.prototype.normalize = function () {
  6661. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6662. var magnitude = 0.0;
  6663. if (norm !== 0) {
  6664. magnitude = 1.0 / norm;
  6665. }
  6666. this.normal.x *= magnitude;
  6667. this.normal.y *= magnitude;
  6668. this.normal.z *= magnitude;
  6669. this.d *= magnitude;
  6670. return this;
  6671. };
  6672. /**
  6673. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6674. */
  6675. Plane.prototype.transform = function (transformation) {
  6676. var transposedMatrix = Matrix.Transpose(transformation);
  6677. var x = this.normal.x;
  6678. var y = this.normal.y;
  6679. var z = this.normal.z;
  6680. var d = this.d;
  6681. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6682. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6683. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6684. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6685. return new Plane(normalX, normalY, normalZ, finalD);
  6686. };
  6687. /**
  6688. * Returns the dot product (float) of the point coordinates and the plane normal.
  6689. */
  6690. Plane.prototype.dotCoordinate = function (point) {
  6691. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6692. };
  6693. /**
  6694. * Updates the current Plane from the plane defined by the three given points.
  6695. * Returns the updated Plane.
  6696. */
  6697. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6698. var x1 = point2.x - point1.x;
  6699. var y1 = point2.y - point1.y;
  6700. var z1 = point2.z - point1.z;
  6701. var x2 = point3.x - point1.x;
  6702. var y2 = point3.y - point1.y;
  6703. var z2 = point3.z - point1.z;
  6704. var yz = (y1 * z2) - (z1 * y2);
  6705. var xz = (z1 * x2) - (x1 * z2);
  6706. var xy = (x1 * y2) - (y1 * x2);
  6707. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6708. var invPyth;
  6709. if (pyth !== 0) {
  6710. invPyth = 1.0 / pyth;
  6711. }
  6712. else {
  6713. invPyth = 0.0;
  6714. }
  6715. this.normal.x = yz * invPyth;
  6716. this.normal.y = xz * invPyth;
  6717. this.normal.z = xy * invPyth;
  6718. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6719. return this;
  6720. };
  6721. /**
  6722. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6723. */
  6724. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6725. var dot = Vector3.Dot(this.normal, direction);
  6726. return (dot <= epsilon);
  6727. };
  6728. /**
  6729. * Returns the signed distance (float) from the given point to the Plane.
  6730. */
  6731. Plane.prototype.signedDistanceTo = function (point) {
  6732. return Vector3.Dot(point, this.normal) + this.d;
  6733. };
  6734. // Statics
  6735. /**
  6736. * Returns a new Plane from the given array.
  6737. */
  6738. Plane.FromArray = function (array) {
  6739. return new Plane(array[0], array[1], array[2], array[3]);
  6740. };
  6741. /**
  6742. * Returns a new Plane defined by the three given points.
  6743. */
  6744. Plane.FromPoints = function (point1, point2, point3) {
  6745. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6746. result.copyFromPoints(point1, point2, point3);
  6747. return result;
  6748. };
  6749. /**
  6750. * Returns a new Plane the normal vector to this plane at the given origin point.
  6751. * Note : the vector "normal" is updated because normalized.
  6752. */
  6753. Plane.FromPositionAndNormal = function (origin, normal) {
  6754. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6755. normal.normalize();
  6756. result.normal = normal;
  6757. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6758. return result;
  6759. };
  6760. /**
  6761. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6762. */
  6763. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6764. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6765. return Vector3.Dot(point, normal) + d;
  6766. };
  6767. return Plane;
  6768. }());
  6769. BABYLON.Plane = Plane;
  6770. var Viewport = /** @class */ (function () {
  6771. /**
  6772. * Creates a Viewport object located at (x, y) and sized (width, height).
  6773. */
  6774. function Viewport(x, y, width, height) {
  6775. this.x = x;
  6776. this.y = y;
  6777. this.width = width;
  6778. this.height = height;
  6779. }
  6780. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6781. if (renderWidthOrEngine.getRenderWidth) {
  6782. var engine = renderWidthOrEngine;
  6783. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6784. }
  6785. var renderWidth = renderWidthOrEngine;
  6786. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6787. };
  6788. /**
  6789. * Returns a new Viewport copied from the current one.
  6790. */
  6791. Viewport.prototype.clone = function () {
  6792. return new Viewport(this.x, this.y, this.width, this.height);
  6793. };
  6794. return Viewport;
  6795. }());
  6796. BABYLON.Viewport = Viewport;
  6797. var Frustum = /** @class */ (function () {
  6798. function Frustum() {
  6799. }
  6800. /**
  6801. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6802. */
  6803. Frustum.GetPlanes = function (transform) {
  6804. var frustumPlanes = [];
  6805. for (var index = 0; index < 6; index++) {
  6806. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6807. }
  6808. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6809. return frustumPlanes;
  6810. };
  6811. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6812. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6813. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6814. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6815. frustumPlane.d = transform.m[15] + transform.m[14];
  6816. frustumPlane.normalize();
  6817. };
  6818. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6819. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6820. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6821. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6822. frustumPlane.d = transform.m[15] - transform.m[14];
  6823. frustumPlane.normalize();
  6824. };
  6825. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6826. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6827. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6828. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6829. frustumPlane.d = transform.m[15] + transform.m[12];
  6830. frustumPlane.normalize();
  6831. };
  6832. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6833. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6834. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6835. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6836. frustumPlane.d = transform.m[15] - transform.m[12];
  6837. frustumPlane.normalize();
  6838. };
  6839. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6840. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6841. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6842. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6843. frustumPlane.d = transform.m[15] - transform.m[13];
  6844. frustumPlane.normalize();
  6845. };
  6846. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6847. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6848. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6849. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6850. frustumPlane.d = transform.m[15] + transform.m[13];
  6851. frustumPlane.normalize();
  6852. };
  6853. /**
  6854. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6855. */
  6856. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6857. // Near
  6858. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6859. // Far
  6860. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6861. // Left
  6862. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6863. // Right
  6864. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6865. // Top
  6866. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6867. // Bottom
  6868. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6869. };
  6870. return Frustum;
  6871. }());
  6872. BABYLON.Frustum = Frustum;
  6873. /** Defines supported spaces */
  6874. var Space;
  6875. (function (Space) {
  6876. /** Local (object) space */
  6877. Space[Space["LOCAL"] = 0] = "LOCAL";
  6878. /** World space */
  6879. Space[Space["WORLD"] = 1] = "WORLD";
  6880. /** Bone space */
  6881. Space[Space["BONE"] = 2] = "BONE";
  6882. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6883. /** Defines the 3 main axes */
  6884. var Axis = /** @class */ (function () {
  6885. function Axis() {
  6886. }
  6887. /** X axis */
  6888. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6889. /** Y axis */
  6890. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6891. /** Z axis */
  6892. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6893. return Axis;
  6894. }());
  6895. BABYLON.Axis = Axis;
  6896. ;
  6897. var BezierCurve = /** @class */ (function () {
  6898. function BezierCurve() {
  6899. }
  6900. /**
  6901. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6902. */
  6903. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6904. // Extract X (which is equal to time here)
  6905. var f0 = 1 - 3 * x2 + 3 * x1;
  6906. var f1 = 3 * x2 - 6 * x1;
  6907. var f2 = 3 * x1;
  6908. var refinedT = t;
  6909. for (var i = 0; i < 5; i++) {
  6910. var refinedT2 = refinedT * refinedT;
  6911. var refinedT3 = refinedT2 * refinedT;
  6912. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6913. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6914. refinedT -= (x - t) * slope;
  6915. refinedT = Math.min(1, Math.max(0, refinedT));
  6916. }
  6917. // Resolve cubic bezier for the given x
  6918. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6919. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6920. Math.pow(refinedT, 3);
  6921. };
  6922. return BezierCurve;
  6923. }());
  6924. BABYLON.BezierCurve = BezierCurve;
  6925. /**
  6926. * Defines potential orientation for back face culling
  6927. */
  6928. var Orientation;
  6929. (function (Orientation) {
  6930. /**
  6931. * Clockwise
  6932. */
  6933. Orientation[Orientation["CW"] = 0] = "CW";
  6934. /** Counter clockwise */
  6935. Orientation[Orientation["CCW"] = 1] = "CCW";
  6936. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6937. /**
  6938. * Defines angle representation
  6939. */
  6940. var Angle = /** @class */ (function () {
  6941. /**
  6942. * Creates an Angle object of "radians" radians (float).
  6943. */
  6944. function Angle(radians) {
  6945. this._radians = radians;
  6946. if (this._radians < 0.0)
  6947. this._radians += (2.0 * Math.PI);
  6948. }
  6949. /**
  6950. * Get value in degrees
  6951. * @returns the Angle value in degrees (float)
  6952. */
  6953. Angle.prototype.degrees = function () {
  6954. return this._radians * 180.0 / Math.PI;
  6955. };
  6956. /**
  6957. * Get value in radians
  6958. * @returns the Angle value in radians (float)
  6959. */
  6960. Angle.prototype.radians = function () {
  6961. return this._radians;
  6962. };
  6963. /**
  6964. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6965. * @param a defines first vector
  6966. * @param b defines second vector
  6967. * @returns a new Angle
  6968. */
  6969. Angle.BetweenTwoPoints = function (a, b) {
  6970. var delta = b.subtract(a);
  6971. var theta = Math.atan2(delta.y, delta.x);
  6972. return new Angle(theta);
  6973. };
  6974. /**
  6975. * Gets a new Angle object from the given float in radians
  6976. * @param radians defines the angle value in radians
  6977. * @returns a new Angle
  6978. */
  6979. Angle.FromRadians = function (radians) {
  6980. return new Angle(radians);
  6981. };
  6982. /**
  6983. * Gets a new Angle object from the given float in degrees
  6984. * @param degrees defines the angle value in degrees
  6985. * @returns a new Angle
  6986. */
  6987. Angle.FromDegrees = function (degrees) {
  6988. return new Angle(degrees * Math.PI / 180.0);
  6989. };
  6990. return Angle;
  6991. }());
  6992. BABYLON.Angle = Angle;
  6993. var Arc2 = /** @class */ (function () {
  6994. /**
  6995. * Creates an Arc object from the three given points : start, middle and end.
  6996. */
  6997. function Arc2(startPoint, midPoint, endPoint) {
  6998. this.startPoint = startPoint;
  6999. this.midPoint = midPoint;
  7000. this.endPoint = endPoint;
  7001. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7002. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7003. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7004. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7005. 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);
  7006. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7007. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7008. var a1 = this.startAngle.degrees();
  7009. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7010. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7011. // angles correction
  7012. if (a2 - a1 > +180.0)
  7013. a2 -= 360.0;
  7014. if (a2 - a1 < -180.0)
  7015. a2 += 360.0;
  7016. if (a3 - a2 > +180.0)
  7017. a3 -= 360.0;
  7018. if (a3 - a2 < -180.0)
  7019. a3 += 360.0;
  7020. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7021. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7022. }
  7023. return Arc2;
  7024. }());
  7025. BABYLON.Arc2 = Arc2;
  7026. var Path2 = /** @class */ (function () {
  7027. /**
  7028. * Creates a Path2 object from the starting 2D coordinates x and y.
  7029. */
  7030. function Path2(x, y) {
  7031. this._points = new Array();
  7032. this._length = 0.0;
  7033. this.closed = false;
  7034. this._points.push(new Vector2(x, y));
  7035. }
  7036. /**
  7037. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7038. * Returns the updated Path2.
  7039. */
  7040. Path2.prototype.addLineTo = function (x, y) {
  7041. if (this.closed) {
  7042. return this;
  7043. }
  7044. var newPoint = new Vector2(x, y);
  7045. var previousPoint = this._points[this._points.length - 1];
  7046. this._points.push(newPoint);
  7047. this._length += newPoint.subtract(previousPoint).length();
  7048. return this;
  7049. };
  7050. /**
  7051. * 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.
  7052. * Returns the updated Path2.
  7053. */
  7054. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7055. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7056. if (this.closed) {
  7057. return this;
  7058. }
  7059. var startPoint = this._points[this._points.length - 1];
  7060. var midPoint = new Vector2(midX, midY);
  7061. var endPoint = new Vector2(endX, endY);
  7062. var arc = new Arc2(startPoint, midPoint, endPoint);
  7063. var increment = arc.angle.radians() / numberOfSegments;
  7064. if (arc.orientation === Orientation.CW)
  7065. increment *= -1;
  7066. var currentAngle = arc.startAngle.radians() + increment;
  7067. for (var i = 0; i < numberOfSegments; i++) {
  7068. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7069. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7070. this.addLineTo(x, y);
  7071. currentAngle += increment;
  7072. }
  7073. return this;
  7074. };
  7075. /**
  7076. * Closes the Path2.
  7077. * Returns the Path2.
  7078. */
  7079. Path2.prototype.close = function () {
  7080. this.closed = true;
  7081. return this;
  7082. };
  7083. /**
  7084. * Returns the Path2 total length (float).
  7085. */
  7086. Path2.prototype.length = function () {
  7087. var result = this._length;
  7088. if (!this.closed) {
  7089. var lastPoint = this._points[this._points.length - 1];
  7090. var firstPoint = this._points[0];
  7091. result += (firstPoint.subtract(lastPoint).length());
  7092. }
  7093. return result;
  7094. };
  7095. /**
  7096. * Returns the Path2 internal array of points.
  7097. */
  7098. Path2.prototype.getPoints = function () {
  7099. return this._points;
  7100. };
  7101. /**
  7102. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7103. */
  7104. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7105. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7106. return Vector2.Zero();
  7107. }
  7108. var lengthPosition = normalizedLengthPosition * this.length();
  7109. var previousOffset = 0;
  7110. for (var i = 0; i < this._points.length; i++) {
  7111. var j = (i + 1) % this._points.length;
  7112. var a = this._points[i];
  7113. var b = this._points[j];
  7114. var bToA = b.subtract(a);
  7115. var nextOffset = (bToA.length() + previousOffset);
  7116. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7117. var dir = bToA.normalize();
  7118. var localOffset = lengthPosition - previousOffset;
  7119. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7120. }
  7121. previousOffset = nextOffset;
  7122. }
  7123. return Vector2.Zero();
  7124. };
  7125. /**
  7126. * Returns a new Path2 starting at the coordinates (x, y).
  7127. */
  7128. Path2.StartingAt = function (x, y) {
  7129. return new Path2(x, y);
  7130. };
  7131. return Path2;
  7132. }());
  7133. BABYLON.Path2 = Path2;
  7134. var Path3D = /** @class */ (function () {
  7135. /**
  7136. * new Path3D(path, normal, raw)
  7137. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7138. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7139. * path : an array of Vector3, the curve axis of the Path3D
  7140. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7141. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7142. */
  7143. function Path3D(path, firstNormal, raw) {
  7144. if (firstNormal === void 0) { firstNormal = null; }
  7145. this.path = path;
  7146. this._curve = new Array();
  7147. this._distances = new Array();
  7148. this._tangents = new Array();
  7149. this._normals = new Array();
  7150. this._binormals = new Array();
  7151. for (var p = 0; p < path.length; p++) {
  7152. this._curve[p] = path[p].clone(); // hard copy
  7153. }
  7154. this._raw = raw || false;
  7155. this._compute(firstNormal);
  7156. }
  7157. /**
  7158. * Returns the Path3D array of successive Vector3 designing its curve.
  7159. */
  7160. Path3D.prototype.getCurve = function () {
  7161. return this._curve;
  7162. };
  7163. /**
  7164. * Returns an array populated with tangent vectors on each Path3D curve point.
  7165. */
  7166. Path3D.prototype.getTangents = function () {
  7167. return this._tangents;
  7168. };
  7169. /**
  7170. * Returns an array populated with normal vectors on each Path3D curve point.
  7171. */
  7172. Path3D.prototype.getNormals = function () {
  7173. return this._normals;
  7174. };
  7175. /**
  7176. * Returns an array populated with binormal vectors on each Path3D curve point.
  7177. */
  7178. Path3D.prototype.getBinormals = function () {
  7179. return this._binormals;
  7180. };
  7181. /**
  7182. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7183. */
  7184. Path3D.prototype.getDistances = function () {
  7185. return this._distances;
  7186. };
  7187. /**
  7188. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7189. * Returns the same object updated.
  7190. */
  7191. Path3D.prototype.update = function (path, firstNormal) {
  7192. if (firstNormal === void 0) { firstNormal = null; }
  7193. for (var p = 0; p < path.length; p++) {
  7194. this._curve[p].x = path[p].x;
  7195. this._curve[p].y = path[p].y;
  7196. this._curve[p].z = path[p].z;
  7197. }
  7198. this._compute(firstNormal);
  7199. return this;
  7200. };
  7201. // private function compute() : computes tangents, normals and binormals
  7202. Path3D.prototype._compute = function (firstNormal) {
  7203. var l = this._curve.length;
  7204. // first and last tangents
  7205. this._tangents[0] = this._getFirstNonNullVector(0);
  7206. if (!this._raw) {
  7207. this._tangents[0].normalize();
  7208. }
  7209. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7210. if (!this._raw) {
  7211. this._tangents[l - 1].normalize();
  7212. }
  7213. // normals and binormals at first point : arbitrary vector with _normalVector()
  7214. var tg0 = this._tangents[0];
  7215. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7216. this._normals[0] = pp0;
  7217. if (!this._raw) {
  7218. this._normals[0].normalize();
  7219. }
  7220. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7221. if (!this._raw) {
  7222. this._binormals[0].normalize();
  7223. }
  7224. this._distances[0] = 0.0;
  7225. // normals and binormals : next points
  7226. var prev; // previous vector (segment)
  7227. var cur; // current vector (segment)
  7228. var curTang; // current tangent
  7229. // previous normal
  7230. var prevBinor; // previous binormal
  7231. for (var i = 1; i < l; i++) {
  7232. // tangents
  7233. prev = this._getLastNonNullVector(i);
  7234. if (i < l - 1) {
  7235. cur = this._getFirstNonNullVector(i);
  7236. this._tangents[i] = prev.add(cur);
  7237. this._tangents[i].normalize();
  7238. }
  7239. this._distances[i] = this._distances[i - 1] + prev.length();
  7240. // normals and binormals
  7241. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7242. curTang = this._tangents[i];
  7243. prevBinor = this._binormals[i - 1];
  7244. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7245. if (!this._raw) {
  7246. this._normals[i].normalize();
  7247. }
  7248. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7249. if (!this._raw) {
  7250. this._binormals[i].normalize();
  7251. }
  7252. }
  7253. };
  7254. // private function getFirstNonNullVector(index)
  7255. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7256. Path3D.prototype._getFirstNonNullVector = function (index) {
  7257. var i = 1;
  7258. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7259. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7260. i++;
  7261. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7262. }
  7263. return nNVector;
  7264. };
  7265. // private function getLastNonNullVector(index)
  7266. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7267. Path3D.prototype._getLastNonNullVector = function (index) {
  7268. var i = 1;
  7269. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7270. while (nLVector.length() === 0 && index > i + 1) {
  7271. i++;
  7272. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7273. }
  7274. return nLVector;
  7275. };
  7276. // private function normalVector(v0, vt, va) :
  7277. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7278. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7279. Path3D.prototype._normalVector = function (v0, vt, va) {
  7280. var normal0;
  7281. var tgl = vt.length();
  7282. if (tgl === 0.0) {
  7283. tgl = 1.0;
  7284. }
  7285. if (va === undefined || va === null) {
  7286. var point;
  7287. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7288. point = new Vector3(0.0, -1.0, 0.0);
  7289. }
  7290. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7291. point = new Vector3(1.0, 0.0, 0.0);
  7292. }
  7293. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7294. point = new Vector3(0.0, 0.0, 1.0);
  7295. }
  7296. else {
  7297. point = Vector3.Zero();
  7298. }
  7299. normal0 = Vector3.Cross(vt, point);
  7300. }
  7301. else {
  7302. normal0 = Vector3.Cross(vt, va);
  7303. Vector3.CrossToRef(normal0, vt, normal0);
  7304. }
  7305. normal0.normalize();
  7306. return normal0;
  7307. };
  7308. return Path3D;
  7309. }());
  7310. BABYLON.Path3D = Path3D;
  7311. var Curve3 = /** @class */ (function () {
  7312. /**
  7313. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7314. * A Curve3 is designed from a series of successive Vector3.
  7315. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7316. */
  7317. function Curve3(points) {
  7318. this._length = 0.0;
  7319. this._points = points;
  7320. this._length = this._computeLength(points);
  7321. }
  7322. /**
  7323. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7324. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7325. * @param v1 (Vector3) the control point
  7326. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7327. * @param nbPoints (integer) the wanted number of points in the curve
  7328. */
  7329. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7330. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7331. var bez = new Array();
  7332. var equation = function (t, val0, val1, val2) {
  7333. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7334. return res;
  7335. };
  7336. for (var i = 0; i <= nbPoints; i++) {
  7337. 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)));
  7338. }
  7339. return new Curve3(bez);
  7340. };
  7341. /**
  7342. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7343. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7344. * @param v1 (Vector3) the first control point
  7345. * @param v2 (Vector3) the second control point
  7346. * @param v3 (Vector3) the end point of the Cubic Bezier
  7347. * @param nbPoints (integer) the wanted number of points in the curve
  7348. */
  7349. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7350. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7351. var bez = new Array();
  7352. var equation = function (t, val0, val1, val2, val3) {
  7353. 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;
  7354. return res;
  7355. };
  7356. for (var i = 0; i <= nbPoints; i++) {
  7357. 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)));
  7358. }
  7359. return new Curve3(bez);
  7360. };
  7361. /**
  7362. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7363. * @param p1 (Vector3) the origin point of the Hermite Spline
  7364. * @param t1 (Vector3) the tangent vector at the origin point
  7365. * @param p2 (Vector3) the end point of the Hermite Spline
  7366. * @param t2 (Vector3) the tangent vector at the end point
  7367. * @param nbPoints (integer) the wanted number of points in the curve
  7368. */
  7369. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7370. var hermite = new Array();
  7371. var step = 1.0 / nbPoints;
  7372. for (var i = 0; i <= nbPoints; i++) {
  7373. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7374. }
  7375. return new Curve3(hermite);
  7376. };
  7377. /**
  7378. * Returns a Curve3 object along a CatmullRom Spline curve :
  7379. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7380. * @param nbPoints (integer) the wanted number of points between each curve control points
  7381. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7382. */
  7383. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7384. var catmullRom = new Array();
  7385. var step = 1.0 / nbPoints;
  7386. var amount = 0.0;
  7387. if (closed) {
  7388. var pointsCount = points.length;
  7389. for (var i = 0; i < pointsCount; i++) {
  7390. amount = 0;
  7391. for (var c = 0; c < nbPoints; c++) {
  7392. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7393. amount += step;
  7394. }
  7395. }
  7396. catmullRom.push(catmullRom[0]);
  7397. }
  7398. else {
  7399. var totalPoints = new Array();
  7400. totalPoints.push(points[0].clone());
  7401. Array.prototype.push.apply(totalPoints, points);
  7402. totalPoints.push(points[points.length - 1].clone());
  7403. for (var i = 0; i < totalPoints.length - 3; i++) {
  7404. amount = 0;
  7405. for (var c = 0; c < nbPoints; c++) {
  7406. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7407. amount += step;
  7408. }
  7409. }
  7410. i--;
  7411. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7412. }
  7413. return new Curve3(catmullRom);
  7414. };
  7415. /**
  7416. * Returns the Curve3 stored array of successive Vector3
  7417. */
  7418. Curve3.prototype.getPoints = function () {
  7419. return this._points;
  7420. };
  7421. /**
  7422. * Returns the computed length (float) of the curve.
  7423. */
  7424. Curve3.prototype.length = function () {
  7425. return this._length;
  7426. };
  7427. /**
  7428. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7429. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7430. * curveA and curveB keep unchanged.
  7431. */
  7432. Curve3.prototype.continue = function (curve) {
  7433. var lastPoint = this._points[this._points.length - 1];
  7434. var continuedPoints = this._points.slice();
  7435. var curvePoints = curve.getPoints();
  7436. for (var i = 1; i < curvePoints.length; i++) {
  7437. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7438. }
  7439. var continuedCurve = new Curve3(continuedPoints);
  7440. return continuedCurve;
  7441. };
  7442. Curve3.prototype._computeLength = function (path) {
  7443. var l = 0;
  7444. for (var i = 1; i < path.length; i++) {
  7445. l += (path[i].subtract(path[i - 1])).length();
  7446. }
  7447. return l;
  7448. };
  7449. return Curve3;
  7450. }());
  7451. BABYLON.Curve3 = Curve3;
  7452. // Vertex formats
  7453. var PositionNormalVertex = /** @class */ (function () {
  7454. function PositionNormalVertex(position, normal) {
  7455. if (position === void 0) { position = Vector3.Zero(); }
  7456. if (normal === void 0) { normal = Vector3.Up(); }
  7457. this.position = position;
  7458. this.normal = normal;
  7459. }
  7460. PositionNormalVertex.prototype.clone = function () {
  7461. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7462. };
  7463. return PositionNormalVertex;
  7464. }());
  7465. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7466. var PositionNormalTextureVertex = /** @class */ (function () {
  7467. function PositionNormalTextureVertex(position, normal, uv) {
  7468. if (position === void 0) { position = Vector3.Zero(); }
  7469. if (normal === void 0) { normal = Vector3.Up(); }
  7470. if (uv === void 0) { uv = Vector2.Zero(); }
  7471. this.position = position;
  7472. this.normal = normal;
  7473. this.uv = uv;
  7474. }
  7475. PositionNormalTextureVertex.prototype.clone = function () {
  7476. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7477. };
  7478. return PositionNormalTextureVertex;
  7479. }());
  7480. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7481. // Temporary pre-allocated objects for engine internal use
  7482. // usage in any internal function :
  7483. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7484. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7485. var Tmp = /** @class */ (function () {
  7486. function Tmp() {
  7487. }
  7488. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7489. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7490. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7491. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7492. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7493. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7494. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7495. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7496. Matrix.Zero(), Matrix.Zero(),
  7497. Matrix.Zero(), Matrix.Zero(),
  7498. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7499. return Tmp;
  7500. }());
  7501. BABYLON.Tmp = Tmp;
  7502. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7503. var MathTmp = /** @class */ (function () {
  7504. function MathTmp() {
  7505. }
  7506. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7507. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7508. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7509. return MathTmp;
  7510. }());
  7511. })(BABYLON || (BABYLON = {}));
  7512. //# sourceMappingURL=babylon.math.js.map
  7513. var BABYLON;
  7514. (function (BABYLON) {
  7515. var Scalar = /** @class */ (function () {
  7516. function Scalar() {
  7517. }
  7518. /**
  7519. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7520. */
  7521. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7522. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7523. var num = a - b;
  7524. return -epsilon <= num && num <= epsilon;
  7525. };
  7526. /**
  7527. * Returns a string : the upper case translation of the number i to hexadecimal.
  7528. */
  7529. Scalar.ToHex = function (i) {
  7530. var str = i.toString(16);
  7531. if (i <= 15) {
  7532. return ("0" + str).toUpperCase();
  7533. }
  7534. return str.toUpperCase();
  7535. };
  7536. /**
  7537. * Returns -1 if value is negative and +1 is value is positive.
  7538. * Returns the value itself if it's equal to zero.
  7539. */
  7540. Scalar.Sign = function (value) {
  7541. value = +value; // convert to a number
  7542. if (value === 0 || isNaN(value))
  7543. return value;
  7544. return value > 0 ? 1 : -1;
  7545. };
  7546. /**
  7547. * Returns the value itself if it's between min and max.
  7548. * Returns min if the value is lower than min.
  7549. * Returns max if the value is greater than max.
  7550. */
  7551. Scalar.Clamp = function (value, min, max) {
  7552. if (min === void 0) { min = 0; }
  7553. if (max === void 0) { max = 1; }
  7554. return Math.min(max, Math.max(min, value));
  7555. };
  7556. /**
  7557. * Returns the log2 of value.
  7558. */
  7559. Scalar.Log2 = function (value) {
  7560. return Math.log(value) * Math.LOG2E;
  7561. };
  7562. /**
  7563. * Loops the value, so that it is never larger than length and never smaller than 0.
  7564. *
  7565. * This is similar to the modulo operator but it works with floating point numbers.
  7566. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7567. * With t = 5 and length = 2.5, the result would be 0.0.
  7568. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7569. */
  7570. Scalar.Repeat = function (value, length) {
  7571. return value - Math.floor(value / length) * length;
  7572. };
  7573. /**
  7574. * Normalize the value between 0.0 and 1.0 using min and max values
  7575. */
  7576. Scalar.Normalize = function (value, min, max) {
  7577. return (value - min) / (max - min);
  7578. };
  7579. /**
  7580. * Denormalize the value from 0.0 and 1.0 using min and max values
  7581. */
  7582. Scalar.Denormalize = function (normalized, min, max) {
  7583. return (normalized * (max - min) + min);
  7584. };
  7585. /**
  7586. * Calculates the shortest difference between two given angles given in degrees.
  7587. */
  7588. Scalar.DeltaAngle = function (current, target) {
  7589. var num = Scalar.Repeat(target - current, 360.0);
  7590. if (num > 180.0) {
  7591. num -= 360.0;
  7592. }
  7593. return num;
  7594. };
  7595. /**
  7596. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7597. *
  7598. * The returned value will move back and forth between 0 and length
  7599. */
  7600. Scalar.PingPong = function (tx, length) {
  7601. var t = Scalar.Repeat(tx, length * 2.0);
  7602. return length - Math.abs(t - length);
  7603. };
  7604. /**
  7605. * Interpolates between min and max with smoothing at the limits.
  7606. *
  7607. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7608. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7609. */
  7610. Scalar.SmoothStep = function (from, to, tx) {
  7611. var t = Scalar.Clamp(tx);
  7612. t = -2.0 * t * t * t + 3.0 * t * t;
  7613. return to * t + from * (1.0 - t);
  7614. };
  7615. /**
  7616. * Moves a value current towards target.
  7617. *
  7618. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7619. * Negative values of maxDelta pushes the value away from target.
  7620. */
  7621. Scalar.MoveTowards = function (current, target, maxDelta) {
  7622. var result = 0;
  7623. if (Math.abs(target - current) <= maxDelta) {
  7624. result = target;
  7625. }
  7626. else {
  7627. result = current + Scalar.Sign(target - current) * maxDelta;
  7628. }
  7629. return result;
  7630. };
  7631. /**
  7632. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7633. *
  7634. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7635. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7636. */
  7637. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7638. var num = Scalar.DeltaAngle(current, target);
  7639. var result = 0;
  7640. if (-maxDelta < num && num < maxDelta) {
  7641. result = target;
  7642. }
  7643. else {
  7644. target = current + num;
  7645. result = Scalar.MoveTowards(current, target, maxDelta);
  7646. }
  7647. return result;
  7648. };
  7649. /**
  7650. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7651. */
  7652. Scalar.Lerp = function (start, end, amount) {
  7653. return start + ((end - start) * amount);
  7654. };
  7655. /**
  7656. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7657. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7658. */
  7659. Scalar.LerpAngle = function (start, end, amount) {
  7660. var num = Scalar.Repeat(end - start, 360.0);
  7661. if (num > 180.0) {
  7662. num -= 360.0;
  7663. }
  7664. return start + num * Scalar.Clamp(amount);
  7665. };
  7666. /**
  7667. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7668. */
  7669. Scalar.InverseLerp = function (a, b, value) {
  7670. var result = 0;
  7671. if (a != b) {
  7672. result = Scalar.Clamp((value - a) / (b - a));
  7673. }
  7674. else {
  7675. result = 0.0;
  7676. }
  7677. return result;
  7678. };
  7679. /**
  7680. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7681. */
  7682. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7683. var squared = amount * amount;
  7684. var cubed = amount * squared;
  7685. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7686. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7687. var part3 = (cubed - (2.0 * squared)) + amount;
  7688. var part4 = cubed - squared;
  7689. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7690. };
  7691. /**
  7692. * Returns a random float number between and min and max values
  7693. */
  7694. Scalar.RandomRange = function (min, max) {
  7695. if (min === max)
  7696. return min;
  7697. return ((Math.random() * (max - min)) + min);
  7698. };
  7699. /**
  7700. * This function returns percentage of a number in a given range.
  7701. *
  7702. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7703. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7704. */
  7705. Scalar.RangeToPercent = function (number, min, max) {
  7706. return ((number - min) / (max - min));
  7707. };
  7708. /**
  7709. * This function returns number that corresponds to the percentage in a given range.
  7710. *
  7711. * PercentToRange(0.34,0,100) will return 34.
  7712. */
  7713. Scalar.PercentToRange = function (percent, min, max) {
  7714. return ((max - min) * percent + min);
  7715. };
  7716. /**
  7717. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7718. * @param angle The angle to normalize in radian.
  7719. * @return The converted angle.
  7720. */
  7721. Scalar.NormalizeRadians = function (angle) {
  7722. // More precise but slower version kept for reference.
  7723. // angle = angle % Tools.TwoPi;
  7724. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7725. //if (angle > Math.PI) {
  7726. // angle -= Tools.TwoPi;
  7727. //}
  7728. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7729. return angle;
  7730. };
  7731. /**
  7732. * Two pi constants convenient for computation.
  7733. */
  7734. Scalar.TwoPi = Math.PI * 2;
  7735. return Scalar;
  7736. }());
  7737. BABYLON.Scalar = Scalar;
  7738. })(BABYLON || (BABYLON = {}));
  7739. //# sourceMappingURL=babylon.math.scalar.js.map
  7740. //# sourceMappingURL=babylon.mixins.js.map
  7741. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7742. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7743. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7744. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7745. //# sourceMappingURL=babylon.webgl2.js.map
  7746. var BABYLON;
  7747. (function (BABYLON) {
  7748. var __decoratorInitialStore = {};
  7749. var __mergedStore = {};
  7750. var _copySource = function (creationFunction, source, instanciate) {
  7751. var destination = creationFunction();
  7752. // Tags
  7753. if (BABYLON.Tags) {
  7754. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7755. }
  7756. var classStore = getMergedStore(destination);
  7757. // Properties
  7758. for (var property in classStore) {
  7759. var propertyDescriptor = classStore[property];
  7760. var sourceProperty = source[property];
  7761. var propertyType = propertyDescriptor.type;
  7762. if (sourceProperty !== undefined && sourceProperty !== null) {
  7763. switch (propertyType) {
  7764. case 0: // Value
  7765. case 6: // Mesh reference
  7766. case 11: // Camera reference
  7767. destination[property] = sourceProperty;
  7768. break;
  7769. case 1: // Texture
  7770. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7771. break;
  7772. case 2: // Color3
  7773. case 3: // FresnelParameters
  7774. case 4: // Vector2
  7775. case 5: // Vector3
  7776. case 7: // Color Curves
  7777. case 10: // Quaternion
  7778. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7779. break;
  7780. }
  7781. }
  7782. }
  7783. return destination;
  7784. };
  7785. function getDirectStore(target) {
  7786. var classKey = target.getClassName();
  7787. if (!__decoratorInitialStore[classKey]) {
  7788. __decoratorInitialStore[classKey] = {};
  7789. }
  7790. return __decoratorInitialStore[classKey];
  7791. }
  7792. /**
  7793. * Return the list of properties flagged as serializable
  7794. * @param target: host object
  7795. */
  7796. function getMergedStore(target) {
  7797. var classKey = target.getClassName();
  7798. if (__mergedStore[classKey]) {
  7799. return __mergedStore[classKey];
  7800. }
  7801. __mergedStore[classKey] = {};
  7802. var store = __mergedStore[classKey];
  7803. var currentTarget = target;
  7804. var currentKey = classKey;
  7805. while (currentKey) {
  7806. var initialStore = __decoratorInitialStore[currentKey];
  7807. for (var property in initialStore) {
  7808. store[property] = initialStore[property];
  7809. }
  7810. var parent_1 = void 0;
  7811. var done = false;
  7812. do {
  7813. parent_1 = Object.getPrototypeOf(currentTarget);
  7814. if (!parent_1.getClassName) {
  7815. done = true;
  7816. break;
  7817. }
  7818. if (parent_1.getClassName() !== currentKey) {
  7819. break;
  7820. }
  7821. currentTarget = parent_1;
  7822. } while (parent_1);
  7823. if (done) {
  7824. break;
  7825. }
  7826. currentKey = parent_1.getClassName();
  7827. currentTarget = parent_1;
  7828. }
  7829. return store;
  7830. }
  7831. function generateSerializableMember(type, sourceName) {
  7832. return function (target, propertyKey) {
  7833. var classStore = getDirectStore(target);
  7834. if (!classStore[propertyKey]) {
  7835. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7836. }
  7837. };
  7838. }
  7839. function generateExpandMember(setCallback, targetKey) {
  7840. if (targetKey === void 0) { targetKey = null; }
  7841. return function (target, propertyKey) {
  7842. var key = targetKey || ("_" + propertyKey);
  7843. Object.defineProperty(target, propertyKey, {
  7844. get: function () {
  7845. return this[key];
  7846. },
  7847. set: function (value) {
  7848. if (this[key] === value) {
  7849. return;
  7850. }
  7851. this[key] = value;
  7852. target[setCallback].apply(this);
  7853. },
  7854. enumerable: true,
  7855. configurable: true
  7856. });
  7857. };
  7858. }
  7859. function expandToProperty(callback, targetKey) {
  7860. if (targetKey === void 0) { targetKey = null; }
  7861. return generateExpandMember(callback, targetKey);
  7862. }
  7863. BABYLON.expandToProperty = expandToProperty;
  7864. function serialize(sourceName) {
  7865. return generateSerializableMember(0, sourceName); // value member
  7866. }
  7867. BABYLON.serialize = serialize;
  7868. function serializeAsTexture(sourceName) {
  7869. return generateSerializableMember(1, sourceName); // texture member
  7870. }
  7871. BABYLON.serializeAsTexture = serializeAsTexture;
  7872. function serializeAsColor3(sourceName) {
  7873. return generateSerializableMember(2, sourceName); // color3 member
  7874. }
  7875. BABYLON.serializeAsColor3 = serializeAsColor3;
  7876. function serializeAsFresnelParameters(sourceName) {
  7877. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7878. }
  7879. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7880. function serializeAsVector2(sourceName) {
  7881. return generateSerializableMember(4, sourceName); // vector2 member
  7882. }
  7883. BABYLON.serializeAsVector2 = serializeAsVector2;
  7884. function serializeAsVector3(sourceName) {
  7885. return generateSerializableMember(5, sourceName); // vector3 member
  7886. }
  7887. BABYLON.serializeAsVector3 = serializeAsVector3;
  7888. function serializeAsMeshReference(sourceName) {
  7889. return generateSerializableMember(6, sourceName); // mesh reference member
  7890. }
  7891. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7892. function serializeAsColorCurves(sourceName) {
  7893. return generateSerializableMember(7, sourceName); // color curves
  7894. }
  7895. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7896. function serializeAsColor4(sourceName) {
  7897. return generateSerializableMember(8, sourceName); // color 4
  7898. }
  7899. BABYLON.serializeAsColor4 = serializeAsColor4;
  7900. function serializeAsImageProcessingConfiguration(sourceName) {
  7901. return generateSerializableMember(9, sourceName); // image processing
  7902. }
  7903. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7904. function serializeAsQuaternion(sourceName) {
  7905. return generateSerializableMember(10, sourceName); // quaternion member
  7906. }
  7907. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7908. /**
  7909. * Decorator used to define property that can be serialized as reference to a camera
  7910. * @param sourceName defines the name of the property to decorate
  7911. */
  7912. function serializeAsCameraReference(sourceName) {
  7913. return generateSerializableMember(11, sourceName); // camera reference member
  7914. }
  7915. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7916. var SerializationHelper = /** @class */ (function () {
  7917. function SerializationHelper() {
  7918. }
  7919. SerializationHelper.Serialize = function (entity, serializationObject) {
  7920. if (!serializationObject) {
  7921. serializationObject = {};
  7922. }
  7923. // Tags
  7924. if (BABYLON.Tags) {
  7925. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7926. }
  7927. var serializedProperties = getMergedStore(entity);
  7928. // Properties
  7929. for (var property in serializedProperties) {
  7930. var propertyDescriptor = serializedProperties[property];
  7931. var targetPropertyName = propertyDescriptor.sourceName || property;
  7932. var propertyType = propertyDescriptor.type;
  7933. var sourceProperty = entity[property];
  7934. if (sourceProperty !== undefined && sourceProperty !== null) {
  7935. switch (propertyType) {
  7936. case 0: // Value
  7937. serializationObject[targetPropertyName] = sourceProperty;
  7938. break;
  7939. case 1: // Texture
  7940. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7941. break;
  7942. case 2: // Color3
  7943. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7944. break;
  7945. case 3: // FresnelParameters
  7946. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7947. break;
  7948. case 4: // Vector2
  7949. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7950. break;
  7951. case 5: // Vector3
  7952. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7953. break;
  7954. case 6: // Mesh reference
  7955. serializationObject[targetPropertyName] = sourceProperty.id;
  7956. break;
  7957. case 7: // Color Curves
  7958. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7959. break;
  7960. case 8: // Color 4
  7961. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7962. break;
  7963. case 9: // Image Processing
  7964. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7965. break;
  7966. case 10: // Quaternion
  7967. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7968. break;
  7969. case 11: // Camera reference
  7970. serializationObject[targetPropertyName] = sourceProperty.id;
  7971. break;
  7972. }
  7973. }
  7974. }
  7975. return serializationObject;
  7976. };
  7977. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7978. if (rootUrl === void 0) { rootUrl = null; }
  7979. var destination = creationFunction();
  7980. if (!rootUrl) {
  7981. rootUrl = "";
  7982. }
  7983. // Tags
  7984. if (BABYLON.Tags) {
  7985. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7986. }
  7987. var classStore = getMergedStore(destination);
  7988. // Properties
  7989. for (var property in classStore) {
  7990. var propertyDescriptor = classStore[property];
  7991. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7992. var propertyType = propertyDescriptor.type;
  7993. if (sourceProperty !== undefined && sourceProperty !== null) {
  7994. var dest = destination;
  7995. switch (propertyType) {
  7996. case 0: // Value
  7997. dest[property] = sourceProperty;
  7998. break;
  7999. case 1: // Texture
  8000. if (scene) {
  8001. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8002. }
  8003. break;
  8004. case 2: // Color3
  8005. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8006. break;
  8007. case 3: // FresnelParameters
  8008. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8009. break;
  8010. case 4: // Vector2
  8011. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8012. break;
  8013. case 5: // Vector3
  8014. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8015. break;
  8016. case 6: // Mesh reference
  8017. if (scene) {
  8018. dest[property] = scene.getLastMeshByID(sourceProperty);
  8019. }
  8020. break;
  8021. case 7: // Color Curves
  8022. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8023. break;
  8024. case 8: // Color 4
  8025. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8026. break;
  8027. case 9: // Image Processing
  8028. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8029. break;
  8030. case 10: // Quaternion
  8031. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8032. break;
  8033. case 11: // Camera reference
  8034. if (scene) {
  8035. dest[property] = scene.getCameraByID(sourceProperty);
  8036. }
  8037. break;
  8038. }
  8039. }
  8040. }
  8041. return destination;
  8042. };
  8043. SerializationHelper.Clone = function (creationFunction, source) {
  8044. return _copySource(creationFunction, source, false);
  8045. };
  8046. SerializationHelper.Instanciate = function (creationFunction, source) {
  8047. return _copySource(creationFunction, source, true);
  8048. };
  8049. return SerializationHelper;
  8050. }());
  8051. BABYLON.SerializationHelper = SerializationHelper;
  8052. })(BABYLON || (BABYLON = {}));
  8053. //# sourceMappingURL=babylon.decorators.js.map
  8054. var BABYLON;
  8055. (function (BABYLON) {
  8056. /**
  8057. * Wrapper class for promise with external resolve and reject.
  8058. */
  8059. var Deferred = /** @class */ (function () {
  8060. /**
  8061. * Constructor for this deferred object.
  8062. */
  8063. function Deferred() {
  8064. var _this = this;
  8065. this.promise = new Promise(function (resolve, reject) {
  8066. _this._resolve = resolve;
  8067. _this._reject = reject;
  8068. });
  8069. }
  8070. Object.defineProperty(Deferred.prototype, "resolve", {
  8071. /**
  8072. * The resolve method of the promise associated with this deferred object.
  8073. */
  8074. get: function () {
  8075. return this._resolve;
  8076. },
  8077. enumerable: true,
  8078. configurable: true
  8079. });
  8080. Object.defineProperty(Deferred.prototype, "reject", {
  8081. /**
  8082. * The reject method of the promise associated with this deferred object.
  8083. */
  8084. get: function () {
  8085. return this._reject;
  8086. },
  8087. enumerable: true,
  8088. configurable: true
  8089. });
  8090. return Deferred;
  8091. }());
  8092. BABYLON.Deferred = Deferred;
  8093. })(BABYLON || (BABYLON = {}));
  8094. //# sourceMappingURL=babylon.deferred.js.map
  8095. var BABYLON;
  8096. (function (BABYLON) {
  8097. /**
  8098. * A class serves as a medium between the observable and its observers
  8099. */
  8100. var EventState = /** @class */ (function () {
  8101. /**
  8102. * Create a new EventState
  8103. * @param mask defines the mask associated with this state
  8104. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8105. * @param target defines the original target of the state
  8106. * @param currentTarget defines the current target of the state
  8107. */
  8108. function EventState(mask, skipNextObservers, target, currentTarget) {
  8109. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8110. this.initalize(mask, skipNextObservers, target, currentTarget);
  8111. }
  8112. /**
  8113. * Initialize the current event state
  8114. * @param mask defines the mask associated with this state
  8115. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8116. * @param target defines the original target of the state
  8117. * @param currentTarget defines the current target of the state
  8118. * @returns the current event state
  8119. */
  8120. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8121. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8122. this.mask = mask;
  8123. this.skipNextObservers = skipNextObservers;
  8124. this.target = target;
  8125. this.currentTarget = currentTarget;
  8126. return this;
  8127. };
  8128. return EventState;
  8129. }());
  8130. BABYLON.EventState = EventState;
  8131. /**
  8132. * Represent an Observer registered to a given Observable object.
  8133. */
  8134. var Observer = /** @class */ (function () {
  8135. /**
  8136. * Creates a new observer
  8137. * @param callback defines the callback to call when the observer is notified
  8138. * @param mask defines the mask of the observer (used to filter notifications)
  8139. * @param scope defines the current scope used to restore the JS context
  8140. */
  8141. function Observer(
  8142. /**
  8143. * Defines the callback to call when the observer is notified
  8144. */
  8145. callback,
  8146. /**
  8147. * Defines the mask of the observer (used to filter notifications)
  8148. */
  8149. mask,
  8150. /**
  8151. * Defines the current scope used to restore the JS context
  8152. */
  8153. scope) {
  8154. if (scope === void 0) { scope = null; }
  8155. this.callback = callback;
  8156. this.mask = mask;
  8157. this.scope = scope;
  8158. /** @hidden */
  8159. this._willBeUnregistered = false;
  8160. /**
  8161. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8162. */
  8163. this.unregisterOnNextCall = false;
  8164. }
  8165. return Observer;
  8166. }());
  8167. BABYLON.Observer = Observer;
  8168. /**
  8169. * Represent a list of observers registered to multiple Observables object.
  8170. */
  8171. var MultiObserver = /** @class */ (function () {
  8172. function MultiObserver() {
  8173. }
  8174. /**
  8175. * Release associated resources
  8176. */
  8177. MultiObserver.prototype.dispose = function () {
  8178. if (this._observers && this._observables) {
  8179. for (var index = 0; index < this._observers.length; index++) {
  8180. this._observables[index].remove(this._observers[index]);
  8181. }
  8182. }
  8183. this._observers = null;
  8184. this._observables = null;
  8185. };
  8186. /**
  8187. * Raise a callback when one of the observable will notify
  8188. * @param observables defines a list of observables to watch
  8189. * @param callback defines the callback to call on notification
  8190. * @param mask defines the mask used to filter notifications
  8191. * @param scope defines the current scope used to restore the JS context
  8192. * @returns the new MultiObserver
  8193. */
  8194. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8195. if (mask === void 0) { mask = -1; }
  8196. if (scope === void 0) { scope = null; }
  8197. var result = new MultiObserver();
  8198. result._observers = new Array();
  8199. result._observables = observables;
  8200. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8201. var observable = observables_1[_i];
  8202. var observer = observable.add(callback, mask, false, scope);
  8203. if (observer) {
  8204. result._observers.push(observer);
  8205. }
  8206. }
  8207. return result;
  8208. };
  8209. return MultiObserver;
  8210. }());
  8211. BABYLON.MultiObserver = MultiObserver;
  8212. /**
  8213. * The Observable class is a simple implementation of the Observable pattern.
  8214. *
  8215. * 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.
  8216. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8217. * 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).
  8218. * 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.
  8219. */
  8220. var Observable = /** @class */ (function () {
  8221. /**
  8222. * Creates a new observable
  8223. * @param onObserverAdded defines a callback to call when a new observer is added
  8224. */
  8225. function Observable(onObserverAdded) {
  8226. this._observers = new Array();
  8227. this._eventState = new EventState(0);
  8228. if (onObserverAdded) {
  8229. this._onObserverAdded = onObserverAdded;
  8230. }
  8231. }
  8232. /**
  8233. * Create a new Observer with the specified callback
  8234. * @param callback the callback that will be executed for that Observer
  8235. * @param mask the mask used to filter observers
  8236. * @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.
  8237. * @param scope optional scope for the callback to be called from
  8238. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8239. * @returns the new observer created for the callback
  8240. */
  8241. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8242. if (mask === void 0) { mask = -1; }
  8243. if (insertFirst === void 0) { insertFirst = false; }
  8244. if (scope === void 0) { scope = null; }
  8245. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8246. if (!callback) {
  8247. return null;
  8248. }
  8249. var observer = new Observer(callback, mask, scope);
  8250. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8251. if (insertFirst) {
  8252. this._observers.unshift(observer);
  8253. }
  8254. else {
  8255. this._observers.push(observer);
  8256. }
  8257. if (this._onObserverAdded) {
  8258. this._onObserverAdded(observer);
  8259. }
  8260. return observer;
  8261. };
  8262. /**
  8263. * Create a new Observer with the specified callback and unregisters after the next notification
  8264. * @param callback the callback that will be executed for that Observer
  8265. * @returns the new observer created for the callback
  8266. */
  8267. Observable.prototype.addOnce = function (callback) {
  8268. return this.add(callback, undefined, undefined, undefined, true);
  8269. };
  8270. /**
  8271. * Remove an Observer from the Observable object
  8272. * @param observer the instance of the Observer to remove
  8273. * @returns false if it doesn't belong to this Observable
  8274. */
  8275. Observable.prototype.remove = function (observer) {
  8276. if (!observer) {
  8277. return false;
  8278. }
  8279. var index = this._observers.indexOf(observer);
  8280. if (index !== -1) {
  8281. this._deferUnregister(observer);
  8282. return true;
  8283. }
  8284. return false;
  8285. };
  8286. /**
  8287. * Remove a callback from the Observable object
  8288. * @param callback the callback to remove
  8289. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8290. * @returns false if it doesn't belong to this Observable
  8291. */
  8292. Observable.prototype.removeCallback = function (callback, scope) {
  8293. for (var index = 0; index < this._observers.length; index++) {
  8294. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8295. this._deferUnregister(this._observers[index]);
  8296. return true;
  8297. }
  8298. }
  8299. return false;
  8300. };
  8301. Observable.prototype._deferUnregister = function (observer) {
  8302. var _this = this;
  8303. observer.unregisterOnNextCall = false;
  8304. observer._willBeUnregistered = true;
  8305. BABYLON.Tools.SetImmediate(function () {
  8306. _this._remove(observer);
  8307. });
  8308. };
  8309. // This should only be called when not iterating over _observers to avoid callback skipping.
  8310. // Removes an observer from the _observer Array.
  8311. Observable.prototype._remove = function (observer) {
  8312. if (!observer) {
  8313. return false;
  8314. }
  8315. var index = this._observers.indexOf(observer);
  8316. if (index !== -1) {
  8317. this._observers.splice(index, 1);
  8318. return true;
  8319. }
  8320. return false;
  8321. };
  8322. /**
  8323. * Notify all Observers by calling their respective callback with the given data
  8324. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8325. * @param eventData defines the data to send to all observers
  8326. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8327. * @param target defines the original target of the state
  8328. * @param currentTarget defines the current target of the state
  8329. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8330. */
  8331. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8332. if (mask === void 0) { mask = -1; }
  8333. if (!this._observers.length) {
  8334. return true;
  8335. }
  8336. var state = this._eventState;
  8337. state.mask = mask;
  8338. state.target = target;
  8339. state.currentTarget = currentTarget;
  8340. state.skipNextObservers = false;
  8341. state.lastReturnValue = eventData;
  8342. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8343. var obs = _a[_i];
  8344. if (obs._willBeUnregistered) {
  8345. continue;
  8346. }
  8347. if (obs.mask & mask) {
  8348. if (obs.scope) {
  8349. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8350. }
  8351. else {
  8352. state.lastReturnValue = obs.callback(eventData, state);
  8353. }
  8354. if (obs.unregisterOnNextCall) {
  8355. this._deferUnregister(obs);
  8356. }
  8357. }
  8358. if (state.skipNextObservers) {
  8359. return false;
  8360. }
  8361. }
  8362. return true;
  8363. };
  8364. /**
  8365. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8366. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8367. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8368. * and it is crucial that all callbacks will be executed.
  8369. * The order of the callbacks is kept, callbacks are not executed parallel.
  8370. *
  8371. * @param eventData The data to be sent to each callback
  8372. * @param mask is used to filter observers defaults to -1
  8373. * @param target defines the callback target (see EventState)
  8374. * @param currentTarget defines he current object in the bubbling phase
  8375. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8376. */
  8377. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8378. var _this = this;
  8379. if (mask === void 0) { mask = -1; }
  8380. // create an empty promise
  8381. var p = Promise.resolve(eventData);
  8382. // no observers? return this promise.
  8383. if (!this._observers.length) {
  8384. return p;
  8385. }
  8386. var state = this._eventState;
  8387. state.mask = mask;
  8388. state.target = target;
  8389. state.currentTarget = currentTarget;
  8390. state.skipNextObservers = false;
  8391. // execute one callback after another (not using Promise.all, the order is important)
  8392. this._observers.forEach(function (obs) {
  8393. if (state.skipNextObservers) {
  8394. return;
  8395. }
  8396. if (obs._willBeUnregistered) {
  8397. return;
  8398. }
  8399. if (obs.mask & mask) {
  8400. if (obs.scope) {
  8401. p = p.then(function (lastReturnedValue) {
  8402. state.lastReturnValue = lastReturnedValue;
  8403. return obs.callback.apply(obs.scope, [eventData, state]);
  8404. });
  8405. }
  8406. else {
  8407. p = p.then(function (lastReturnedValue) {
  8408. state.lastReturnValue = lastReturnedValue;
  8409. return obs.callback(eventData, state);
  8410. });
  8411. }
  8412. if (obs.unregisterOnNextCall) {
  8413. _this._deferUnregister(obs);
  8414. }
  8415. }
  8416. });
  8417. // return the eventData
  8418. return p.then(function () { return eventData; });
  8419. };
  8420. /**
  8421. * Notify a specific observer
  8422. * @param observer defines the observer to notify
  8423. * @param eventData defines the data to be sent to each callback
  8424. * @param mask is used to filter observers defaults to -1
  8425. */
  8426. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8427. if (mask === void 0) { mask = -1; }
  8428. var state = this._eventState;
  8429. state.mask = mask;
  8430. state.skipNextObservers = false;
  8431. observer.callback(eventData, state);
  8432. };
  8433. /**
  8434. * Gets a boolean indicating if the observable has at least one observer
  8435. * @returns true is the Observable has at least one Observer registered
  8436. */
  8437. Observable.prototype.hasObservers = function () {
  8438. return this._observers.length > 0;
  8439. };
  8440. /**
  8441. * Clear the list of observers
  8442. */
  8443. Observable.prototype.clear = function () {
  8444. this._observers = new Array();
  8445. this._onObserverAdded = null;
  8446. };
  8447. /**
  8448. * Clone the current observable
  8449. * @returns a new observable
  8450. */
  8451. Observable.prototype.clone = function () {
  8452. var result = new Observable();
  8453. result._observers = this._observers.slice(0);
  8454. return result;
  8455. };
  8456. /**
  8457. * Does this observable handles observer registered with a given mask
  8458. * @param mask defines the mask to be tested
  8459. * @return whether or not one observer registered with the given mask is handeled
  8460. **/
  8461. Observable.prototype.hasSpecificMask = function (mask) {
  8462. if (mask === void 0) { mask = -1; }
  8463. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8464. var obs = _a[_i];
  8465. if (obs.mask & mask || obs.mask === mask) {
  8466. return true;
  8467. }
  8468. }
  8469. return false;
  8470. };
  8471. return Observable;
  8472. }());
  8473. BABYLON.Observable = Observable;
  8474. })(BABYLON || (BABYLON = {}));
  8475. //# sourceMappingURL=babylon.observable.js.map
  8476. var BABYLON;
  8477. (function (BABYLON) {
  8478. /**
  8479. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8480. */
  8481. var SmartArray = /** @class */ (function () {
  8482. /**
  8483. * Instantiates a Smart Array.
  8484. * @param capacity defines the default capacity of the array.
  8485. */
  8486. function SmartArray(capacity) {
  8487. /**
  8488. * The active length of the array.
  8489. */
  8490. this.length = 0;
  8491. this.data = new Array(capacity);
  8492. this._id = SmartArray._GlobalId++;
  8493. }
  8494. /**
  8495. * Pushes a value at the end of the active data.
  8496. * @param value defines the object to push in the array.
  8497. */
  8498. SmartArray.prototype.push = function (value) {
  8499. this.data[this.length++] = value;
  8500. if (this.length > this.data.length) {
  8501. this.data.length *= 2;
  8502. }
  8503. };
  8504. /**
  8505. * Iterates over the active data and apply the lambda to them.
  8506. * @param func defines the action to apply on each value.
  8507. */
  8508. SmartArray.prototype.forEach = function (func) {
  8509. for (var index = 0; index < this.length; index++) {
  8510. func(this.data[index]);
  8511. }
  8512. };
  8513. /**
  8514. * Sorts the full sets of data.
  8515. * @param compareFn defines the comparison function to apply.
  8516. */
  8517. SmartArray.prototype.sort = function (compareFn) {
  8518. this.data.sort(compareFn);
  8519. };
  8520. /**
  8521. * Resets the active data to an empty array.
  8522. */
  8523. SmartArray.prototype.reset = function () {
  8524. this.length = 0;
  8525. };
  8526. /**
  8527. * Releases all the data from the array as well as the array.
  8528. */
  8529. SmartArray.prototype.dispose = function () {
  8530. this.reset();
  8531. if (this.data) {
  8532. this.data.length = 0;
  8533. this.data = [];
  8534. }
  8535. };
  8536. /**
  8537. * Concats the active data with a given array.
  8538. * @param array defines the data to concatenate with.
  8539. */
  8540. SmartArray.prototype.concat = function (array) {
  8541. if (array.length === 0) {
  8542. return;
  8543. }
  8544. if (this.length + array.length > this.data.length) {
  8545. this.data.length = (this.length + array.length) * 2;
  8546. }
  8547. for (var index = 0; index < array.length; index++) {
  8548. this.data[this.length++] = (array.data || array)[index];
  8549. }
  8550. };
  8551. /**
  8552. * Returns the position of a value in the active data.
  8553. * @param value defines the value to find the index for
  8554. * @returns the index if found in the active data otherwise -1
  8555. */
  8556. SmartArray.prototype.indexOf = function (value) {
  8557. var position = this.data.indexOf(value);
  8558. if (position >= this.length) {
  8559. return -1;
  8560. }
  8561. return position;
  8562. };
  8563. /**
  8564. * Returns whether an element is part of the active data.
  8565. * @param value defines the value to look for
  8566. * @returns true if found in the active data otherwise false
  8567. */
  8568. SmartArray.prototype.contains = function (value) {
  8569. return this.indexOf(value) !== -1;
  8570. };
  8571. // Statics
  8572. SmartArray._GlobalId = 0;
  8573. return SmartArray;
  8574. }());
  8575. BABYLON.SmartArray = SmartArray;
  8576. /**
  8577. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8578. * The data in this array can only be present once
  8579. */
  8580. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8581. __extends(SmartArrayNoDuplicate, _super);
  8582. function SmartArrayNoDuplicate() {
  8583. var _this = _super !== null && _super.apply(this, arguments) || this;
  8584. _this._duplicateId = 0;
  8585. return _this;
  8586. }
  8587. /**
  8588. * Pushes a value at the end of the active data.
  8589. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8590. * @param value defines the object to push in the array.
  8591. */
  8592. SmartArrayNoDuplicate.prototype.push = function (value) {
  8593. _super.prototype.push.call(this, value);
  8594. if (!value.__smartArrayFlags) {
  8595. value.__smartArrayFlags = {};
  8596. }
  8597. value.__smartArrayFlags[this._id] = this._duplicateId;
  8598. };
  8599. /**
  8600. * Pushes a value at the end of the active data.
  8601. * If the data is already present, it won t be added again
  8602. * @param value defines the object to push in the array.
  8603. * @returns true if added false if it was already present
  8604. */
  8605. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8606. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8607. return false;
  8608. }
  8609. this.push(value);
  8610. return true;
  8611. };
  8612. /**
  8613. * Resets the active data to an empty array.
  8614. */
  8615. SmartArrayNoDuplicate.prototype.reset = function () {
  8616. _super.prototype.reset.call(this);
  8617. this._duplicateId++;
  8618. };
  8619. /**
  8620. * Concats the active data with a given array.
  8621. * This ensures no dupplicate will be present in the result.
  8622. * @param array defines the data to concatenate with.
  8623. */
  8624. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8625. if (array.length === 0) {
  8626. return;
  8627. }
  8628. if (this.length + array.length > this.data.length) {
  8629. this.data.length = (this.length + array.length) * 2;
  8630. }
  8631. for (var index = 0; index < array.length; index++) {
  8632. var item = (array.data || array)[index];
  8633. this.pushNoDuplicate(item);
  8634. }
  8635. };
  8636. return SmartArrayNoDuplicate;
  8637. }(SmartArray));
  8638. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8639. })(BABYLON || (BABYLON = {}));
  8640. //# sourceMappingURL=babylon.smartArray.js.map
  8641. var BABYLON;
  8642. (function (BABYLON) {
  8643. /** Class used to store color4 gradient */
  8644. var ColorGradient = /** @class */ (function () {
  8645. function ColorGradient() {
  8646. }
  8647. /**
  8648. * Will get a color picked randomly between color1 and color2.
  8649. * If color2 is undefined then color1 will be used
  8650. * @param result defines the target Color4 to store the result in
  8651. */
  8652. ColorGradient.prototype.getColorToRef = function (result) {
  8653. if (!this.color2) {
  8654. result.copyFrom(this.color1);
  8655. return;
  8656. }
  8657. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8658. };
  8659. return ColorGradient;
  8660. }());
  8661. BABYLON.ColorGradient = ColorGradient;
  8662. /** Class used to store color 3 gradient */
  8663. var Color3Gradient = /** @class */ (function () {
  8664. function Color3Gradient() {
  8665. }
  8666. return Color3Gradient;
  8667. }());
  8668. BABYLON.Color3Gradient = Color3Gradient;
  8669. /** Class used to store factor gradient */
  8670. var FactorGradient = /** @class */ (function () {
  8671. function FactorGradient() {
  8672. }
  8673. /**
  8674. * Will get a number picked randomly between factor1 and factor2.
  8675. * If factor2 is undefined then factor1 will be used
  8676. * @returns the picked number
  8677. */
  8678. FactorGradient.prototype.getFactor = function () {
  8679. if (this.factor2 === undefined) {
  8680. return this.factor1;
  8681. }
  8682. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8683. };
  8684. return FactorGradient;
  8685. }());
  8686. BABYLON.FactorGradient = FactorGradient;
  8687. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8688. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8689. var LoadFileError = /** @class */ (function (_super) {
  8690. __extends(LoadFileError, _super);
  8691. function LoadFileError(message, request) {
  8692. var _this = _super.call(this, message) || this;
  8693. _this.request = request;
  8694. _this.name = "LoadFileError";
  8695. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8696. return _this;
  8697. }
  8698. // Polyfill for Object.setPrototypeOf if necessary.
  8699. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8700. return LoadFileError;
  8701. }(Error));
  8702. BABYLON.LoadFileError = LoadFileError;
  8703. var RetryStrategy = /** @class */ (function () {
  8704. function RetryStrategy() {
  8705. }
  8706. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8707. if (maxRetries === void 0) { maxRetries = 3; }
  8708. if (baseInterval === void 0) { baseInterval = 500; }
  8709. return function (url, request, retryIndex) {
  8710. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8711. return -1;
  8712. }
  8713. return Math.pow(2, retryIndex) * baseInterval;
  8714. };
  8715. };
  8716. return RetryStrategy;
  8717. }());
  8718. BABYLON.RetryStrategy = RetryStrategy;
  8719. // Screenshots
  8720. var screenshotCanvas;
  8721. var cloneValue = function (source, destinationObject) {
  8722. if (!source)
  8723. return null;
  8724. if (source instanceof BABYLON.Mesh) {
  8725. return null;
  8726. }
  8727. if (source instanceof BABYLON.SubMesh) {
  8728. return source.clone(destinationObject);
  8729. }
  8730. else if (source.clone) {
  8731. return source.clone();
  8732. }
  8733. return null;
  8734. };
  8735. var Tools = /** @class */ (function () {
  8736. function Tools() {
  8737. }
  8738. /**
  8739. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8740. * @param u defines the coordinate on X axis
  8741. * @param v defines the coordinate on Y axis
  8742. * @param width defines the width of the source data
  8743. * @param height defines the height of the source data
  8744. * @param pixels defines the source byte array
  8745. * @param color defines the output color
  8746. */
  8747. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8748. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8749. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8750. var position = (wrappedU + wrappedV * width) * 4;
  8751. color.r = pixels[position] / 255;
  8752. color.g = pixels[position + 1] / 255;
  8753. color.b = pixels[position + 2] / 255;
  8754. color.a = pixels[position + 3] / 255;
  8755. };
  8756. /**
  8757. * Interpolates between a and b via alpha
  8758. * @param a The lower value (returned when alpha = 0)
  8759. * @param b The upper value (returned when alpha = 1)
  8760. * @param alpha The interpolation-factor
  8761. * @return The mixed value
  8762. */
  8763. Tools.Mix = function (a, b, alpha) {
  8764. return a * (1 - alpha) + b * alpha;
  8765. };
  8766. Tools.Instantiate = function (className) {
  8767. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8768. return Tools.RegisteredExternalClasses[className];
  8769. }
  8770. var arr = className.split(".");
  8771. var fn = (window || this);
  8772. for (var i = 0, len = arr.length; i < len; i++) {
  8773. fn = fn[arr[i]];
  8774. }
  8775. if (typeof fn !== "function") {
  8776. return null;
  8777. }
  8778. return fn;
  8779. };
  8780. /**
  8781. * Provides a slice function that will work even on IE
  8782. * @param data defines the array to slice
  8783. * @param start defines the start of the data (optional)
  8784. * @param end defines the end of the data (optional)
  8785. * @returns the new sliced array
  8786. */
  8787. Tools.Slice = function (data, start, end) {
  8788. if (data.slice) {
  8789. return data.slice(start, end);
  8790. }
  8791. return Array.prototype.slice.call(data, start, end);
  8792. };
  8793. Tools.SetImmediate = function (action) {
  8794. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8795. window.setImmediate(action);
  8796. }
  8797. else {
  8798. setTimeout(action, 1);
  8799. }
  8800. };
  8801. Tools.IsExponentOfTwo = function (value) {
  8802. var count = 1;
  8803. do {
  8804. count *= 2;
  8805. } while (count < value);
  8806. return count === value;
  8807. };
  8808. /**
  8809. * Returns the nearest 32-bit single precision float representation of a Number
  8810. * @param value A Number. If the parameter is of a different type, it will get converted
  8811. * to a number or to NaN if it cannot be converted
  8812. * @returns number
  8813. */
  8814. Tools.FloatRound = function (value) {
  8815. if (Math.fround) {
  8816. return Math.fround(value);
  8817. }
  8818. return (Tools._tmpFloatArray[0] = value);
  8819. };
  8820. /**
  8821. * Find the next highest power of two.
  8822. * @param x Number to start search from.
  8823. * @return Next highest power of two.
  8824. */
  8825. Tools.CeilingPOT = function (x) {
  8826. x--;
  8827. x |= x >> 1;
  8828. x |= x >> 2;
  8829. x |= x >> 4;
  8830. x |= x >> 8;
  8831. x |= x >> 16;
  8832. x++;
  8833. return x;
  8834. };
  8835. /**
  8836. * Find the next lowest power of two.
  8837. * @param x Number to start search from.
  8838. * @return Next lowest power of two.
  8839. */
  8840. Tools.FloorPOT = function (x) {
  8841. x = x | (x >> 1);
  8842. x = x | (x >> 2);
  8843. x = x | (x >> 4);
  8844. x = x | (x >> 8);
  8845. x = x | (x >> 16);
  8846. return x - (x >> 1);
  8847. };
  8848. /**
  8849. * Find the nearest power of two.
  8850. * @param x Number to start search from.
  8851. * @return Next nearest power of two.
  8852. */
  8853. Tools.NearestPOT = function (x) {
  8854. var c = Tools.CeilingPOT(x);
  8855. var f = Tools.FloorPOT(x);
  8856. return (c - x) > (x - f) ? f : c;
  8857. };
  8858. Tools.GetExponentOfTwo = function (value, max, mode) {
  8859. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8860. var pot;
  8861. switch (mode) {
  8862. case BABYLON.Engine.SCALEMODE_FLOOR:
  8863. pot = Tools.FloorPOT(value);
  8864. break;
  8865. case BABYLON.Engine.SCALEMODE_NEAREST:
  8866. pot = Tools.NearestPOT(value);
  8867. break;
  8868. case BABYLON.Engine.SCALEMODE_CEILING:
  8869. default:
  8870. pot = Tools.CeilingPOT(value);
  8871. break;
  8872. }
  8873. return Math.min(pot, max);
  8874. };
  8875. Tools.GetFilename = function (path) {
  8876. var index = path.lastIndexOf("/");
  8877. if (index < 0)
  8878. return path;
  8879. return path.substring(index + 1);
  8880. };
  8881. /**
  8882. * Extracts the "folder" part of a path (everything before the filename).
  8883. * @param uri The URI to extract the info from
  8884. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8885. * @returns The "folder" part of the path
  8886. */
  8887. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8888. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8889. var index = uri.lastIndexOf("/");
  8890. if (index < 0) {
  8891. if (returnUnchangedIfNoSlash) {
  8892. return uri;
  8893. }
  8894. return "";
  8895. }
  8896. return uri.substring(0, index + 1);
  8897. };
  8898. Tools.GetDOMTextContent = function (element) {
  8899. var result = "";
  8900. var child = element.firstChild;
  8901. while (child) {
  8902. if (child.nodeType === 3) {
  8903. result += child.textContent;
  8904. }
  8905. child = child.nextSibling;
  8906. }
  8907. return result;
  8908. };
  8909. Tools.ToDegrees = function (angle) {
  8910. return angle * 180 / Math.PI;
  8911. };
  8912. Tools.ToRadians = function (angle) {
  8913. return angle * Math.PI / 180;
  8914. };
  8915. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8916. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8917. var output = "";
  8918. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8919. var i = 0;
  8920. var bytes = new Uint8Array(buffer);
  8921. while (i < bytes.length) {
  8922. chr1 = bytes[i++];
  8923. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8924. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8925. enc1 = chr1 >> 2;
  8926. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8927. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8928. enc4 = chr3 & 63;
  8929. if (isNaN(chr2)) {
  8930. enc3 = enc4 = 64;
  8931. }
  8932. else if (isNaN(chr3)) {
  8933. enc4 = 64;
  8934. }
  8935. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8936. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8937. }
  8938. return "data:image/png;base64," + output;
  8939. };
  8940. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8941. if (bias === void 0) { bias = null; }
  8942. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8943. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8944. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8945. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8946. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8947. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8948. }
  8949. if (bias) {
  8950. minimum.x -= minimum.x * bias.x + bias.y;
  8951. minimum.y -= minimum.y * bias.x + bias.y;
  8952. minimum.z -= minimum.z * bias.x + bias.y;
  8953. maximum.x += maximum.x * bias.x + bias.y;
  8954. maximum.y += maximum.y * bias.x + bias.y;
  8955. maximum.z += maximum.z * bias.x + bias.y;
  8956. }
  8957. return {
  8958. minimum: minimum,
  8959. maximum: maximum
  8960. };
  8961. };
  8962. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8963. if (bias === void 0) { bias = null; }
  8964. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8965. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8966. if (!stride) {
  8967. stride = 3;
  8968. }
  8969. for (var index = start; index < start + count; index++) {
  8970. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8971. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8972. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8973. }
  8974. if (bias) {
  8975. minimum.x -= minimum.x * bias.x + bias.y;
  8976. minimum.y -= minimum.y * bias.x + bias.y;
  8977. minimum.z -= minimum.z * bias.x + bias.y;
  8978. maximum.x += maximum.x * bias.x + bias.y;
  8979. maximum.y += maximum.y * bias.x + bias.y;
  8980. maximum.z += maximum.z * bias.x + bias.y;
  8981. }
  8982. return {
  8983. minimum: minimum,
  8984. maximum: maximum
  8985. };
  8986. };
  8987. Tools.Vector2ArrayFeeder = function (array) {
  8988. return function (index) {
  8989. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8990. var length = isFloatArray ? array.length / 2 : array.length;
  8991. if (index >= length) {
  8992. return null;
  8993. }
  8994. if (isFloatArray) {
  8995. var fa = array;
  8996. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8997. }
  8998. var a = array;
  8999. return a[index];
  9000. };
  9001. };
  9002. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9003. if (bias === void 0) { bias = null; }
  9004. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9005. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9006. var i = 0;
  9007. var cur = feeder(i++);
  9008. while (cur) {
  9009. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9010. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9011. cur = feeder(i++);
  9012. }
  9013. if (bias) {
  9014. minimum.x -= minimum.x * bias.x + bias.y;
  9015. minimum.y -= minimum.y * bias.x + bias.y;
  9016. maximum.x += maximum.x * bias.x + bias.y;
  9017. maximum.y += maximum.y * bias.x + bias.y;
  9018. }
  9019. return {
  9020. minimum: minimum,
  9021. maximum: maximum
  9022. };
  9023. };
  9024. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9025. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9026. return null;
  9027. return Array.isArray(obj) ? obj : [obj];
  9028. };
  9029. // Misc.
  9030. Tools.GetPointerPrefix = function () {
  9031. var eventPrefix = "pointer";
  9032. // Check if pointer events are supported
  9033. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9034. eventPrefix = "mouse";
  9035. }
  9036. return eventPrefix;
  9037. };
  9038. /**
  9039. * @param func - the function to be called
  9040. * @param requester - the object that will request the next frame. Falls back to window.
  9041. */
  9042. Tools.QueueNewFrame = function (func, requester) {
  9043. if (!Tools.IsWindowObjectExist()) {
  9044. return setTimeout(func, 16);
  9045. }
  9046. if (!requester) {
  9047. requester = window;
  9048. }
  9049. if (requester.requestAnimationFrame) {
  9050. return requester.requestAnimationFrame(func);
  9051. }
  9052. else if (requester.msRequestAnimationFrame) {
  9053. return requester.msRequestAnimationFrame(func);
  9054. }
  9055. else if (requester.webkitRequestAnimationFrame) {
  9056. return requester.webkitRequestAnimationFrame(func);
  9057. }
  9058. else if (requester.mozRequestAnimationFrame) {
  9059. return requester.mozRequestAnimationFrame(func);
  9060. }
  9061. else if (requester.oRequestAnimationFrame) {
  9062. return requester.oRequestAnimationFrame(func);
  9063. }
  9064. else {
  9065. return window.setTimeout(func, 16);
  9066. }
  9067. };
  9068. Tools.RequestFullscreen = function (element) {
  9069. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9070. if (!requestFunction)
  9071. return;
  9072. requestFunction.call(element);
  9073. };
  9074. Tools.ExitFullscreen = function () {
  9075. if (document.exitFullscreen) {
  9076. document.exitFullscreen();
  9077. }
  9078. else if (document.mozCancelFullScreen) {
  9079. document.mozCancelFullScreen();
  9080. }
  9081. else if (document.webkitCancelFullScreen) {
  9082. document.webkitCancelFullScreen();
  9083. }
  9084. else if (document.msCancelFullScreen) {
  9085. document.msCancelFullScreen();
  9086. }
  9087. };
  9088. Tools.SetCorsBehavior = function (url, element) {
  9089. if (url && url.indexOf("data:") === 0) {
  9090. return;
  9091. }
  9092. if (Tools.CorsBehavior) {
  9093. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9094. element.crossOrigin = Tools.CorsBehavior;
  9095. }
  9096. else {
  9097. var result = Tools.CorsBehavior(url);
  9098. if (result) {
  9099. element.crossOrigin = result;
  9100. }
  9101. }
  9102. }
  9103. };
  9104. // External files
  9105. Tools.CleanUrl = function (url) {
  9106. url = url.replace(/#/mg, "%23");
  9107. return url;
  9108. };
  9109. /**
  9110. * Loads an image as an HTMLImageElement.
  9111. * @param input url string, ArrayBuffer, or Blob to load
  9112. * @param onLoad callback called when the image successfully loads
  9113. * @param onError callback called when the image fails to load
  9114. * @param database database for caching
  9115. * @returns the HTMLImageElement of the loaded image
  9116. */
  9117. Tools.LoadImage = function (input, onLoad, onError, database) {
  9118. var url;
  9119. var usingObjectURL = false;
  9120. if (input instanceof ArrayBuffer) {
  9121. url = URL.createObjectURL(new Blob([input]));
  9122. usingObjectURL = true;
  9123. }
  9124. else if (input instanceof Blob) {
  9125. url = URL.createObjectURL(input);
  9126. usingObjectURL = true;
  9127. }
  9128. else {
  9129. url = Tools.CleanUrl(input);
  9130. url = Tools.PreprocessUrl(input);
  9131. }
  9132. var img = new Image();
  9133. Tools.SetCorsBehavior(url, img);
  9134. var loadHandler = function () {
  9135. if (usingObjectURL && img.src) {
  9136. URL.revokeObjectURL(img.src);
  9137. }
  9138. img.removeEventListener("load", loadHandler);
  9139. img.removeEventListener("error", errorHandler);
  9140. onLoad(img);
  9141. };
  9142. var errorHandler = function (err) {
  9143. if (usingObjectURL && img.src) {
  9144. URL.revokeObjectURL(img.src);
  9145. }
  9146. img.removeEventListener("load", loadHandler);
  9147. img.removeEventListener("error", errorHandler);
  9148. Tools.Error("Error while trying to load image: " + input);
  9149. if (onError) {
  9150. onError("Error while trying to load image: " + input, err);
  9151. }
  9152. };
  9153. img.addEventListener("load", loadHandler);
  9154. img.addEventListener("error", errorHandler);
  9155. var noIndexedDB = function () {
  9156. img.src = url;
  9157. };
  9158. var loadFromIndexedDB = function () {
  9159. if (database) {
  9160. database.loadImageFromDB(url, img);
  9161. }
  9162. };
  9163. //ANY database to do!
  9164. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9165. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9166. }
  9167. else {
  9168. if (url.indexOf("file:") !== -1) {
  9169. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9170. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9171. try {
  9172. var blobURL;
  9173. try {
  9174. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9175. }
  9176. catch (ex) {
  9177. // Chrome doesn't support oneTimeOnly parameter
  9178. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9179. }
  9180. img.src = blobURL;
  9181. usingObjectURL = true;
  9182. }
  9183. catch (e) {
  9184. img.src = "";
  9185. }
  9186. return img;
  9187. }
  9188. }
  9189. noIndexedDB();
  9190. }
  9191. return img;
  9192. };
  9193. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9194. url = Tools.CleanUrl(url);
  9195. url = Tools.PreprocessUrl(url);
  9196. // If file and file input are set
  9197. if (url.indexOf("file:") !== -1) {
  9198. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9199. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9200. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9201. }
  9202. }
  9203. var loadUrl = Tools.BaseUrl + url;
  9204. var aborted = false;
  9205. var fileRequest = {
  9206. onCompleteObservable: new BABYLON.Observable(),
  9207. abort: function () { return aborted = true; },
  9208. };
  9209. var requestFile = function () {
  9210. var request = new XMLHttpRequest();
  9211. var retryHandle = null;
  9212. fileRequest.abort = function () {
  9213. aborted = true;
  9214. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9215. request.abort();
  9216. }
  9217. if (retryHandle !== null) {
  9218. clearTimeout(retryHandle);
  9219. retryHandle = null;
  9220. }
  9221. };
  9222. var retryLoop = function (retryIndex) {
  9223. request.open('GET', loadUrl, true);
  9224. if (useArrayBuffer) {
  9225. request.responseType = "arraybuffer";
  9226. }
  9227. if (onProgress) {
  9228. request.addEventListener("progress", onProgress);
  9229. }
  9230. var onLoadEnd = function () {
  9231. request.removeEventListener("loadend", onLoadEnd);
  9232. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9233. fileRequest.onCompleteObservable.clear();
  9234. };
  9235. request.addEventListener("loadend", onLoadEnd);
  9236. var onReadyStateChange = function () {
  9237. if (aborted) {
  9238. return;
  9239. }
  9240. // In case of undefined state in some browsers.
  9241. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9242. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9243. request.removeEventListener("readystatechange", onReadyStateChange);
  9244. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9245. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9246. return;
  9247. }
  9248. var retryStrategy = Tools.DefaultRetryStrategy;
  9249. if (retryStrategy) {
  9250. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9251. if (waitTime !== -1) {
  9252. // Prevent the request from completing for retry.
  9253. request.removeEventListener("loadend", onLoadEnd);
  9254. request = new XMLHttpRequest();
  9255. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9256. return;
  9257. }
  9258. }
  9259. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9260. if (onError) {
  9261. onError(request, e);
  9262. }
  9263. else {
  9264. throw e;
  9265. }
  9266. }
  9267. };
  9268. request.addEventListener("readystatechange", onReadyStateChange);
  9269. request.send();
  9270. };
  9271. retryLoop(0);
  9272. };
  9273. // Caching all files
  9274. if (database && database.enableSceneOffline) {
  9275. var noIndexedDB_1 = function (request) {
  9276. if (request && request.status > 400) {
  9277. if (onError) {
  9278. onError(request);
  9279. }
  9280. }
  9281. else {
  9282. if (!aborted) {
  9283. requestFile();
  9284. }
  9285. }
  9286. };
  9287. var loadFromIndexedDB = function () {
  9288. // TODO: database needs to support aborting and should return a IFileRequest
  9289. if (aborted) {
  9290. return;
  9291. }
  9292. if (database) {
  9293. database.loadFileFromDB(url, function (data) {
  9294. if (!aborted) {
  9295. onSuccess(data);
  9296. }
  9297. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9298. }, onProgress ? function (event) {
  9299. if (!aborted) {
  9300. onProgress(event);
  9301. }
  9302. } : undefined, noIndexedDB_1, useArrayBuffer);
  9303. }
  9304. };
  9305. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9306. }
  9307. else {
  9308. requestFile();
  9309. }
  9310. return fileRequest;
  9311. };
  9312. /**
  9313. * Load a script (identified by an url). When the url returns, the
  9314. * content of this file is added into a new script element, attached to the DOM (body element)
  9315. */
  9316. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9317. if (!Tools.IsWindowObjectExist()) {
  9318. return;
  9319. }
  9320. var head = document.getElementsByTagName('head')[0];
  9321. var script = document.createElement('script');
  9322. script.type = 'text/javascript';
  9323. script.src = scriptUrl;
  9324. script.onload = function () {
  9325. if (onSuccess) {
  9326. onSuccess();
  9327. }
  9328. };
  9329. script.onerror = function (e) {
  9330. if (onError) {
  9331. onError("Unable to load script '" + scriptUrl + "'", e);
  9332. }
  9333. };
  9334. head.appendChild(script);
  9335. };
  9336. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9337. var reader = new FileReader();
  9338. var request = {
  9339. onCompleteObservable: new BABYLON.Observable(),
  9340. abort: function () { return reader.abort(); },
  9341. };
  9342. reader.onloadend = function (e) {
  9343. request.onCompleteObservable.notifyObservers(request);
  9344. };
  9345. reader.onload = function (e) {
  9346. //target doesn't have result from ts 1.3
  9347. callback(e.target['result']);
  9348. };
  9349. reader.onprogress = progressCallback;
  9350. reader.readAsDataURL(fileToLoad);
  9351. return request;
  9352. };
  9353. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9354. var reader = new FileReader();
  9355. var request = {
  9356. onCompleteObservable: new BABYLON.Observable(),
  9357. abort: function () { return reader.abort(); },
  9358. };
  9359. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9360. reader.onerror = function (e) {
  9361. Tools.Log("Error while reading file: " + fileToLoad.name);
  9362. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9363. };
  9364. reader.onload = function (e) {
  9365. //target doesn't have result from ts 1.3
  9366. callback(e.target['result']);
  9367. };
  9368. if (progressCallBack) {
  9369. reader.onprogress = progressCallBack;
  9370. }
  9371. if (!useArrayBuffer) {
  9372. // Asynchronous read
  9373. reader.readAsText(fileToLoad);
  9374. }
  9375. else {
  9376. reader.readAsArrayBuffer(fileToLoad);
  9377. }
  9378. return request;
  9379. };
  9380. //returns a downloadable url to a file content.
  9381. Tools.FileAsURL = function (content) {
  9382. var fileBlob = new Blob([content]);
  9383. var url = window.URL || window.webkitURL;
  9384. var link = url.createObjectURL(fileBlob);
  9385. return link;
  9386. };
  9387. // Misc.
  9388. Tools.Format = function (value, decimals) {
  9389. if (decimals === void 0) { decimals = 2; }
  9390. return value.toFixed(decimals);
  9391. };
  9392. Tools.CheckExtends = function (v, min, max) {
  9393. if (v.x < min.x)
  9394. min.x = v.x;
  9395. if (v.y < min.y)
  9396. min.y = v.y;
  9397. if (v.z < min.z)
  9398. min.z = v.z;
  9399. if (v.x > max.x)
  9400. max.x = v.x;
  9401. if (v.y > max.y)
  9402. max.y = v.y;
  9403. if (v.z > max.z)
  9404. max.z = v.z;
  9405. };
  9406. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9407. for (var prop in source) {
  9408. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9409. continue;
  9410. }
  9411. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9412. continue;
  9413. }
  9414. var sourceValue = source[prop];
  9415. var typeOfSourceValue = typeof sourceValue;
  9416. if (typeOfSourceValue === "function") {
  9417. continue;
  9418. }
  9419. try {
  9420. if (typeOfSourceValue === "object") {
  9421. if (sourceValue instanceof Array) {
  9422. destination[prop] = [];
  9423. if (sourceValue.length > 0) {
  9424. if (typeof sourceValue[0] == "object") {
  9425. for (var index = 0; index < sourceValue.length; index++) {
  9426. var clonedValue = cloneValue(sourceValue[index], destination);
  9427. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9428. destination[prop].push(clonedValue);
  9429. }
  9430. }
  9431. }
  9432. else {
  9433. destination[prop] = sourceValue.slice(0);
  9434. }
  9435. }
  9436. }
  9437. else {
  9438. destination[prop] = cloneValue(sourceValue, destination);
  9439. }
  9440. }
  9441. else {
  9442. destination[prop] = sourceValue;
  9443. }
  9444. }
  9445. catch (e) {
  9446. // Just ignore error (it could be because of a read-only property)
  9447. }
  9448. }
  9449. };
  9450. Tools.IsEmpty = function (obj) {
  9451. for (var i in obj) {
  9452. if (obj.hasOwnProperty(i)) {
  9453. return false;
  9454. }
  9455. }
  9456. return true;
  9457. };
  9458. Tools.RegisterTopRootEvents = function (events) {
  9459. for (var index = 0; index < events.length; index++) {
  9460. var event = events[index];
  9461. window.addEventListener(event.name, event.handler, false);
  9462. try {
  9463. if (window.parent) {
  9464. window.parent.addEventListener(event.name, event.handler, false);
  9465. }
  9466. }
  9467. catch (e) {
  9468. // Silently fails...
  9469. }
  9470. }
  9471. };
  9472. Tools.UnregisterTopRootEvents = function (events) {
  9473. for (var index = 0; index < events.length; index++) {
  9474. var event = events[index];
  9475. window.removeEventListener(event.name, event.handler);
  9476. try {
  9477. if (window.parent) {
  9478. window.parent.removeEventListener(event.name, event.handler);
  9479. }
  9480. }
  9481. catch (e) {
  9482. // Silently fails...
  9483. }
  9484. }
  9485. };
  9486. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9487. if (mimeType === void 0) { mimeType = "image/png"; }
  9488. // Read the contents of the framebuffer
  9489. var numberOfChannelsByLine = width * 4;
  9490. var halfHeight = height / 2;
  9491. //Reading datas from WebGL
  9492. var data = engine.readPixels(0, 0, width, height);
  9493. //To flip image on Y axis.
  9494. for (var i = 0; i < halfHeight; i++) {
  9495. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9496. var currentCell = j + i * numberOfChannelsByLine;
  9497. var targetLine = height - i - 1;
  9498. var targetCell = j + targetLine * numberOfChannelsByLine;
  9499. var temp = data[currentCell];
  9500. data[currentCell] = data[targetCell];
  9501. data[targetCell] = temp;
  9502. }
  9503. }
  9504. // Create a 2D canvas to store the result
  9505. if (!screenshotCanvas) {
  9506. screenshotCanvas = document.createElement('canvas');
  9507. }
  9508. screenshotCanvas.width = width;
  9509. screenshotCanvas.height = height;
  9510. var context = screenshotCanvas.getContext('2d');
  9511. if (context) {
  9512. // Copy the pixels to a 2D canvas
  9513. var imageData = context.createImageData(width, height);
  9514. var castData = (imageData.data);
  9515. castData.set(data);
  9516. context.putImageData(imageData, 0, 0);
  9517. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9518. }
  9519. };
  9520. /**
  9521. * Converts the canvas data to blob.
  9522. * This acts as a polyfill for browsers not supporting the to blob function.
  9523. * @param canvas Defines the canvas to extract the data from
  9524. * @param successCallback Defines the callback triggered once the data are available
  9525. * @param mimeType Defines the mime type of the result
  9526. */
  9527. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9528. if (mimeType === void 0) { mimeType = "image/png"; }
  9529. // We need HTMLCanvasElement.toBlob for HD screenshots
  9530. if (!canvas.toBlob) {
  9531. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9532. canvas.toBlob = function (callback, type, quality) {
  9533. var _this = this;
  9534. setTimeout(function () {
  9535. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9536. for (var i = 0; i < len; i++) {
  9537. arr[i] = binStr.charCodeAt(i);
  9538. }
  9539. callback(new Blob([arr]));
  9540. });
  9541. };
  9542. }
  9543. canvas.toBlob(function (blob) {
  9544. successCallback(blob);
  9545. }, mimeType);
  9546. };
  9547. /**
  9548. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9549. * @param successCallback Defines the callback triggered once the data are available
  9550. * @param mimeType Defines the mime type of the result
  9551. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9552. */
  9553. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9554. if (mimeType === void 0) { mimeType = "image/png"; }
  9555. if (successCallback) {
  9556. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9557. successCallback(base64Image);
  9558. }
  9559. else {
  9560. this.ToBlob(screenshotCanvas, function (blob) {
  9561. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9562. if (("download" in document.createElement("a"))) {
  9563. if (!fileName) {
  9564. var date = new Date();
  9565. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9566. fileName = "screenshot_" + stringDate + ".png";
  9567. }
  9568. Tools.Download(blob, fileName);
  9569. }
  9570. else {
  9571. var url = URL.createObjectURL(blob);
  9572. var newWindow = window.open("");
  9573. if (!newWindow)
  9574. return;
  9575. var img = newWindow.document.createElement("img");
  9576. img.onload = function () {
  9577. // no longer need to read the blob so it's revoked
  9578. URL.revokeObjectURL(url);
  9579. };
  9580. img.src = url;
  9581. newWindow.document.body.appendChild(img);
  9582. }
  9583. }, mimeType);
  9584. }
  9585. };
  9586. /**
  9587. * Downloads a blob in the browser
  9588. * @param blob defines the blob to download
  9589. * @param fileName defines the name of the downloaded file
  9590. */
  9591. Tools.Download = function (blob, fileName) {
  9592. if (navigator && navigator.msSaveBlob) {
  9593. navigator.msSaveBlob(blob, fileName);
  9594. return;
  9595. }
  9596. var url = window.URL.createObjectURL(blob);
  9597. var a = document.createElement("a");
  9598. document.body.appendChild(a);
  9599. a.style.display = "none";
  9600. a.href = url;
  9601. a.download = fileName;
  9602. a.addEventListener("click", function () {
  9603. if (a.parentElement) {
  9604. a.parentElement.removeChild(a);
  9605. }
  9606. });
  9607. a.click();
  9608. window.URL.revokeObjectURL(url);
  9609. };
  9610. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9611. if (mimeType === void 0) { mimeType = "image/png"; }
  9612. var width;
  9613. var height;
  9614. // If a precision value is specified
  9615. if (size.precision) {
  9616. width = Math.round(engine.getRenderWidth() * size.precision);
  9617. height = Math.round(width / engine.getAspectRatio(camera));
  9618. }
  9619. else if (size.width && size.height) {
  9620. width = size.width;
  9621. height = size.height;
  9622. }
  9623. //If passing only width, computing height to keep display canvas ratio.
  9624. else if (size.width && !size.height) {
  9625. width = size.width;
  9626. height = Math.round(width / engine.getAspectRatio(camera));
  9627. }
  9628. //If passing only height, computing width to keep display canvas ratio.
  9629. else if (size.height && !size.width) {
  9630. height = size.height;
  9631. width = Math.round(height * engine.getAspectRatio(camera));
  9632. }
  9633. //Assuming here that "size" parameter is a number
  9634. else if (!isNaN(size)) {
  9635. height = size;
  9636. width = size;
  9637. }
  9638. else {
  9639. Tools.Error("Invalid 'size' parameter !");
  9640. return;
  9641. }
  9642. if (!screenshotCanvas) {
  9643. screenshotCanvas = document.createElement('canvas');
  9644. }
  9645. screenshotCanvas.width = width;
  9646. screenshotCanvas.height = height;
  9647. var renderContext = screenshotCanvas.getContext("2d");
  9648. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9649. var newWidth = width;
  9650. var newHeight = newWidth / ratio;
  9651. if (newHeight > height) {
  9652. newHeight = height;
  9653. newWidth = newHeight * ratio;
  9654. }
  9655. var offsetX = Math.max(0, width - newWidth) / 2;
  9656. var offsetY = Math.max(0, height - newHeight) / 2;
  9657. var renderingCanvas = engine.getRenderingCanvas();
  9658. if (renderContext && renderingCanvas) {
  9659. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9660. }
  9661. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9662. };
  9663. /**
  9664. * Generates an image screenshot from the specified camera.
  9665. *
  9666. * @param engine The engine to use for rendering
  9667. * @param camera The camera to use for rendering
  9668. * @param size This parameter can be set to a single number or to an object with the
  9669. * following (optional) properties: precision, width, height. If a single number is passed,
  9670. * it will be used for both width and height. If an object is passed, the screenshot size
  9671. * will be derived from the parameters. The precision property is a multiplier allowing
  9672. * rendering at a higher or lower resolution.
  9673. * @param successCallback The callback receives a single parameter which contains the
  9674. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9675. * src parameter of an <img> to display it.
  9676. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9677. * Check your browser for supported MIME types.
  9678. * @param samples Texture samples (default: 1)
  9679. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9680. * @param fileName A name for for the downloaded file.
  9681. * @constructor
  9682. */
  9683. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9684. if (mimeType === void 0) { mimeType = "image/png"; }
  9685. if (samples === void 0) { samples = 1; }
  9686. if (antialiasing === void 0) { antialiasing = false; }
  9687. var width;
  9688. var height;
  9689. //If a precision value is specified
  9690. if (size.precision) {
  9691. width = Math.round(engine.getRenderWidth() * size.precision);
  9692. height = Math.round(width / engine.getAspectRatio(camera));
  9693. size = { width: width, height: height };
  9694. }
  9695. else if (size.width && size.height) {
  9696. width = size.width;
  9697. height = size.height;
  9698. }
  9699. //If passing only width, computing height to keep display canvas ratio.
  9700. else if (size.width && !size.height) {
  9701. width = size.width;
  9702. height = Math.round(width / engine.getAspectRatio(camera));
  9703. size = { width: width, height: height };
  9704. }
  9705. //If passing only height, computing width to keep display canvas ratio.
  9706. else if (size.height && !size.width) {
  9707. height = size.height;
  9708. width = Math.round(height * engine.getAspectRatio(camera));
  9709. size = { width: width, height: height };
  9710. }
  9711. //Assuming here that "size" parameter is a number
  9712. else if (!isNaN(size)) {
  9713. height = size;
  9714. width = size;
  9715. }
  9716. else {
  9717. Tools.Error("Invalid 'size' parameter !");
  9718. return;
  9719. }
  9720. var scene = camera.getScene();
  9721. var previousCamera = null;
  9722. if (scene.activeCamera !== camera) {
  9723. previousCamera = scene.activeCamera;
  9724. scene.activeCamera = camera;
  9725. }
  9726. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9727. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9728. texture.renderList = null;
  9729. texture.samples = samples;
  9730. if (antialiasing) {
  9731. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9732. }
  9733. texture.onAfterRenderObservable.add(function () {
  9734. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9735. });
  9736. scene.incrementRenderId();
  9737. scene.resetCachedMaterial();
  9738. texture.render(true);
  9739. texture.dispose();
  9740. if (previousCamera) {
  9741. scene.activeCamera = previousCamera;
  9742. }
  9743. camera.getProjectionMatrix(true); // Force cache refresh;
  9744. };
  9745. // XHR response validator for local file scenario
  9746. Tools.ValidateXHRData = function (xhr, dataType) {
  9747. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9748. if (dataType === void 0) { dataType = 7; }
  9749. try {
  9750. if (dataType & 1) {
  9751. if (xhr.responseText && xhr.responseText.length > 0) {
  9752. return true;
  9753. }
  9754. else if (dataType === 1) {
  9755. return false;
  9756. }
  9757. }
  9758. if (dataType & 2) {
  9759. // Check header width and height since there is no "TGA" magic number
  9760. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9761. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9762. return true;
  9763. }
  9764. else if (dataType === 2) {
  9765. return false;
  9766. }
  9767. }
  9768. if (dataType & 4) {
  9769. // Check for the "DDS" magic number
  9770. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9771. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9772. return true;
  9773. }
  9774. else {
  9775. return false;
  9776. }
  9777. }
  9778. }
  9779. catch (e) {
  9780. // Global protection
  9781. }
  9782. return false;
  9783. };
  9784. /**
  9785. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9786. * Be aware Math.random() could cause collisions, but:
  9787. * "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"
  9788. */
  9789. Tools.RandomId = function () {
  9790. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9791. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9792. return v.toString(16);
  9793. });
  9794. };
  9795. /**
  9796. * Test if the given uri is a base64 string.
  9797. * @param uri The uri to test
  9798. * @return True if the uri is a base64 string or false otherwise.
  9799. */
  9800. Tools.IsBase64 = function (uri) {
  9801. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9802. };
  9803. /**
  9804. * Decode the given base64 uri.
  9805. * @param uri The uri to decode
  9806. * @return The decoded base64 data.
  9807. */
  9808. Tools.DecodeBase64 = function (uri) {
  9809. var decodedString = atob(uri.split(",")[1]);
  9810. var bufferLength = decodedString.length;
  9811. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9812. for (var i = 0; i < bufferLength; i++) {
  9813. bufferView[i] = decodedString.charCodeAt(i);
  9814. }
  9815. return bufferView.buffer;
  9816. };
  9817. Object.defineProperty(Tools, "NoneLogLevel", {
  9818. get: function () {
  9819. return Tools._NoneLogLevel;
  9820. },
  9821. enumerable: true,
  9822. configurable: true
  9823. });
  9824. Object.defineProperty(Tools, "MessageLogLevel", {
  9825. get: function () {
  9826. return Tools._MessageLogLevel;
  9827. },
  9828. enumerable: true,
  9829. configurable: true
  9830. });
  9831. Object.defineProperty(Tools, "WarningLogLevel", {
  9832. get: function () {
  9833. return Tools._WarningLogLevel;
  9834. },
  9835. enumerable: true,
  9836. configurable: true
  9837. });
  9838. Object.defineProperty(Tools, "ErrorLogLevel", {
  9839. get: function () {
  9840. return Tools._ErrorLogLevel;
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Object.defineProperty(Tools, "AllLogLevel", {
  9846. get: function () {
  9847. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9848. },
  9849. enumerable: true,
  9850. configurable: true
  9851. });
  9852. Tools._AddLogEntry = function (entry) {
  9853. Tools._LogCache = entry + Tools._LogCache;
  9854. if (Tools.OnNewCacheEntry) {
  9855. Tools.OnNewCacheEntry(entry);
  9856. }
  9857. };
  9858. Tools._FormatMessage = function (message) {
  9859. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9860. var date = new Date();
  9861. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9862. };
  9863. Tools._LogDisabled = function (message) {
  9864. // nothing to do
  9865. };
  9866. Tools._LogEnabled = function (message) {
  9867. var formattedMessage = Tools._FormatMessage(message);
  9868. console.log("BJS - " + formattedMessage);
  9869. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9870. Tools._AddLogEntry(entry);
  9871. };
  9872. Tools._WarnDisabled = function (message) {
  9873. // nothing to do
  9874. };
  9875. Tools._WarnEnabled = function (message) {
  9876. var formattedMessage = Tools._FormatMessage(message);
  9877. console.warn("BJS - " + formattedMessage);
  9878. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9879. Tools._AddLogEntry(entry);
  9880. };
  9881. Tools._ErrorDisabled = function (message) {
  9882. // nothing to do
  9883. };
  9884. Tools._ErrorEnabled = function (message) {
  9885. Tools.errorsCount++;
  9886. var formattedMessage = Tools._FormatMessage(message);
  9887. console.error("BJS - " + formattedMessage);
  9888. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9889. Tools._AddLogEntry(entry);
  9890. };
  9891. Object.defineProperty(Tools, "LogCache", {
  9892. get: function () {
  9893. return Tools._LogCache;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Tools.ClearLogCache = function () {
  9899. Tools._LogCache = "";
  9900. Tools.errorsCount = 0;
  9901. };
  9902. Object.defineProperty(Tools, "LogLevels", {
  9903. set: function (level) {
  9904. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9905. Tools.Log = Tools._LogEnabled;
  9906. }
  9907. else {
  9908. Tools.Log = Tools._LogDisabled;
  9909. }
  9910. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9911. Tools.Warn = Tools._WarnEnabled;
  9912. }
  9913. else {
  9914. Tools.Warn = Tools._WarnDisabled;
  9915. }
  9916. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9917. Tools.Error = Tools._ErrorEnabled;
  9918. }
  9919. else {
  9920. Tools.Error = Tools._ErrorDisabled;
  9921. }
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. /**
  9927. * Check if the loaded document was accessed via `file:`-Protocol.
  9928. * @returns boolean
  9929. */
  9930. Tools.IsFileURL = function () {
  9931. return location.protocol === "file:";
  9932. };
  9933. Tools.IsWindowObjectExist = function () {
  9934. return (typeof window) !== "undefined";
  9935. };
  9936. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9937. get: function () {
  9938. return Tools._PerformanceNoneLogLevel;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9944. get: function () {
  9945. return Tools._PerformanceUserMarkLogLevel;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9951. get: function () {
  9952. return Tools._PerformanceConsoleLogLevel;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9958. set: function (level) {
  9959. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9960. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9961. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9962. return;
  9963. }
  9964. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9965. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9966. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9967. return;
  9968. }
  9969. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9970. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9976. };
  9977. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9978. };
  9979. Tools._StartUserMark = function (counterName, condition) {
  9980. if (condition === void 0) { condition = true; }
  9981. if (!Tools._performance) {
  9982. if (!Tools.IsWindowObjectExist()) {
  9983. return;
  9984. }
  9985. Tools._performance = window.performance;
  9986. }
  9987. if (!condition || !Tools._performance.mark) {
  9988. return;
  9989. }
  9990. Tools._performance.mark(counterName + "-Begin");
  9991. };
  9992. Tools._EndUserMark = function (counterName, condition) {
  9993. if (condition === void 0) { condition = true; }
  9994. if (!condition || !Tools._performance.mark) {
  9995. return;
  9996. }
  9997. Tools._performance.mark(counterName + "-End");
  9998. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9999. };
  10000. Tools._StartPerformanceConsole = function (counterName, condition) {
  10001. if (condition === void 0) { condition = true; }
  10002. if (!condition) {
  10003. return;
  10004. }
  10005. Tools._StartUserMark(counterName, condition);
  10006. if (console.time) {
  10007. console.time(counterName);
  10008. }
  10009. };
  10010. Tools._EndPerformanceConsole = function (counterName, condition) {
  10011. if (condition === void 0) { condition = true; }
  10012. if (!condition) {
  10013. return;
  10014. }
  10015. Tools._EndUserMark(counterName, condition);
  10016. if (console.time) {
  10017. console.timeEnd(counterName);
  10018. }
  10019. };
  10020. Object.defineProperty(Tools, "Now", {
  10021. get: function () {
  10022. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10023. return window.performance.now();
  10024. }
  10025. return Date.now();
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. /**
  10031. * This method will return the name of the class used to create the instance of the given object.
  10032. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10033. * @param object the object to get the class name from
  10034. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10035. */
  10036. Tools.GetClassName = function (object, isType) {
  10037. if (isType === void 0) { isType = false; }
  10038. var name = null;
  10039. if (!isType && object.getClassName) {
  10040. name = object.getClassName();
  10041. }
  10042. else {
  10043. if (object instanceof Object) {
  10044. var classObj = isType ? object : Object.getPrototypeOf(object);
  10045. name = classObj.constructor["__bjsclassName__"];
  10046. }
  10047. if (!name) {
  10048. name = typeof object;
  10049. }
  10050. }
  10051. return name;
  10052. };
  10053. Tools.First = function (array, predicate) {
  10054. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10055. var el = array_1[_i];
  10056. if (predicate(el)) {
  10057. return el;
  10058. }
  10059. }
  10060. return null;
  10061. };
  10062. /**
  10063. * This method will return the name of the full name of the class, including its owning module (if any).
  10064. * 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).
  10065. * @param object the object to get the class name from
  10066. * @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.
  10067. */
  10068. Tools.getFullClassName = function (object, isType) {
  10069. if (isType === void 0) { isType = false; }
  10070. var className = null;
  10071. var moduleName = null;
  10072. if (!isType && object.getClassName) {
  10073. className = object.getClassName();
  10074. }
  10075. else {
  10076. if (object instanceof Object) {
  10077. var classObj = isType ? object : Object.getPrototypeOf(object);
  10078. className = classObj.constructor["__bjsclassName__"];
  10079. moduleName = classObj.constructor["__bjsmoduleName__"];
  10080. }
  10081. if (!className) {
  10082. className = typeof object;
  10083. }
  10084. }
  10085. if (!className) {
  10086. return null;
  10087. }
  10088. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10089. };
  10090. /**
  10091. * 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.
  10092. * @param array
  10093. */
  10094. Tools.arrayOrStringFeeder = function (array) {
  10095. return function (index) {
  10096. if (index >= array.length) {
  10097. return null;
  10098. }
  10099. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10100. if (val && val.getHashCode) {
  10101. val = val.getHashCode();
  10102. }
  10103. if (typeof val === "string") {
  10104. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10105. }
  10106. return val;
  10107. };
  10108. };
  10109. /**
  10110. * Compute the hashCode of a stream of number
  10111. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10112. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10113. * @return the hash code computed
  10114. */
  10115. Tools.hashCodeFromStream = function (feeder) {
  10116. // Based from here: http://stackoverflow.com/a/7616484/802124
  10117. var hash = 0;
  10118. var index = 0;
  10119. var chr = feeder(index++);
  10120. while (chr != null) {
  10121. hash = ((hash << 5) - hash) + chr;
  10122. hash |= 0; // Convert to 32bit integer
  10123. chr = feeder(index++);
  10124. }
  10125. return hash;
  10126. };
  10127. /**
  10128. * Returns a promise that resolves after the given amount of time.
  10129. * @param delay Number of milliseconds to delay
  10130. * @returns Promise that resolves after the given amount of time
  10131. */
  10132. Tools.DelayAsync = function (delay) {
  10133. return new Promise(function (resolve) {
  10134. setTimeout(function () {
  10135. resolve();
  10136. }, delay);
  10137. });
  10138. };
  10139. /**
  10140. * Gets the current gradient from an array of IValueGradient
  10141. * @param ratio defines the current ratio to get
  10142. * @param gradients defines the array of IValueGradient
  10143. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10144. */
  10145. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10146. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10147. var currentGradient = gradients[gradientIndex];
  10148. var nextGradient = gradients[gradientIndex + 1];
  10149. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10150. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10151. updateFunc(currentGradient, nextGradient, scale);
  10152. return;
  10153. }
  10154. }
  10155. // Use last index if over
  10156. var lastIndex = gradients.length - 1;
  10157. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10158. };
  10159. Tools.BaseUrl = "";
  10160. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10161. /**
  10162. * Default behaviour for cors in the application.
  10163. * It can be a string if the expected behavior is identical in the entire app.
  10164. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10165. */
  10166. Tools.CorsBehavior = "anonymous";
  10167. Tools.UseFallbackTexture = true;
  10168. /**
  10169. * Use this object to register external classes like custom textures or material
  10170. * to allow the laoders to instantiate them
  10171. */
  10172. Tools.RegisteredExternalClasses = {};
  10173. // Used in case of a texture loading problem
  10174. 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";
  10175. Tools._tmpFloatArray = new Float32Array(1);
  10176. Tools.PreprocessUrl = function (url) {
  10177. return url;
  10178. };
  10179. // Logs
  10180. Tools._NoneLogLevel = 0;
  10181. Tools._MessageLogLevel = 1;
  10182. Tools._WarningLogLevel = 2;
  10183. Tools._ErrorLogLevel = 4;
  10184. Tools._LogCache = "";
  10185. Tools.errorsCount = 0;
  10186. Tools.Log = Tools._LogEnabled;
  10187. Tools.Warn = Tools._WarnEnabled;
  10188. Tools.Error = Tools._ErrorEnabled;
  10189. // Performances
  10190. Tools._PerformanceNoneLogLevel = 0;
  10191. Tools._PerformanceUserMarkLogLevel = 1;
  10192. Tools._PerformanceConsoleLogLevel = 2;
  10193. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10194. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10195. return Tools;
  10196. }());
  10197. BABYLON.Tools = Tools;
  10198. /**
  10199. * This class is used to track a performance counter which is number based.
  10200. * The user has access to many properties which give statistics of different nature
  10201. *
  10202. * The implementer can track two kinds of Performance Counter: time and count
  10203. * 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.
  10204. * 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.
  10205. */
  10206. var PerfCounter = /** @class */ (function () {
  10207. function PerfCounter() {
  10208. this._startMonitoringTime = 0;
  10209. this._min = 0;
  10210. this._max = 0;
  10211. this._average = 0;
  10212. this._lastSecAverage = 0;
  10213. this._current = 0;
  10214. this._totalValueCount = 0;
  10215. this._totalAccumulated = 0;
  10216. this._lastSecAccumulated = 0;
  10217. this._lastSecTime = 0;
  10218. this._lastSecValueCount = 0;
  10219. }
  10220. Object.defineProperty(PerfCounter.prototype, "min", {
  10221. /**
  10222. * Returns the smallest value ever
  10223. */
  10224. get: function () {
  10225. return this._min;
  10226. },
  10227. enumerable: true,
  10228. configurable: true
  10229. });
  10230. Object.defineProperty(PerfCounter.prototype, "max", {
  10231. /**
  10232. * Returns the biggest value ever
  10233. */
  10234. get: function () {
  10235. return this._max;
  10236. },
  10237. enumerable: true,
  10238. configurable: true
  10239. });
  10240. Object.defineProperty(PerfCounter.prototype, "average", {
  10241. /**
  10242. * Returns the average value since the performance counter is running
  10243. */
  10244. get: function () {
  10245. return this._average;
  10246. },
  10247. enumerable: true,
  10248. configurable: true
  10249. });
  10250. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10251. /**
  10252. * Returns the average value of the last second the counter was monitored
  10253. */
  10254. get: function () {
  10255. return this._lastSecAverage;
  10256. },
  10257. enumerable: true,
  10258. configurable: true
  10259. });
  10260. Object.defineProperty(PerfCounter.prototype, "current", {
  10261. /**
  10262. * Returns the current value
  10263. */
  10264. get: function () {
  10265. return this._current;
  10266. },
  10267. enumerable: true,
  10268. configurable: true
  10269. });
  10270. Object.defineProperty(PerfCounter.prototype, "total", {
  10271. get: function () {
  10272. return this._totalAccumulated;
  10273. },
  10274. enumerable: true,
  10275. configurable: true
  10276. });
  10277. Object.defineProperty(PerfCounter.prototype, "count", {
  10278. get: function () {
  10279. return this._totalValueCount;
  10280. },
  10281. enumerable: true,
  10282. configurable: true
  10283. });
  10284. /**
  10285. * Call this method to start monitoring a new frame.
  10286. * 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.
  10287. */
  10288. PerfCounter.prototype.fetchNewFrame = function () {
  10289. this._totalValueCount++;
  10290. this._current = 0;
  10291. this._lastSecValueCount++;
  10292. };
  10293. /**
  10294. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10295. * @param newCount the count value to add to the monitored count
  10296. * @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.
  10297. */
  10298. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10299. if (!PerfCounter.Enabled) {
  10300. return;
  10301. }
  10302. this._current += newCount;
  10303. if (fetchResult) {
  10304. this._fetchResult();
  10305. }
  10306. };
  10307. /**
  10308. * Start monitoring this performance counter
  10309. */
  10310. PerfCounter.prototype.beginMonitoring = function () {
  10311. if (!PerfCounter.Enabled) {
  10312. return;
  10313. }
  10314. this._startMonitoringTime = Tools.Now;
  10315. };
  10316. /**
  10317. * Compute the time lapsed since the previous beginMonitoring() call.
  10318. * @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
  10319. */
  10320. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10321. if (newFrame === void 0) { newFrame = true; }
  10322. if (!PerfCounter.Enabled) {
  10323. return;
  10324. }
  10325. if (newFrame) {
  10326. this.fetchNewFrame();
  10327. }
  10328. var currentTime = Tools.Now;
  10329. this._current = currentTime - this._startMonitoringTime;
  10330. if (newFrame) {
  10331. this._fetchResult();
  10332. }
  10333. };
  10334. PerfCounter.prototype._fetchResult = function () {
  10335. this._totalAccumulated += this._current;
  10336. this._lastSecAccumulated += this._current;
  10337. // Min/Max update
  10338. this._min = Math.min(this._min, this._current);
  10339. this._max = Math.max(this._max, this._current);
  10340. this._average = this._totalAccumulated / this._totalValueCount;
  10341. // Reset last sec?
  10342. var now = Tools.Now;
  10343. if ((now - this._lastSecTime) > 1000) {
  10344. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10345. this._lastSecTime = now;
  10346. this._lastSecAccumulated = 0;
  10347. this._lastSecValueCount = 0;
  10348. }
  10349. };
  10350. PerfCounter.Enabled = true;
  10351. return PerfCounter;
  10352. }());
  10353. BABYLON.PerfCounter = PerfCounter;
  10354. /**
  10355. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10356. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10357. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10358. * @param name The name of the class, case should be preserved
  10359. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10360. */
  10361. function className(name, module) {
  10362. return function (target) {
  10363. target["__bjsclassName__"] = name;
  10364. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10365. };
  10366. }
  10367. BABYLON.className = className;
  10368. /**
  10369. * An implementation of a loop for asynchronous functions.
  10370. */
  10371. var AsyncLoop = /** @class */ (function () {
  10372. /**
  10373. * Constroctor.
  10374. * @param iterations the number of iterations.
  10375. * @param _fn the function to run each iteration
  10376. * @param _successCallback the callback that will be called upon succesful execution
  10377. * @param offset starting offset.
  10378. */
  10379. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10380. if (offset === void 0) { offset = 0; }
  10381. this.iterations = iterations;
  10382. this._fn = _fn;
  10383. this._successCallback = _successCallback;
  10384. this.index = offset - 1;
  10385. this._done = false;
  10386. }
  10387. /**
  10388. * Execute the next iteration. Must be called after the last iteration was finished.
  10389. */
  10390. AsyncLoop.prototype.executeNext = function () {
  10391. if (!this._done) {
  10392. if (this.index + 1 < this.iterations) {
  10393. ++this.index;
  10394. this._fn(this);
  10395. }
  10396. else {
  10397. this.breakLoop();
  10398. }
  10399. }
  10400. };
  10401. /**
  10402. * Break the loop and run the success callback.
  10403. */
  10404. AsyncLoop.prototype.breakLoop = function () {
  10405. this._done = true;
  10406. this._successCallback();
  10407. };
  10408. /**
  10409. * Helper function
  10410. */
  10411. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10412. if (offset === void 0) { offset = 0; }
  10413. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10414. loop.executeNext();
  10415. return loop;
  10416. };
  10417. /**
  10418. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10419. * @param iterations total number of iterations
  10420. * @param syncedIterations number of synchronous iterations in each async iteration.
  10421. * @param fn the function to call each iteration.
  10422. * @param callback a success call back that will be called when iterating stops.
  10423. * @param breakFunction a break condition (optional)
  10424. * @param timeout timeout settings for the setTimeout function. default - 0.
  10425. * @constructor
  10426. */
  10427. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10428. if (timeout === void 0) { timeout = 0; }
  10429. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10430. if (breakFunction && breakFunction())
  10431. loop.breakLoop();
  10432. else {
  10433. setTimeout(function () {
  10434. for (var i = 0; i < syncedIterations; ++i) {
  10435. var iteration = (loop.index * syncedIterations) + i;
  10436. if (iteration >= iterations)
  10437. break;
  10438. fn(iteration);
  10439. if (breakFunction && breakFunction()) {
  10440. loop.breakLoop();
  10441. break;
  10442. }
  10443. }
  10444. loop.executeNext();
  10445. }, timeout);
  10446. }
  10447. }, callback);
  10448. };
  10449. return AsyncLoop;
  10450. }());
  10451. BABYLON.AsyncLoop = AsyncLoop;
  10452. })(BABYLON || (BABYLON = {}));
  10453. //# sourceMappingURL=babylon.tools.js.map
  10454. var BABYLON;
  10455. (function (BABYLON) {
  10456. var PromiseStates;
  10457. (function (PromiseStates) {
  10458. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10459. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10460. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10461. })(PromiseStates || (PromiseStates = {}));
  10462. var FulFillmentAgregator = /** @class */ (function () {
  10463. function FulFillmentAgregator() {
  10464. this.count = 0;
  10465. this.target = 0;
  10466. this.results = [];
  10467. }
  10468. return FulFillmentAgregator;
  10469. }());
  10470. var InternalPromise = /** @class */ (function () {
  10471. function InternalPromise(resolver) {
  10472. var _this = this;
  10473. this._state = PromiseStates.Pending;
  10474. this._children = new Array();
  10475. this._rejectWasConsumed = false;
  10476. if (!resolver) {
  10477. return;
  10478. }
  10479. try {
  10480. resolver(function (value) {
  10481. _this._resolve(value);
  10482. }, function (reason) {
  10483. _this._reject(reason);
  10484. });
  10485. }
  10486. catch (e) {
  10487. this._reject(e);
  10488. }
  10489. }
  10490. Object.defineProperty(InternalPromise.prototype, "_result", {
  10491. get: function () {
  10492. return this._resultValue;
  10493. },
  10494. set: function (value) {
  10495. this._resultValue = value;
  10496. if (this._parent && this._parent._result === undefined) {
  10497. this._parent._result = value;
  10498. }
  10499. },
  10500. enumerable: true,
  10501. configurable: true
  10502. });
  10503. InternalPromise.prototype.catch = function (onRejected) {
  10504. return this.then(undefined, onRejected);
  10505. };
  10506. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10507. var _this = this;
  10508. var newPromise = new InternalPromise();
  10509. newPromise._onFulfilled = onFulfilled;
  10510. newPromise._onRejected = onRejected;
  10511. // Composition
  10512. this._children.push(newPromise);
  10513. newPromise._parent = this;
  10514. if (this._state !== PromiseStates.Pending) {
  10515. BABYLON.Tools.SetImmediate(function () {
  10516. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10517. var returnedValue = newPromise._resolve(_this._result);
  10518. if (returnedValue !== undefined && returnedValue !== null) {
  10519. if (returnedValue._state !== undefined) {
  10520. var returnedPromise = returnedValue;
  10521. newPromise._children.push(returnedPromise);
  10522. returnedPromise._parent = newPromise;
  10523. newPromise = returnedPromise;
  10524. }
  10525. else {
  10526. newPromise._result = returnedValue;
  10527. }
  10528. }
  10529. }
  10530. else {
  10531. newPromise._reject(_this._reason);
  10532. }
  10533. });
  10534. }
  10535. return newPromise;
  10536. };
  10537. InternalPromise.prototype._moveChildren = function (children) {
  10538. var _this = this;
  10539. var _a;
  10540. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10541. this._children.forEach(function (child) {
  10542. child._parent = _this;
  10543. });
  10544. if (this._state === PromiseStates.Fulfilled) {
  10545. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10546. var child = _b[_i];
  10547. child._resolve(this._result);
  10548. }
  10549. }
  10550. else if (this._state === PromiseStates.Rejected) {
  10551. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10552. var child = _d[_c];
  10553. child._reject(this._reason);
  10554. }
  10555. }
  10556. };
  10557. InternalPromise.prototype._resolve = function (value) {
  10558. try {
  10559. this._state = PromiseStates.Fulfilled;
  10560. var returnedValue = null;
  10561. if (this._onFulfilled) {
  10562. returnedValue = this._onFulfilled(value);
  10563. }
  10564. if (returnedValue !== undefined && returnedValue !== null) {
  10565. if (returnedValue._state !== undefined) {
  10566. // Transmit children
  10567. var returnedPromise = returnedValue;
  10568. returnedPromise._parent = this;
  10569. returnedPromise._moveChildren(this._children);
  10570. value = returnedPromise._result;
  10571. }
  10572. else {
  10573. value = returnedValue;
  10574. }
  10575. }
  10576. this._result = value;
  10577. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10578. var child = _a[_i];
  10579. child._resolve(value);
  10580. }
  10581. this._children.length = 0;
  10582. delete this._onFulfilled;
  10583. delete this._onRejected;
  10584. }
  10585. catch (e) {
  10586. this._reject(e, true);
  10587. }
  10588. };
  10589. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10590. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10591. this._state = PromiseStates.Rejected;
  10592. this._reason = reason;
  10593. if (this._onRejected && !onLocalThrow) {
  10594. try {
  10595. this._onRejected(reason);
  10596. this._rejectWasConsumed = true;
  10597. }
  10598. catch (e) {
  10599. reason = e;
  10600. }
  10601. }
  10602. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10603. var child = _a[_i];
  10604. if (this._rejectWasConsumed) {
  10605. child._resolve(null);
  10606. }
  10607. else {
  10608. child._reject(reason);
  10609. }
  10610. }
  10611. this._children.length = 0;
  10612. delete this._onFulfilled;
  10613. delete this._onRejected;
  10614. };
  10615. InternalPromise.resolve = function (value) {
  10616. var newPromise = new InternalPromise();
  10617. newPromise._resolve(value);
  10618. return newPromise;
  10619. };
  10620. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10621. promise.then(function (value) {
  10622. agregator.results[index] = value;
  10623. agregator.count++;
  10624. if (agregator.count === agregator.target) {
  10625. agregator.rootPromise._resolve(agregator.results);
  10626. }
  10627. return null;
  10628. }, function (reason) {
  10629. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10630. agregator.rootPromise._reject(reason);
  10631. }
  10632. });
  10633. };
  10634. InternalPromise.all = function (promises) {
  10635. var newPromise = new InternalPromise();
  10636. var agregator = new FulFillmentAgregator();
  10637. agregator.target = promises.length;
  10638. agregator.rootPromise = newPromise;
  10639. if (promises.length) {
  10640. for (var index = 0; index < promises.length; index++) {
  10641. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10642. }
  10643. }
  10644. else {
  10645. newPromise._resolve([]);
  10646. }
  10647. return newPromise;
  10648. };
  10649. InternalPromise.race = function (promises) {
  10650. var newPromise = new InternalPromise();
  10651. if (promises.length) {
  10652. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10653. var promise = promises_1[_i];
  10654. promise.then(function (value) {
  10655. if (newPromise) {
  10656. newPromise._resolve(value);
  10657. newPromise = null;
  10658. }
  10659. return null;
  10660. }, function (reason) {
  10661. if (newPromise) {
  10662. newPromise._reject(reason);
  10663. newPromise = null;
  10664. }
  10665. });
  10666. }
  10667. }
  10668. return newPromise;
  10669. };
  10670. return InternalPromise;
  10671. }());
  10672. /**
  10673. * Helper class that provides a small promise polyfill
  10674. */
  10675. var PromisePolyfill = /** @class */ (function () {
  10676. function PromisePolyfill() {
  10677. }
  10678. /**
  10679. * Static function used to check if the polyfill is required
  10680. * If this is the case then the function will inject the polyfill to window.Promise
  10681. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10682. */
  10683. PromisePolyfill.Apply = function (force) {
  10684. if (force === void 0) { force = false; }
  10685. if (force || typeof Promise === 'undefined') {
  10686. var root = window;
  10687. root.Promise = InternalPromise;
  10688. }
  10689. };
  10690. return PromisePolyfill;
  10691. }());
  10692. BABYLON.PromisePolyfill = PromisePolyfill;
  10693. })(BABYLON || (BABYLON = {}));
  10694. //# sourceMappingURL=babylon.promise.js.map
  10695. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10696. var BABYLON;
  10697. (function (BABYLON) {
  10698. /**
  10699. * Helper class to push actions to a pool of workers.
  10700. */
  10701. var WorkerPool = /** @class */ (function () {
  10702. /**
  10703. * Constructor
  10704. * @param workers Array of workers to use for actions
  10705. */
  10706. function WorkerPool(workers) {
  10707. this._pendingActions = new Array();
  10708. this._workerInfos = workers.map(function (worker) { return ({
  10709. worker: worker,
  10710. active: false
  10711. }); });
  10712. }
  10713. /**
  10714. * Terminates all workers and clears any pending actions.
  10715. */
  10716. WorkerPool.prototype.dispose = function () {
  10717. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10718. var workerInfo = _a[_i];
  10719. workerInfo.worker.terminate();
  10720. }
  10721. delete this._workerInfos;
  10722. delete this._pendingActions;
  10723. };
  10724. /**
  10725. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10726. * pended until a worker has completed its action.
  10727. * @param action The action to perform. Call onComplete when the action is complete.
  10728. */
  10729. WorkerPool.prototype.push = function (action) {
  10730. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10731. var workerInfo = _a[_i];
  10732. if (!workerInfo.active) {
  10733. this._execute(workerInfo, action);
  10734. return;
  10735. }
  10736. }
  10737. this._pendingActions.push(action);
  10738. };
  10739. WorkerPool.prototype._execute = function (workerInfo, action) {
  10740. var _this = this;
  10741. workerInfo.active = true;
  10742. action(workerInfo.worker, function () {
  10743. workerInfo.active = false;
  10744. var nextAction = _this._pendingActions.shift();
  10745. if (nextAction) {
  10746. _this._execute(workerInfo, nextAction);
  10747. }
  10748. });
  10749. };
  10750. return WorkerPool;
  10751. }());
  10752. BABYLON.WorkerPool = WorkerPool;
  10753. })(BABYLON || (BABYLON = {}));
  10754. //# sourceMappingURL=babylon.workerPool.js.map
  10755. var BABYLON;
  10756. (function (BABYLON) {
  10757. /**
  10758. * @hidden
  10759. **/
  10760. var _AlphaState = /** @class */ (function () {
  10761. /**
  10762. * Initializes the state.
  10763. */
  10764. function _AlphaState() {
  10765. this._isAlphaBlendDirty = false;
  10766. this._isBlendFunctionParametersDirty = false;
  10767. this._isBlendEquationParametersDirty = false;
  10768. this._isBlendConstantsDirty = false;
  10769. this._alphaBlend = false;
  10770. this._blendFunctionParameters = new Array(4);
  10771. this._blendEquationParameters = new Array(2);
  10772. this._blendConstants = new Array(4);
  10773. this.reset();
  10774. }
  10775. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10776. get: function () {
  10777. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10783. get: function () {
  10784. return this._alphaBlend;
  10785. },
  10786. set: function (value) {
  10787. if (this._alphaBlend === value) {
  10788. return;
  10789. }
  10790. this._alphaBlend = value;
  10791. this._isAlphaBlendDirty = true;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10797. if (this._blendConstants[0] === r &&
  10798. this._blendConstants[1] === g &&
  10799. this._blendConstants[2] === b &&
  10800. this._blendConstants[3] === a) {
  10801. return;
  10802. }
  10803. this._blendConstants[0] = r;
  10804. this._blendConstants[1] = g;
  10805. this._blendConstants[2] = b;
  10806. this._blendConstants[3] = a;
  10807. this._isBlendConstantsDirty = true;
  10808. };
  10809. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10810. if (this._blendFunctionParameters[0] === value0 &&
  10811. this._blendFunctionParameters[1] === value1 &&
  10812. this._blendFunctionParameters[2] === value2 &&
  10813. this._blendFunctionParameters[3] === value3) {
  10814. return;
  10815. }
  10816. this._blendFunctionParameters[0] = value0;
  10817. this._blendFunctionParameters[1] = value1;
  10818. this._blendFunctionParameters[2] = value2;
  10819. this._blendFunctionParameters[3] = value3;
  10820. this._isBlendFunctionParametersDirty = true;
  10821. };
  10822. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10823. if (this._blendEquationParameters[0] === rgb &&
  10824. this._blendEquationParameters[1] === alpha) {
  10825. return;
  10826. }
  10827. this._blendEquationParameters[0] = rgb;
  10828. this._blendEquationParameters[1] = alpha;
  10829. this._isBlendEquationParametersDirty = true;
  10830. };
  10831. _AlphaState.prototype.reset = function () {
  10832. this._alphaBlend = false;
  10833. this._blendFunctionParameters[0] = null;
  10834. this._blendFunctionParameters[1] = null;
  10835. this._blendFunctionParameters[2] = null;
  10836. this._blendFunctionParameters[3] = null;
  10837. this._blendEquationParameters[0] = null;
  10838. this._blendEquationParameters[1] = null;
  10839. this._blendConstants[0] = null;
  10840. this._blendConstants[1] = null;
  10841. this._blendConstants[2] = null;
  10842. this._blendConstants[3] = null;
  10843. this._isAlphaBlendDirty = true;
  10844. this._isBlendFunctionParametersDirty = false;
  10845. this._isBlendEquationParametersDirty = false;
  10846. this._isBlendConstantsDirty = false;
  10847. };
  10848. _AlphaState.prototype.apply = function (gl) {
  10849. if (!this.isDirty) {
  10850. return;
  10851. }
  10852. // Alpha blend
  10853. if (this._isAlphaBlendDirty) {
  10854. if (this._alphaBlend) {
  10855. gl.enable(gl.BLEND);
  10856. }
  10857. else {
  10858. gl.disable(gl.BLEND);
  10859. }
  10860. this._isAlphaBlendDirty = false;
  10861. }
  10862. // Alpha function
  10863. if (this._isBlendFunctionParametersDirty) {
  10864. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10865. this._isBlendFunctionParametersDirty = false;
  10866. }
  10867. // Alpha equation
  10868. if (this._isBlendEquationParametersDirty) {
  10869. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10870. this._isBlendEquationParametersDirty = false;
  10871. }
  10872. // Constants
  10873. if (this._isBlendConstantsDirty) {
  10874. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10875. this._isBlendConstantsDirty = false;
  10876. }
  10877. };
  10878. return _AlphaState;
  10879. }());
  10880. BABYLON._AlphaState = _AlphaState;
  10881. })(BABYLON || (BABYLON = {}));
  10882. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10883. var BABYLON;
  10884. (function (BABYLON) {
  10885. /**
  10886. * @hidden
  10887. **/
  10888. var _DepthCullingState = /** @class */ (function () {
  10889. /**
  10890. * Initializes the state.
  10891. */
  10892. function _DepthCullingState() {
  10893. this._isDepthTestDirty = false;
  10894. this._isDepthMaskDirty = false;
  10895. this._isDepthFuncDirty = false;
  10896. this._isCullFaceDirty = false;
  10897. this._isCullDirty = false;
  10898. this._isZOffsetDirty = false;
  10899. this._isFrontFaceDirty = false;
  10900. this.reset();
  10901. }
  10902. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10903. get: function () {
  10904. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10910. get: function () {
  10911. return this._zOffset;
  10912. },
  10913. set: function (value) {
  10914. if (this._zOffset === value) {
  10915. return;
  10916. }
  10917. this._zOffset = value;
  10918. this._isZOffsetDirty = true;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10924. get: function () {
  10925. return this._cullFace;
  10926. },
  10927. set: function (value) {
  10928. if (this._cullFace === value) {
  10929. return;
  10930. }
  10931. this._cullFace = value;
  10932. this._isCullFaceDirty = true;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10938. get: function () {
  10939. return this._cull;
  10940. },
  10941. set: function (value) {
  10942. if (this._cull === value) {
  10943. return;
  10944. }
  10945. this._cull = value;
  10946. this._isCullDirty = true;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10952. get: function () {
  10953. return this._depthFunc;
  10954. },
  10955. set: function (value) {
  10956. if (this._depthFunc === value) {
  10957. return;
  10958. }
  10959. this._depthFunc = value;
  10960. this._isDepthFuncDirty = true;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10966. get: function () {
  10967. return this._depthMask;
  10968. },
  10969. set: function (value) {
  10970. if (this._depthMask === value) {
  10971. return;
  10972. }
  10973. this._depthMask = value;
  10974. this._isDepthMaskDirty = true;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10980. get: function () {
  10981. return this._depthTest;
  10982. },
  10983. set: function (value) {
  10984. if (this._depthTest === value) {
  10985. return;
  10986. }
  10987. this._depthTest = value;
  10988. this._isDepthTestDirty = true;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10994. get: function () {
  10995. return this._frontFace;
  10996. },
  10997. set: function (value) {
  10998. if (this._frontFace === value) {
  10999. return;
  11000. }
  11001. this._frontFace = value;
  11002. this._isFrontFaceDirty = true;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. _DepthCullingState.prototype.reset = function () {
  11008. this._depthMask = true;
  11009. this._depthTest = true;
  11010. this._depthFunc = null;
  11011. this._cullFace = null;
  11012. this._cull = null;
  11013. this._zOffset = 0;
  11014. this._frontFace = null;
  11015. this._isDepthTestDirty = true;
  11016. this._isDepthMaskDirty = true;
  11017. this._isDepthFuncDirty = false;
  11018. this._isCullFaceDirty = false;
  11019. this._isCullDirty = false;
  11020. this._isZOffsetDirty = false;
  11021. this._isFrontFaceDirty = false;
  11022. };
  11023. _DepthCullingState.prototype.apply = function (gl) {
  11024. if (!this.isDirty) {
  11025. return;
  11026. }
  11027. // Cull
  11028. if (this._isCullDirty) {
  11029. if (this.cull) {
  11030. gl.enable(gl.CULL_FACE);
  11031. }
  11032. else {
  11033. gl.disable(gl.CULL_FACE);
  11034. }
  11035. this._isCullDirty = false;
  11036. }
  11037. // Cull face
  11038. if (this._isCullFaceDirty) {
  11039. gl.cullFace(this.cullFace);
  11040. this._isCullFaceDirty = false;
  11041. }
  11042. // Depth mask
  11043. if (this._isDepthMaskDirty) {
  11044. gl.depthMask(this.depthMask);
  11045. this._isDepthMaskDirty = false;
  11046. }
  11047. // Depth test
  11048. if (this._isDepthTestDirty) {
  11049. if (this.depthTest) {
  11050. gl.enable(gl.DEPTH_TEST);
  11051. }
  11052. else {
  11053. gl.disable(gl.DEPTH_TEST);
  11054. }
  11055. this._isDepthTestDirty = false;
  11056. }
  11057. // Depth func
  11058. if (this._isDepthFuncDirty) {
  11059. gl.depthFunc(this.depthFunc);
  11060. this._isDepthFuncDirty = false;
  11061. }
  11062. // zOffset
  11063. if (this._isZOffsetDirty) {
  11064. if (this.zOffset) {
  11065. gl.enable(gl.POLYGON_OFFSET_FILL);
  11066. gl.polygonOffset(this.zOffset, 0);
  11067. }
  11068. else {
  11069. gl.disable(gl.POLYGON_OFFSET_FILL);
  11070. }
  11071. this._isZOffsetDirty = false;
  11072. }
  11073. // Front face
  11074. if (this._isFrontFaceDirty) {
  11075. gl.frontFace(this.frontFace);
  11076. this._isFrontFaceDirty = false;
  11077. }
  11078. };
  11079. return _DepthCullingState;
  11080. }());
  11081. BABYLON._DepthCullingState = _DepthCullingState;
  11082. })(BABYLON || (BABYLON = {}));
  11083. //# sourceMappingURL=babylon.depthCullingState.js.map
  11084. var BABYLON;
  11085. (function (BABYLON) {
  11086. /**
  11087. * @hidden
  11088. **/
  11089. var _StencilState = /** @class */ (function () {
  11090. function _StencilState() {
  11091. this._isStencilTestDirty = false;
  11092. this._isStencilMaskDirty = false;
  11093. this._isStencilFuncDirty = false;
  11094. this._isStencilOpDirty = false;
  11095. this.reset();
  11096. }
  11097. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11098. get: function () {
  11099. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11105. get: function () {
  11106. return this._stencilFunc;
  11107. },
  11108. set: function (value) {
  11109. if (this._stencilFunc === value) {
  11110. return;
  11111. }
  11112. this._stencilFunc = value;
  11113. this._isStencilFuncDirty = true;
  11114. },
  11115. enumerable: true,
  11116. configurable: true
  11117. });
  11118. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11119. get: function () {
  11120. return this._stencilFuncRef;
  11121. },
  11122. set: function (value) {
  11123. if (this._stencilFuncRef === value) {
  11124. return;
  11125. }
  11126. this._stencilFuncRef = value;
  11127. this._isStencilFuncDirty = true;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11133. get: function () {
  11134. return this._stencilFuncMask;
  11135. },
  11136. set: function (value) {
  11137. if (this._stencilFuncMask === value) {
  11138. return;
  11139. }
  11140. this._stencilFuncMask = value;
  11141. this._isStencilFuncDirty = true;
  11142. },
  11143. enumerable: true,
  11144. configurable: true
  11145. });
  11146. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11147. get: function () {
  11148. return this._stencilOpStencilFail;
  11149. },
  11150. set: function (value) {
  11151. if (this._stencilOpStencilFail === value) {
  11152. return;
  11153. }
  11154. this._stencilOpStencilFail = value;
  11155. this._isStencilOpDirty = true;
  11156. },
  11157. enumerable: true,
  11158. configurable: true
  11159. });
  11160. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11161. get: function () {
  11162. return this._stencilOpDepthFail;
  11163. },
  11164. set: function (value) {
  11165. if (this._stencilOpDepthFail === value) {
  11166. return;
  11167. }
  11168. this._stencilOpDepthFail = value;
  11169. this._isStencilOpDirty = true;
  11170. },
  11171. enumerable: true,
  11172. configurable: true
  11173. });
  11174. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11175. get: function () {
  11176. return this._stencilOpStencilDepthPass;
  11177. },
  11178. set: function (value) {
  11179. if (this._stencilOpStencilDepthPass === value) {
  11180. return;
  11181. }
  11182. this._stencilOpStencilDepthPass = value;
  11183. this._isStencilOpDirty = true;
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11189. get: function () {
  11190. return this._stencilMask;
  11191. },
  11192. set: function (value) {
  11193. if (this._stencilMask === value) {
  11194. return;
  11195. }
  11196. this._stencilMask = value;
  11197. this._isStencilMaskDirty = true;
  11198. },
  11199. enumerable: true,
  11200. configurable: true
  11201. });
  11202. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11203. get: function () {
  11204. return this._stencilTest;
  11205. },
  11206. set: function (value) {
  11207. if (this._stencilTest === value) {
  11208. return;
  11209. }
  11210. this._stencilTest = value;
  11211. this._isStencilTestDirty = true;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. _StencilState.prototype.reset = function () {
  11217. this._stencilTest = false;
  11218. this._stencilMask = 0xFF;
  11219. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11220. this._stencilFuncRef = 1;
  11221. this._stencilFuncMask = 0xFF;
  11222. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11223. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11224. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11225. this._isStencilTestDirty = true;
  11226. this._isStencilMaskDirty = true;
  11227. this._isStencilFuncDirty = true;
  11228. this._isStencilOpDirty = true;
  11229. };
  11230. _StencilState.prototype.apply = function (gl) {
  11231. if (!this.isDirty) {
  11232. return;
  11233. }
  11234. // Stencil test
  11235. if (this._isStencilTestDirty) {
  11236. if (this.stencilTest) {
  11237. gl.enable(gl.STENCIL_TEST);
  11238. }
  11239. else {
  11240. gl.disable(gl.STENCIL_TEST);
  11241. }
  11242. this._isStencilTestDirty = false;
  11243. }
  11244. // Stencil mask
  11245. if (this._isStencilMaskDirty) {
  11246. gl.stencilMask(this.stencilMask);
  11247. this._isStencilMaskDirty = false;
  11248. }
  11249. // Stencil func
  11250. if (this._isStencilFuncDirty) {
  11251. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11252. this._isStencilFuncDirty = false;
  11253. }
  11254. // Stencil op
  11255. if (this._isStencilOpDirty) {
  11256. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11257. this._isStencilOpDirty = false;
  11258. }
  11259. };
  11260. return _StencilState;
  11261. }());
  11262. BABYLON._StencilState = _StencilState;
  11263. })(BABYLON || (BABYLON = {}));
  11264. //# sourceMappingURL=babylon.stencilState.js.map
  11265. var __assign = (this && this.__assign) || function () {
  11266. __assign = Object.assign || function(t) {
  11267. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11268. s = arguments[i];
  11269. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11270. t[p] = s[p];
  11271. }
  11272. return t;
  11273. };
  11274. return __assign.apply(this, arguments);
  11275. };
  11276. var BABYLON;
  11277. (function (BABYLON) {
  11278. /**
  11279. * Keeps track of all the buffer info used in engine.
  11280. */
  11281. var BufferPointer = /** @class */ (function () {
  11282. function BufferPointer() {
  11283. }
  11284. return BufferPointer;
  11285. }());
  11286. /**
  11287. * Interface for attribute information associated with buffer instanciation
  11288. */
  11289. var InstancingAttributeInfo = /** @class */ (function () {
  11290. function InstancingAttributeInfo() {
  11291. }
  11292. return InstancingAttributeInfo;
  11293. }());
  11294. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11295. /**
  11296. * Define options used to create a render target texture
  11297. */
  11298. var RenderTargetCreationOptions = /** @class */ (function () {
  11299. function RenderTargetCreationOptions() {
  11300. }
  11301. return RenderTargetCreationOptions;
  11302. }());
  11303. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11304. /**
  11305. * Define options used to create a depth texture
  11306. */
  11307. var DepthTextureCreationOptions = /** @class */ (function () {
  11308. function DepthTextureCreationOptions() {
  11309. }
  11310. return DepthTextureCreationOptions;
  11311. }());
  11312. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11313. /**
  11314. * Class used to describe the capabilities of the engine relatively to the current browser
  11315. */
  11316. var EngineCapabilities = /** @class */ (function () {
  11317. function EngineCapabilities() {
  11318. }
  11319. return EngineCapabilities;
  11320. }());
  11321. BABYLON.EngineCapabilities = EngineCapabilities;
  11322. /**
  11323. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11324. */
  11325. var Engine = /** @class */ (function () {
  11326. /**
  11327. * Creates a new engine
  11328. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11329. * @param antialias defines enable antialiasing (default: false)
  11330. * @param options defines further options to be sent to the getContext() function
  11331. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11332. */
  11333. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11334. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11335. var _this = this;
  11336. // Public members
  11337. /**
  11338. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11339. */
  11340. this.forcePOTTextures = false;
  11341. /**
  11342. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11343. */
  11344. this.isFullscreen = false;
  11345. /**
  11346. * Gets a boolean indicating if the pointer is currently locked
  11347. */
  11348. this.isPointerLock = false;
  11349. /**
  11350. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11351. */
  11352. this.cullBackFaces = true;
  11353. /**
  11354. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11355. */
  11356. this.renderEvenInBackground = true;
  11357. /**
  11358. * Gets or sets a boolean indicating that cache can be kept between frames
  11359. */
  11360. this.preventCacheWipeBetweenFrames = false;
  11361. /**
  11362. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11363. **/
  11364. this.enableOfflineSupport = false;
  11365. /**
  11366. * 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)
  11367. **/
  11368. this.disableManifestCheck = false;
  11369. /**
  11370. * Gets the list of created scenes
  11371. */
  11372. this.scenes = new Array();
  11373. /**
  11374. * Gets the list of created postprocesses
  11375. */
  11376. this.postProcesses = new Array();
  11377. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11378. this.validateShaderPrograms = false;
  11379. // Observables
  11380. /**
  11381. * Observable event triggered each time the rendering canvas is resized
  11382. */
  11383. this.onResizeObservable = new BABYLON.Observable();
  11384. /**
  11385. * Observable event triggered each time the canvas loses focus
  11386. */
  11387. this.onCanvasBlurObservable = new BABYLON.Observable();
  11388. /**
  11389. * Observable event triggered each time the canvas gains focus
  11390. */
  11391. this.onCanvasFocusObservable = new BABYLON.Observable();
  11392. /**
  11393. * Observable event triggered each time the canvas receives pointerout event
  11394. */
  11395. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11396. /**
  11397. * Observable event triggered before each texture is initialized
  11398. */
  11399. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11400. //WebVR
  11401. this._vrDisplay = undefined;
  11402. this._vrSupported = false;
  11403. this._vrExclusivePointerMode = false;
  11404. // Uniform buffers list
  11405. /**
  11406. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11407. */
  11408. this.disableUniformBuffers = false;
  11409. /** @hidden */
  11410. this._uniformBuffers = new Array();
  11411. // Observables
  11412. /**
  11413. * Observable raised when the engine begins a new frame
  11414. */
  11415. this.onBeginFrameObservable = new BABYLON.Observable();
  11416. /**
  11417. * Observable raised when the engine ends the current frame
  11418. */
  11419. this.onEndFrameObservable = new BABYLON.Observable();
  11420. /**
  11421. * Observable raised when the engine is about to compile a shader
  11422. */
  11423. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11424. /**
  11425. * Observable raised when the engine has jsut compiled a shader
  11426. */
  11427. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11428. this._windowIsBackground = false;
  11429. this._webGLVersion = 1.0;
  11430. /** @hidden */
  11431. this._badOS = false;
  11432. /** @hidden */
  11433. this._badDesktopOS = false;
  11434. /**
  11435. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11436. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11437. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11438. */
  11439. this.disableTextureBindingOptimization = false;
  11440. /**
  11441. * Observable signaled when VR display mode changes
  11442. */
  11443. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11444. /**
  11445. * Observable signaled when VR request present is complete
  11446. */
  11447. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11448. /**
  11449. * Observable signaled when VR request present starts
  11450. */
  11451. this.onVRRequestPresentStart = new BABYLON.Observable();
  11452. this._colorWrite = true;
  11453. /** @hidden */
  11454. this._drawCalls = new BABYLON.PerfCounter();
  11455. /** @hidden */
  11456. this._textureCollisions = new BABYLON.PerfCounter();
  11457. this._renderingQueueLaunched = false;
  11458. this._activeRenderLoops = new Array();
  11459. // Deterministic lockstepMaxSteps
  11460. this._deterministicLockstep = false;
  11461. this._lockstepMaxSteps = 4;
  11462. // Lost context
  11463. /**
  11464. * Observable signaled when a context lost event is raised
  11465. */
  11466. this.onContextLostObservable = new BABYLON.Observable();
  11467. /**
  11468. * Observable signaled when a context restored event is raised
  11469. */
  11470. this.onContextRestoredObservable = new BABYLON.Observable();
  11471. this._contextWasLost = false;
  11472. this._doNotHandleContextLost = false;
  11473. // FPS
  11474. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11475. this._fps = 60;
  11476. this._deltaTime = 0;
  11477. /**
  11478. * Turn this value on if you want to pause FPS computation when in background
  11479. */
  11480. this.disablePerformanceMonitorInBackground = false;
  11481. // States
  11482. /** @hidden */
  11483. this._depthCullingState = new BABYLON._DepthCullingState();
  11484. /** @hidden */
  11485. this._stencilState = new BABYLON._StencilState();
  11486. /** @hidden */
  11487. this._alphaState = new BABYLON._AlphaState();
  11488. /** @hidden */
  11489. this._alphaMode = Engine.ALPHA_DISABLE;
  11490. // Cache
  11491. this._internalTexturesCache = new Array();
  11492. /** @hidden */
  11493. this._activeChannel = 0;
  11494. this._currentTextureChannel = -1;
  11495. /** @hidden */
  11496. this._boundTexturesCache = {};
  11497. this._compiledEffects = {};
  11498. this._vertexAttribArraysEnabled = [];
  11499. this._uintIndicesCurrentlySet = false;
  11500. this._currentBoundBuffer = new Array();
  11501. /** @hidden */
  11502. this._currentFramebuffer = null;
  11503. this._currentBufferPointers = new Array();
  11504. this._currentInstanceLocations = new Array();
  11505. this._currentInstanceBuffers = new Array();
  11506. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11507. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11508. this._vaoRecordInProgress = false;
  11509. this._mustWipeVertexAttributes = false;
  11510. this._nextFreeTextureSlots = new Array();
  11511. this._maxSimultaneousTextures = 0;
  11512. this._activeRequests = new Array();
  11513. // Hardware supported Compressed Textures
  11514. this._texturesSupported = new Array();
  11515. /**
  11516. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11517. */
  11518. this.premultipliedAlpha = true;
  11519. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11520. this._onVRFullScreenTriggered = function () {
  11521. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11522. //get the old size before we change
  11523. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11524. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11525. //get the width and height, change the render size
  11526. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11527. _this.setHardwareScalingLevel(1);
  11528. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11529. }
  11530. else {
  11531. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11532. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11533. }
  11534. };
  11535. this._unpackFlipYCached = null;
  11536. /**
  11537. * In case you are sharing the context with other applications, it might
  11538. * be interested to not cache the unpack flip y state to ensure a consistent
  11539. * value would be set.
  11540. */
  11541. this.enableUnpackFlipYCached = true;
  11542. this._boundUniforms = {};
  11543. // Register promises
  11544. BABYLON.PromisePolyfill.Apply();
  11545. var canvas = null;
  11546. Engine.Instances.push(this);
  11547. if (!canvasOrContext) {
  11548. return;
  11549. }
  11550. options = options || {};
  11551. if (canvasOrContext.getContext) {
  11552. canvas = canvasOrContext;
  11553. this._renderingCanvas = canvas;
  11554. if (antialias != null) {
  11555. options.antialias = antialias;
  11556. }
  11557. if (options.deterministicLockstep === undefined) {
  11558. options.deterministicLockstep = false;
  11559. }
  11560. if (options.lockstepMaxSteps === undefined) {
  11561. options.lockstepMaxSteps = 4;
  11562. }
  11563. if (options.preserveDrawingBuffer === undefined) {
  11564. options.preserveDrawingBuffer = false;
  11565. }
  11566. if (options.audioEngine === undefined) {
  11567. options.audioEngine = true;
  11568. }
  11569. if (options.stencil === undefined) {
  11570. options.stencil = true;
  11571. }
  11572. if (options.premultipliedAlpha === false) {
  11573. this.premultipliedAlpha = false;
  11574. }
  11575. this._deterministicLockstep = options.deterministicLockstep;
  11576. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11577. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11578. // Exceptions
  11579. if (navigator && navigator.userAgent) {
  11580. var ua = navigator.userAgent;
  11581. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11582. var exception = _a[_i];
  11583. var key = exception.key;
  11584. var targets = exception.targets;
  11585. if (ua.indexOf(key) > -1) {
  11586. if (exception.capture && exception.captureConstraint) {
  11587. var capture = exception.capture;
  11588. var constraint = exception.captureConstraint;
  11589. var regex = new RegExp(capture);
  11590. var matches = regex.exec(ua);
  11591. if (matches && matches.length > 0) {
  11592. var capturedValue = parseInt(matches[matches.length - 1]);
  11593. if (capturedValue >= constraint) {
  11594. continue;
  11595. }
  11596. }
  11597. }
  11598. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11599. var target = targets_1[_b];
  11600. switch (target) {
  11601. case "uniformBuffer":
  11602. this.disableUniformBuffers = true;
  11603. break;
  11604. case "textureBindingOptimization":
  11605. this.disableTextureBindingOptimization = true;
  11606. break;
  11607. }
  11608. }
  11609. }
  11610. }
  11611. }
  11612. // GL
  11613. if (!options.disableWebGL2Support) {
  11614. try {
  11615. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11616. if (this._gl) {
  11617. this._webGLVersion = 2.0;
  11618. }
  11619. }
  11620. catch (e) {
  11621. // Do nothing
  11622. }
  11623. }
  11624. if (!this._gl) {
  11625. if (!canvas) {
  11626. throw new Error("The provided canvas is null or undefined.");
  11627. }
  11628. try {
  11629. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11630. }
  11631. catch (e) {
  11632. throw new Error("WebGL not supported");
  11633. }
  11634. }
  11635. if (!this._gl) {
  11636. throw new Error("WebGL not supported");
  11637. }
  11638. this._onCanvasFocus = function () {
  11639. _this.onCanvasFocusObservable.notifyObservers(_this);
  11640. };
  11641. this._onCanvasBlur = function () {
  11642. _this.onCanvasBlurObservable.notifyObservers(_this);
  11643. };
  11644. canvas.addEventListener("focus", this._onCanvasFocus);
  11645. canvas.addEventListener("blur", this._onCanvasBlur);
  11646. this._onBlur = function () {
  11647. if (_this.disablePerformanceMonitorInBackground) {
  11648. _this._performanceMonitor.disable();
  11649. }
  11650. _this._windowIsBackground = true;
  11651. };
  11652. this._onFocus = function () {
  11653. if (_this.disablePerformanceMonitorInBackground) {
  11654. _this._performanceMonitor.enable();
  11655. }
  11656. _this._windowIsBackground = false;
  11657. };
  11658. this._onCanvasPointerOut = function (ev) {
  11659. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11660. };
  11661. window.addEventListener("blur", this._onBlur);
  11662. window.addEventListener("focus", this._onFocus);
  11663. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11664. // Context lost
  11665. if (!this._doNotHandleContextLost) {
  11666. this._onContextLost = function (evt) {
  11667. evt.preventDefault();
  11668. _this._contextWasLost = true;
  11669. BABYLON.Tools.Warn("WebGL context lost.");
  11670. _this.onContextLostObservable.notifyObservers(_this);
  11671. };
  11672. this._onContextRestored = function (evt) {
  11673. // Adding a timeout to avoid race condition at browser level
  11674. setTimeout(function () {
  11675. // Rebuild gl context
  11676. _this._initGLContext();
  11677. // Rebuild effects
  11678. _this._rebuildEffects();
  11679. // Rebuild textures
  11680. _this._rebuildInternalTextures();
  11681. // Rebuild buffers
  11682. _this._rebuildBuffers();
  11683. // Cache
  11684. _this.wipeCaches(true);
  11685. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11686. _this.onContextRestoredObservable.notifyObservers(_this);
  11687. _this._contextWasLost = false;
  11688. }, 0);
  11689. };
  11690. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11691. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11692. }
  11693. }
  11694. else {
  11695. this._gl = canvasOrContext;
  11696. this._renderingCanvas = this._gl.canvas;
  11697. if (this._gl.renderbufferStorageMultisample) {
  11698. this._webGLVersion = 2.0;
  11699. }
  11700. options.stencil = this._gl.getContextAttributes().stencil;
  11701. }
  11702. // Viewport
  11703. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11704. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11705. this.resize();
  11706. this._isStencilEnable = options.stencil ? true : false;
  11707. this._initGLContext();
  11708. if (canvas) {
  11709. // Fullscreen
  11710. this._onFullscreenChange = function () {
  11711. if (document.fullscreen !== undefined) {
  11712. _this.isFullscreen = document.fullscreen;
  11713. }
  11714. else if (document.mozFullScreen !== undefined) {
  11715. _this.isFullscreen = document.mozFullScreen;
  11716. }
  11717. else if (document.webkitIsFullScreen !== undefined) {
  11718. _this.isFullscreen = document.webkitIsFullScreen;
  11719. }
  11720. else if (document.msIsFullScreen !== undefined) {
  11721. _this.isFullscreen = document.msIsFullScreen;
  11722. }
  11723. // Pointer lock
  11724. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11725. canvas.requestPointerLock = canvas.requestPointerLock ||
  11726. canvas.msRequestPointerLock ||
  11727. canvas.mozRequestPointerLock ||
  11728. canvas.webkitRequestPointerLock;
  11729. if (canvas.requestPointerLock) {
  11730. canvas.requestPointerLock();
  11731. }
  11732. }
  11733. };
  11734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11738. // Pointer lock
  11739. this._onPointerLockChange = function () {
  11740. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11741. document.webkitPointerLockElement === canvas ||
  11742. document.msPointerLockElement === canvas ||
  11743. document.pointerLockElement === canvas);
  11744. };
  11745. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11746. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11747. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11748. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11749. this._onVRDisplayPointerRestricted = function () {
  11750. if (canvas) {
  11751. canvas.requestPointerLock();
  11752. }
  11753. };
  11754. this._onVRDisplayPointerUnrestricted = function () {
  11755. document.exitPointerLock();
  11756. };
  11757. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11758. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11759. }
  11760. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11761. Engine.audioEngine = new BABYLON.AudioEngine();
  11762. }
  11763. // Prepare buffer pointers
  11764. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11765. this._currentBufferPointers[i] = new BufferPointer();
  11766. }
  11767. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11768. // Load WebVR Devices
  11769. if (options.autoEnableWebVR) {
  11770. this.initWebVR();
  11771. }
  11772. // Detect if we are running on a faulty buggy OS.
  11773. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11774. // Detect if we are running on a faulty buggy desktop OS.
  11775. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11776. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11777. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11778. }
  11779. Object.defineProperty(Engine, "LastCreatedEngine", {
  11780. /**
  11781. * Gets the latest created engine
  11782. */
  11783. get: function () {
  11784. if (Engine.Instances.length === 0) {
  11785. return null;
  11786. }
  11787. return Engine.Instances[Engine.Instances.length - 1];
  11788. },
  11789. enumerable: true,
  11790. configurable: true
  11791. });
  11792. Object.defineProperty(Engine, "LastCreatedScene", {
  11793. /**
  11794. * Gets the latest created scene
  11795. */
  11796. get: function () {
  11797. var lastCreatedEngine = Engine.LastCreatedEngine;
  11798. if (!lastCreatedEngine) {
  11799. return null;
  11800. }
  11801. if (lastCreatedEngine.scenes.length === 0) {
  11802. return null;
  11803. }
  11804. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. /**
  11810. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11811. * @param flag defines which part of the materials must be marked as dirty
  11812. * @param predicate defines a predicate used to filter which materials should be affected
  11813. */
  11814. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11815. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11816. var engine = Engine.Instances[engineIndex];
  11817. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11818. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11819. }
  11820. }
  11821. };
  11822. Object.defineProperty(Engine, "Version", {
  11823. /**
  11824. * Returns the current version of the framework
  11825. */
  11826. get: function () {
  11827. return "3.3.0-beta.5";
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11833. /**
  11834. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11835. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11836. */
  11837. get: function () {
  11838. return this._vrExclusivePointerMode;
  11839. },
  11840. enumerable: true,
  11841. configurable: true
  11842. });
  11843. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11844. /**
  11845. * Gets a boolean indicating that the engine supports uniform buffers
  11846. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11847. */
  11848. get: function () {
  11849. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11855. /**
  11856. * Gets a boolean indicating that only power of 2 textures are supported
  11857. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11858. */
  11859. get: function () {
  11860. return this._webGLVersion < 2 || this.forcePOTTextures;
  11861. },
  11862. enumerable: true,
  11863. configurable: true
  11864. });
  11865. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11866. /**
  11867. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11868. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11869. */
  11870. get: function () {
  11871. return this._doNotHandleContextLost;
  11872. },
  11873. set: function (value) {
  11874. this._doNotHandleContextLost = value;
  11875. },
  11876. enumerable: true,
  11877. configurable: true
  11878. });
  11879. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11880. /**
  11881. * Gets the performance monitor attached to this engine
  11882. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11883. */
  11884. get: function () {
  11885. return this._performanceMonitor;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11891. /**
  11892. * Gets the list of texture formats supported
  11893. */
  11894. get: function () {
  11895. return this._texturesSupported;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11901. /**
  11902. * Gets the list of texture formats in use
  11903. */
  11904. get: function () {
  11905. return this._textureFormatInUse;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine.prototype, "currentViewport", {
  11911. /**
  11912. * Gets the current viewport
  11913. */
  11914. get: function () {
  11915. return this._cachedViewport;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11921. /**
  11922. * Gets the default empty texture
  11923. */
  11924. get: function () {
  11925. if (!this._emptyTexture) {
  11926. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11927. }
  11928. return this._emptyTexture;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11934. /**
  11935. * Gets the default empty 3D texture
  11936. */
  11937. get: function () {
  11938. if (!this._emptyTexture3D) {
  11939. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11940. }
  11941. return this._emptyTexture3D;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11947. /**
  11948. * Gets the default empty cube texture
  11949. */
  11950. get: function () {
  11951. if (!this._emptyCubeTexture) {
  11952. var faceData = new Uint8Array(4);
  11953. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11954. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11955. }
  11956. return this._emptyCubeTexture;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Engine.prototype._rebuildInternalTextures = function () {
  11962. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11963. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11964. var internalTexture = currentState_1[_i];
  11965. internalTexture._rebuild();
  11966. }
  11967. };
  11968. Engine.prototype._rebuildEffects = function () {
  11969. for (var key in this._compiledEffects) {
  11970. var effect = this._compiledEffects[key];
  11971. effect._prepareEffect();
  11972. }
  11973. BABYLON.Effect.ResetCache();
  11974. };
  11975. Engine.prototype._rebuildBuffers = function () {
  11976. // Index / Vertex
  11977. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11978. var scene = _a[_i];
  11979. scene.resetCachedMaterial();
  11980. scene._rebuildGeometries();
  11981. scene._rebuildTextures();
  11982. }
  11983. // Uniforms
  11984. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11985. var uniformBuffer = _c[_b];
  11986. uniformBuffer._rebuild();
  11987. }
  11988. };
  11989. Engine.prototype._initGLContext = function () {
  11990. // Caps
  11991. this._caps = new EngineCapabilities();
  11992. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11993. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11994. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11995. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11996. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11997. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11998. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11999. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12000. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12001. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12002. // Infos
  12003. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12004. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12005. if (rendererInfo != null) {
  12006. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12007. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12008. }
  12009. if (!this._glVendor) {
  12010. this._glVendor = "Unknown vendor";
  12011. }
  12012. if (!this._glRenderer) {
  12013. this._glRenderer = "Unknown renderer";
  12014. }
  12015. // Constants
  12016. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12017. if (this._gl.RGBA16F !== 0x881A) {
  12018. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12019. }
  12020. if (this._gl.RGBA32F !== 0x8814) {
  12021. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12022. }
  12023. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12024. this._gl.DEPTH24_STENCIL8 = 35056;
  12025. }
  12026. // Extensions
  12027. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12028. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12029. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12030. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12031. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12032. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12033. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12034. 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');
  12035. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12036. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12037. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12038. this._caps.highPrecisionShaderSupported = true;
  12039. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12040. if (this._caps.timerQuery) {
  12041. if (this._webGLVersion === 1) {
  12042. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12043. }
  12044. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12045. }
  12046. // Checks if some of the format renders first to allow the use of webgl inspector.
  12047. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12048. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12049. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12050. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12051. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12052. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12053. if (this._webGLVersion > 1) {
  12054. this._gl.HALF_FLOAT_OES = 0x140B;
  12055. }
  12056. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12057. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12058. // Draw buffers
  12059. if (this._webGLVersion > 1) {
  12060. this._caps.drawBuffersExtension = true;
  12061. }
  12062. else {
  12063. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12064. if (drawBuffersExtension !== null) {
  12065. this._caps.drawBuffersExtension = true;
  12066. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12067. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12068. for (var i = 0; i < 16; i++) {
  12069. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12070. }
  12071. }
  12072. else {
  12073. this._caps.drawBuffersExtension = false;
  12074. }
  12075. }
  12076. // Depth Texture
  12077. if (this._webGLVersion > 1) {
  12078. this._caps.depthTextureExtension = true;
  12079. }
  12080. else {
  12081. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12082. if (depthTextureExtension != null) {
  12083. this._caps.depthTextureExtension = true;
  12084. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12085. }
  12086. }
  12087. // Vertex array object
  12088. if (this._webGLVersion > 1) {
  12089. this._caps.vertexArrayObject = true;
  12090. }
  12091. else {
  12092. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12093. if (vertexArrayObjectExtension != null) {
  12094. this._caps.vertexArrayObject = true;
  12095. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12096. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12097. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12098. }
  12099. else {
  12100. this._caps.vertexArrayObject = false;
  12101. }
  12102. }
  12103. // Instances count
  12104. if (this._webGLVersion > 1) {
  12105. this._caps.instancedArrays = true;
  12106. }
  12107. else {
  12108. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12109. if (instanceExtension != null) {
  12110. this._caps.instancedArrays = true;
  12111. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12112. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12113. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12114. }
  12115. else {
  12116. this._caps.instancedArrays = false;
  12117. }
  12118. }
  12119. // Intelligently add supported compressed formats in order to check for.
  12120. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12121. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12122. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12123. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12124. if (this._caps.astc)
  12125. this.texturesSupported.push('-astc.ktx');
  12126. if (this._caps.s3tc)
  12127. this.texturesSupported.push('-dxt.ktx');
  12128. if (this._caps.pvrtc)
  12129. this.texturesSupported.push('-pvrtc.ktx');
  12130. if (this._caps.etc2)
  12131. this.texturesSupported.push('-etc2.ktx');
  12132. if (this._caps.etc1)
  12133. this.texturesSupported.push('-etc1.ktx');
  12134. if (this._gl.getShaderPrecisionFormat) {
  12135. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12136. if (highp) {
  12137. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12138. }
  12139. }
  12140. // Depth buffer
  12141. this.setDepthBuffer(true);
  12142. this.setDepthFunctionToLessOrEqual();
  12143. this.setDepthWrite(true);
  12144. // Texture maps
  12145. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12146. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12147. this._nextFreeTextureSlots.push(slot);
  12148. }
  12149. };
  12150. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12151. /**
  12152. * Gets version of the current webGL context
  12153. */
  12154. get: function () {
  12155. return this._webGLVersion;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12161. /**
  12162. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12163. */
  12164. get: function () {
  12165. return this._isStencilEnable;
  12166. },
  12167. enumerable: true,
  12168. configurable: true
  12169. });
  12170. Engine.prototype._prepareWorkingCanvas = function () {
  12171. if (this._workingCanvas) {
  12172. return;
  12173. }
  12174. this._workingCanvas = document.createElement("canvas");
  12175. var context = this._workingCanvas.getContext("2d");
  12176. if (context) {
  12177. this._workingContext = context;
  12178. }
  12179. };
  12180. /**
  12181. * Reset the texture cache to empty state
  12182. */
  12183. Engine.prototype.resetTextureCache = function () {
  12184. for (var key in this._boundTexturesCache) {
  12185. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12186. continue;
  12187. }
  12188. var boundTexture = this._boundTexturesCache[key];
  12189. if (boundTexture) {
  12190. this._removeDesignatedSlot(boundTexture);
  12191. }
  12192. this._boundTexturesCache[key] = null;
  12193. }
  12194. if (!this.disableTextureBindingOptimization) {
  12195. this._nextFreeTextureSlots = [];
  12196. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12197. this._nextFreeTextureSlots.push(slot);
  12198. }
  12199. }
  12200. this._currentTextureChannel = -1;
  12201. };
  12202. /**
  12203. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12204. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12205. * @returns true if engine is in deterministic lock step mode
  12206. */
  12207. Engine.prototype.isDeterministicLockStep = function () {
  12208. return this._deterministicLockstep;
  12209. };
  12210. /**
  12211. * Gets the max steps when engine is running in deterministic lock step
  12212. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12213. * @returns the max steps
  12214. */
  12215. Engine.prototype.getLockstepMaxSteps = function () {
  12216. return this._lockstepMaxSteps;
  12217. };
  12218. /**
  12219. * Gets an object containing information about the current webGL context
  12220. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12221. */
  12222. Engine.prototype.getGlInfo = function () {
  12223. return {
  12224. vendor: this._glVendor,
  12225. renderer: this._glRenderer,
  12226. version: this._glVersion
  12227. };
  12228. };
  12229. /**
  12230. * Gets current aspect ratio
  12231. * @param camera defines the camera to use to get the aspect ratio
  12232. * @param useScreen defines if screen size must be used (or the current render target if any)
  12233. * @returns a number defining the aspect ratio
  12234. */
  12235. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12236. if (useScreen === void 0) { useScreen = false; }
  12237. var viewport = camera.viewport;
  12238. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12239. };
  12240. /**
  12241. * Gets current screen aspect ratio
  12242. * @returns a number defining the aspect ratio
  12243. */
  12244. Engine.prototype.getScreenAspectRatio = function () {
  12245. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12246. };
  12247. /**
  12248. * Gets the current render width
  12249. * @param useScreen defines if screen size must be used (or the current render target if any)
  12250. * @returns a number defining the current render width
  12251. */
  12252. Engine.prototype.getRenderWidth = function (useScreen) {
  12253. if (useScreen === void 0) { useScreen = false; }
  12254. if (!useScreen && this._currentRenderTarget) {
  12255. return this._currentRenderTarget.width;
  12256. }
  12257. return this._gl.drawingBufferWidth;
  12258. };
  12259. /**
  12260. * Gets the current render height
  12261. * @param useScreen defines if screen size must be used (or the current render target if any)
  12262. * @returns a number defining the current render height
  12263. */
  12264. Engine.prototype.getRenderHeight = function (useScreen) {
  12265. if (useScreen === void 0) { useScreen = false; }
  12266. if (!useScreen && this._currentRenderTarget) {
  12267. return this._currentRenderTarget.height;
  12268. }
  12269. return this._gl.drawingBufferHeight;
  12270. };
  12271. /**
  12272. * Gets the HTML canvas attached with the current webGL context
  12273. * @returns a HTML canvas
  12274. */
  12275. Engine.prototype.getRenderingCanvas = function () {
  12276. return this._renderingCanvas;
  12277. };
  12278. /**
  12279. * Gets the client rect of the HTML canvas attached with the current webGL context
  12280. * @returns a client rectanglee
  12281. */
  12282. Engine.prototype.getRenderingCanvasClientRect = function () {
  12283. if (!this._renderingCanvas) {
  12284. return null;
  12285. }
  12286. return this._renderingCanvas.getBoundingClientRect();
  12287. };
  12288. /**
  12289. * Defines the hardware scaling level.
  12290. * By default the hardware scaling level is computed from the window device ratio.
  12291. * 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.
  12292. * @param level defines the level to use
  12293. */
  12294. Engine.prototype.setHardwareScalingLevel = function (level) {
  12295. this._hardwareScalingLevel = level;
  12296. this.resize();
  12297. };
  12298. /**
  12299. * Gets the current hardware scaling level.
  12300. * By default the hardware scaling level is computed from the window device ratio.
  12301. * 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.
  12302. * @returns a number indicating the current hardware scaling level
  12303. */
  12304. Engine.prototype.getHardwareScalingLevel = function () {
  12305. return this._hardwareScalingLevel;
  12306. };
  12307. /**
  12308. * Gets the list of loaded textures
  12309. * @returns an array containing all loaded textures
  12310. */
  12311. Engine.prototype.getLoadedTexturesCache = function () {
  12312. return this._internalTexturesCache;
  12313. };
  12314. /**
  12315. * Gets the object containing all engine capabilities
  12316. * @returns the EngineCapabilities object
  12317. */
  12318. Engine.prototype.getCaps = function () {
  12319. return this._caps;
  12320. };
  12321. Object.defineProperty(Engine.prototype, "drawCalls", {
  12322. /** @hidden */
  12323. get: function () {
  12324. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12325. return 0;
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12331. /** @hidden */
  12332. get: function () {
  12333. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12334. return null;
  12335. },
  12336. enumerable: true,
  12337. configurable: true
  12338. });
  12339. /**
  12340. * Gets the current depth function
  12341. * @returns a number defining the depth function
  12342. */
  12343. Engine.prototype.getDepthFunction = function () {
  12344. return this._depthCullingState.depthFunc;
  12345. };
  12346. /**
  12347. * Sets the current depth function
  12348. * @param depthFunc defines the function to use
  12349. */
  12350. Engine.prototype.setDepthFunction = function (depthFunc) {
  12351. this._depthCullingState.depthFunc = depthFunc;
  12352. };
  12353. /**
  12354. * Sets the current depth function to GREATER
  12355. */
  12356. Engine.prototype.setDepthFunctionToGreater = function () {
  12357. this._depthCullingState.depthFunc = this._gl.GREATER;
  12358. };
  12359. /**
  12360. * Sets the current depth function to GEQUAL
  12361. */
  12362. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12363. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12364. };
  12365. /**
  12366. * Sets the current depth function to LESS
  12367. */
  12368. Engine.prototype.setDepthFunctionToLess = function () {
  12369. this._depthCullingState.depthFunc = this._gl.LESS;
  12370. };
  12371. /**
  12372. * Sets the current depth function to LEQUAL
  12373. */
  12374. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12375. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12376. };
  12377. /**
  12378. * Gets a boolean indicating if stencil buffer is enabled
  12379. * @returns the current stencil buffer state
  12380. */
  12381. Engine.prototype.getStencilBuffer = function () {
  12382. return this._stencilState.stencilTest;
  12383. };
  12384. /**
  12385. * Enable or disable the stencil buffer
  12386. * @param enable defines if the stencil buffer must be enabled or disabled
  12387. */
  12388. Engine.prototype.setStencilBuffer = function (enable) {
  12389. this._stencilState.stencilTest = enable;
  12390. };
  12391. /**
  12392. * Gets the current stencil mask
  12393. * @returns a number defining the new stencil mask to use
  12394. */
  12395. Engine.prototype.getStencilMask = function () {
  12396. return this._stencilState.stencilMask;
  12397. };
  12398. /**
  12399. * Sets the current stencil mask
  12400. * @param mask defines the new stencil mask to use
  12401. */
  12402. Engine.prototype.setStencilMask = function (mask) {
  12403. this._stencilState.stencilMask = mask;
  12404. };
  12405. /**
  12406. * Gets the current stencil function
  12407. * @returns a number defining the stencil function to use
  12408. */
  12409. Engine.prototype.getStencilFunction = function () {
  12410. return this._stencilState.stencilFunc;
  12411. };
  12412. /**
  12413. * Gets the current stencil reference value
  12414. * @returns a number defining the stencil reference value to use
  12415. */
  12416. Engine.prototype.getStencilFunctionReference = function () {
  12417. return this._stencilState.stencilFuncRef;
  12418. };
  12419. /**
  12420. * Gets the current stencil mask
  12421. * @returns a number defining the stencil mask to use
  12422. */
  12423. Engine.prototype.getStencilFunctionMask = function () {
  12424. return this._stencilState.stencilFuncMask;
  12425. };
  12426. /**
  12427. * Sets the current stencil function
  12428. * @param stencilFunc defines the new stencil function to use
  12429. */
  12430. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12431. this._stencilState.stencilFunc = stencilFunc;
  12432. };
  12433. /**
  12434. * Sets the current stencil reference
  12435. * @param reference defines the new stencil reference to use
  12436. */
  12437. Engine.prototype.setStencilFunctionReference = function (reference) {
  12438. this._stencilState.stencilFuncRef = reference;
  12439. };
  12440. /**
  12441. * Sets the current stencil mask
  12442. * @param mask defines the new stencil mask to use
  12443. */
  12444. Engine.prototype.setStencilFunctionMask = function (mask) {
  12445. this._stencilState.stencilFuncMask = mask;
  12446. };
  12447. /**
  12448. * Gets the current stencil operation when stencil fails
  12449. * @returns a number defining stencil operation to use when stencil fails
  12450. */
  12451. Engine.prototype.getStencilOperationFail = function () {
  12452. return this._stencilState.stencilOpStencilFail;
  12453. };
  12454. /**
  12455. * Gets the current stencil operation when depth fails
  12456. * @returns a number defining stencil operation to use when depth fails
  12457. */
  12458. Engine.prototype.getStencilOperationDepthFail = function () {
  12459. return this._stencilState.stencilOpDepthFail;
  12460. };
  12461. /**
  12462. * Gets the current stencil operation when stencil passes
  12463. * @returns a number defining stencil operation to use when stencil passes
  12464. */
  12465. Engine.prototype.getStencilOperationPass = function () {
  12466. return this._stencilState.stencilOpStencilDepthPass;
  12467. };
  12468. /**
  12469. * Sets the stencil operation to use when stencil fails
  12470. * @param operation defines the stencil operation to use when stencil fails
  12471. */
  12472. Engine.prototype.setStencilOperationFail = function (operation) {
  12473. this._stencilState.stencilOpStencilFail = operation;
  12474. };
  12475. /**
  12476. * Sets the stencil operation to use when depth fails
  12477. * @param operation defines the stencil operation to use when depth fails
  12478. */
  12479. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12480. this._stencilState.stencilOpDepthFail = operation;
  12481. };
  12482. /**
  12483. * Sets the stencil operation to use when stencil passes
  12484. * @param operation defines the stencil operation to use when stencil passes
  12485. */
  12486. Engine.prototype.setStencilOperationPass = function (operation) {
  12487. this._stencilState.stencilOpStencilDepthPass = operation;
  12488. };
  12489. /**
  12490. * Sets a boolean indicating if the dithering state is enabled or disabled
  12491. * @param value defines the dithering state
  12492. */
  12493. Engine.prototype.setDitheringState = function (value) {
  12494. if (value) {
  12495. this._gl.enable(this._gl.DITHER);
  12496. }
  12497. else {
  12498. this._gl.disable(this._gl.DITHER);
  12499. }
  12500. };
  12501. /**
  12502. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12503. * @param value defines the rasterizer state
  12504. */
  12505. Engine.prototype.setRasterizerState = function (value) {
  12506. if (value) {
  12507. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12508. }
  12509. else {
  12510. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12511. }
  12512. };
  12513. /**
  12514. * stop executing a render loop function and remove it from the execution array
  12515. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12516. */
  12517. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12518. if (!renderFunction) {
  12519. this._activeRenderLoops = [];
  12520. return;
  12521. }
  12522. var index = this._activeRenderLoops.indexOf(renderFunction);
  12523. if (index >= 0) {
  12524. this._activeRenderLoops.splice(index, 1);
  12525. }
  12526. };
  12527. /** @hidden */
  12528. Engine.prototype._renderLoop = function () {
  12529. if (!this._contextWasLost) {
  12530. var shouldRender = true;
  12531. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12532. shouldRender = false;
  12533. }
  12534. if (shouldRender) {
  12535. // Start new frame
  12536. this.beginFrame();
  12537. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12538. var renderFunction = this._activeRenderLoops[index];
  12539. renderFunction();
  12540. }
  12541. // Present
  12542. this.endFrame();
  12543. }
  12544. }
  12545. if (this._activeRenderLoops.length > 0) {
  12546. // Register new frame
  12547. var requester = null;
  12548. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12549. requester = this._vrDisplay;
  12550. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12551. }
  12552. else {
  12553. this._renderingQueueLaunched = false;
  12554. }
  12555. };
  12556. /**
  12557. * Register and execute a render loop. The engine can have more than one render function
  12558. * @param renderFunction defines the function to continuously execute
  12559. */
  12560. Engine.prototype.runRenderLoop = function (renderFunction) {
  12561. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12562. return;
  12563. }
  12564. this._activeRenderLoops.push(renderFunction);
  12565. if (!this._renderingQueueLaunched) {
  12566. this._renderingQueueLaunched = true;
  12567. this._bindedRenderFunction = this._renderLoop.bind(this);
  12568. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12569. }
  12570. };
  12571. /**
  12572. * Toggle full screen mode
  12573. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12574. * @param options defines an option object to be sent to the requestFullscreen function
  12575. */
  12576. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12577. if (this.isFullscreen) {
  12578. BABYLON.Tools.ExitFullscreen();
  12579. }
  12580. else {
  12581. this._pointerLockRequested = requestPointerLock;
  12582. if (this._renderingCanvas) {
  12583. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12584. }
  12585. }
  12586. };
  12587. /**
  12588. * Clear the current render buffer or the current render target (if any is set up)
  12589. * @param color defines the color to use
  12590. * @param backBuffer defines if the back buffer must be cleared
  12591. * @param depth defines if the depth buffer must be cleared
  12592. * @param stencil defines if the stencil buffer must be cleared
  12593. */
  12594. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12595. if (stencil === void 0) { stencil = false; }
  12596. this.applyStates();
  12597. var mode = 0;
  12598. if (backBuffer && color) {
  12599. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12600. mode |= this._gl.COLOR_BUFFER_BIT;
  12601. }
  12602. if (depth) {
  12603. this._gl.clearDepth(1.0);
  12604. mode |= this._gl.DEPTH_BUFFER_BIT;
  12605. }
  12606. if (stencil) {
  12607. this._gl.clearStencil(0);
  12608. mode |= this._gl.STENCIL_BUFFER_BIT;
  12609. }
  12610. this._gl.clear(mode);
  12611. };
  12612. /**
  12613. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12614. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12615. * @param y defines the y-coordinate of the corner of the clear rectangle
  12616. * @param width defines the width of the clear rectangle
  12617. * @param height defines the height of the clear rectangle
  12618. * @param clearColor defines the clear color
  12619. */
  12620. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12621. var gl = this._gl;
  12622. // Save state
  12623. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12624. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12625. // Change state
  12626. gl.enable(gl.SCISSOR_TEST);
  12627. gl.scissor(x, y, width, height);
  12628. // Clear
  12629. this.clear(clearColor, true, true, true);
  12630. // Restore state
  12631. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12632. if (curScissor === true) {
  12633. gl.enable(gl.SCISSOR_TEST);
  12634. }
  12635. else {
  12636. gl.disable(gl.SCISSOR_TEST);
  12637. }
  12638. };
  12639. /** @hidden */
  12640. Engine.prototype._viewport = function (x, y, width, height) {
  12641. if (x !== this._viewportCached.x ||
  12642. y !== this._viewportCached.y ||
  12643. width !== this._viewportCached.z ||
  12644. height !== this._viewportCached.w) {
  12645. this._viewportCached.x = x;
  12646. this._viewportCached.y = y;
  12647. this._viewportCached.z = width;
  12648. this._viewportCached.w = height;
  12649. this._gl.viewport(x, y, width, height);
  12650. }
  12651. };
  12652. /**
  12653. * Set the WebGL's viewport
  12654. * @param viewport defines the viewport element to be used
  12655. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12656. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12657. */
  12658. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12659. var width = requiredWidth || this.getRenderWidth();
  12660. var height = requiredHeight || this.getRenderHeight();
  12661. var x = viewport.x || 0;
  12662. var y = viewport.y || 0;
  12663. this._cachedViewport = viewport;
  12664. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12665. };
  12666. /**
  12667. * Directly set the WebGL Viewport
  12668. * @param x defines the x coordinate of the viewport (in screen space)
  12669. * @param y defines the y coordinate of the viewport (in screen space)
  12670. * @param width defines the width of the viewport (in screen space)
  12671. * @param height defines the height of the viewport (in screen space)
  12672. * @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
  12673. */
  12674. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12675. var currentViewport = this._cachedViewport;
  12676. this._cachedViewport = null;
  12677. this._viewport(x, y, width, height);
  12678. return currentViewport;
  12679. };
  12680. /**
  12681. * Begin a new frame
  12682. */
  12683. Engine.prototype.beginFrame = function () {
  12684. this.onBeginFrameObservable.notifyObservers(this);
  12685. this._measureFps();
  12686. };
  12687. /**
  12688. * Enf the current frame
  12689. */
  12690. Engine.prototype.endFrame = function () {
  12691. // Force a flush in case we are using a bad OS.
  12692. if (this._badOS) {
  12693. this.flushFramebuffer();
  12694. }
  12695. // Submit frame to the vr device, if enabled
  12696. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12697. // TODO: We should only submit the frame if we read frameData successfully.
  12698. this._vrDisplay.submitFrame();
  12699. }
  12700. this.onEndFrameObservable.notifyObservers(this);
  12701. };
  12702. /**
  12703. * Resize the view according to the canvas' size
  12704. */
  12705. Engine.prototype.resize = function () {
  12706. // We're not resizing the size of the canvas while in VR mode & presenting
  12707. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12708. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12709. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12710. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12711. }
  12712. };
  12713. /**
  12714. * Force a specific size of the canvas
  12715. * @param width defines the new canvas' width
  12716. * @param height defines the new canvas' height
  12717. */
  12718. Engine.prototype.setSize = function (width, height) {
  12719. if (!this._renderingCanvas) {
  12720. return;
  12721. }
  12722. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12723. return;
  12724. }
  12725. this._renderingCanvas.width = width;
  12726. this._renderingCanvas.height = height;
  12727. for (var index = 0; index < this.scenes.length; index++) {
  12728. var scene = this.scenes[index];
  12729. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12730. var cam = scene.cameras[camIndex];
  12731. cam._currentRenderId = 0;
  12732. }
  12733. }
  12734. if (this.onResizeObservable.hasObservers) {
  12735. this.onResizeObservable.notifyObservers(this);
  12736. }
  12737. };
  12738. // WebVR functions
  12739. /**
  12740. * Gets a boolean indicating if a webVR device was detected
  12741. * @returns true if a webVR device was detected
  12742. */
  12743. Engine.prototype.isVRDevicePresent = function () {
  12744. return !!this._vrDisplay;
  12745. };
  12746. /**
  12747. * Gets the current webVR device
  12748. * @returns the current webVR device (or null)
  12749. */
  12750. Engine.prototype.getVRDevice = function () {
  12751. return this._vrDisplay;
  12752. };
  12753. /**
  12754. * Initializes a webVR display and starts listening to display change events
  12755. * The onVRDisplayChangedObservable will be notified upon these changes
  12756. * @returns The onVRDisplayChangedObservable
  12757. */
  12758. Engine.prototype.initWebVR = function () {
  12759. this.initWebVRAsync();
  12760. return this.onVRDisplayChangedObservable;
  12761. };
  12762. /**
  12763. * Initializes a webVR display and starts listening to display change events
  12764. * The onVRDisplayChangedObservable will be notified upon these changes
  12765. * @returns A promise containing a VRDisplay and if vr is supported
  12766. */
  12767. Engine.prototype.initWebVRAsync = function () {
  12768. var _this = this;
  12769. var notifyObservers = function () {
  12770. var eventArgs = {
  12771. vrDisplay: _this._vrDisplay,
  12772. vrSupported: _this._vrSupported
  12773. };
  12774. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12775. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12776. };
  12777. if (!this._onVrDisplayConnect) {
  12778. this._onVrDisplayConnect = function (event) {
  12779. _this._vrDisplay = event.display;
  12780. notifyObservers();
  12781. };
  12782. this._onVrDisplayDisconnect = function () {
  12783. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12784. _this._vrDisplay = undefined;
  12785. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12786. notifyObservers();
  12787. };
  12788. this._onVrDisplayPresentChange = function () {
  12789. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12790. };
  12791. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12792. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12793. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12794. }
  12795. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12796. this._webVRInitPromise.then(notifyObservers);
  12797. return this._webVRInitPromise;
  12798. };
  12799. /**
  12800. * Call this function to switch to webVR mode
  12801. * Will do nothing if webVR is not supported or if there is no webVR device
  12802. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12803. */
  12804. Engine.prototype.enableVR = function () {
  12805. var _this = this;
  12806. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12807. var onResolved = function () {
  12808. _this.onVRRequestPresentComplete.notifyObservers(true);
  12809. _this._onVRFullScreenTriggered();
  12810. };
  12811. var onRejected = function () {
  12812. _this.onVRRequestPresentComplete.notifyObservers(false);
  12813. };
  12814. this.onVRRequestPresentStart.notifyObservers(this);
  12815. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12816. }
  12817. };
  12818. /**
  12819. * Call this function to leave webVR mode
  12820. * Will do nothing if webVR is not supported or if there is no webVR device
  12821. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12822. */
  12823. Engine.prototype.disableVR = function () {
  12824. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12825. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12826. }
  12827. };
  12828. Engine.prototype._getVRDisplaysAsync = function () {
  12829. var _this = this;
  12830. return new Promise(function (res, rej) {
  12831. if (navigator.getVRDisplays) {
  12832. navigator.getVRDisplays().then(function (devices) {
  12833. _this._vrSupported = true;
  12834. // note that devices may actually be an empty array. This is fine;
  12835. // we expect this._vrDisplay to be undefined in this case.
  12836. _this._vrDisplay = devices[0];
  12837. res({
  12838. vrDisplay: _this._vrDisplay,
  12839. vrSupported: _this._vrSupported
  12840. });
  12841. });
  12842. }
  12843. else {
  12844. _this._vrDisplay = undefined;
  12845. _this._vrSupported = false;
  12846. res({
  12847. vrDisplay: _this._vrDisplay,
  12848. vrSupported: _this._vrSupported
  12849. });
  12850. }
  12851. });
  12852. };
  12853. /**
  12854. * Binds the frame buffer to the specified texture.
  12855. * @param texture The texture to render to or null for the default canvas
  12856. * @param faceIndex The face of the texture to render to in case of cube texture
  12857. * @param requiredWidth The width of the target to render to
  12858. * @param requiredHeight The height of the target to render to
  12859. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12860. * @param depthStencilTexture The depth stencil texture to use to render
  12861. * @param lodLevel defines le lod level to bind to the frame buffer
  12862. */
  12863. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12864. if (lodLevel === void 0) { lodLevel = 0; }
  12865. if (this._currentRenderTarget) {
  12866. this.unBindFramebuffer(this._currentRenderTarget);
  12867. }
  12868. this._currentRenderTarget = texture;
  12869. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12870. var gl = this._gl;
  12871. if (texture.isCube) {
  12872. if (faceIndex === undefined) {
  12873. faceIndex = 0;
  12874. }
  12875. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12876. if (depthStencilTexture) {
  12877. if (depthStencilTexture._generateStencilBuffer) {
  12878. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12879. }
  12880. else {
  12881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12882. }
  12883. }
  12884. }
  12885. if (this._cachedViewport && !forceFullscreenViewport) {
  12886. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12887. }
  12888. else {
  12889. if (!requiredWidth) {
  12890. requiredWidth = texture.width;
  12891. if (lodLevel) {
  12892. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12893. }
  12894. }
  12895. if (!requiredHeight) {
  12896. requiredHeight = texture.height;
  12897. if (lodLevel) {
  12898. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12899. }
  12900. }
  12901. this._viewport(0, 0, requiredWidth, requiredHeight);
  12902. }
  12903. this.wipeCaches();
  12904. };
  12905. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12906. if (this._currentFramebuffer !== framebuffer) {
  12907. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12908. this._currentFramebuffer = framebuffer;
  12909. }
  12910. };
  12911. /**
  12912. * Unbind the current render target texture from the webGL context
  12913. * @param texture defines the render target texture to unbind
  12914. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12915. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12916. */
  12917. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12918. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12919. this._currentRenderTarget = null;
  12920. // If MSAA, we need to bitblt back to main texture
  12921. var gl = this._gl;
  12922. if (texture._MSAAFramebuffer) {
  12923. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12924. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12925. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12926. }
  12927. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12928. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12929. gl.generateMipmap(gl.TEXTURE_2D);
  12930. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12931. }
  12932. if (onBeforeUnbind) {
  12933. if (texture._MSAAFramebuffer) {
  12934. // Bind the correct framebuffer
  12935. this.bindUnboundFramebuffer(texture._framebuffer);
  12936. }
  12937. onBeforeUnbind();
  12938. }
  12939. this.bindUnboundFramebuffer(null);
  12940. };
  12941. /**
  12942. * Unbind a list of render target textures from the webGL context
  12943. * This is used only when drawBuffer extension or webGL2 are active
  12944. * @param textures defines the render target textures to unbind
  12945. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12946. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12947. */
  12948. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12949. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12950. this._currentRenderTarget = null;
  12951. // If MSAA, we need to bitblt back to main texture
  12952. var gl = this._gl;
  12953. if (textures[0]._MSAAFramebuffer) {
  12954. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12955. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12956. var attachments = textures[0]._attachments;
  12957. if (!attachments) {
  12958. attachments = new Array(textures.length);
  12959. textures[0]._attachments = attachments;
  12960. }
  12961. for (var i = 0; i < textures.length; i++) {
  12962. var texture = textures[i];
  12963. for (var j = 0; j < attachments.length; j++) {
  12964. attachments[j] = gl.NONE;
  12965. }
  12966. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12967. gl.readBuffer(attachments[i]);
  12968. gl.drawBuffers(attachments);
  12969. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12970. }
  12971. for (var i = 0; i < attachments.length; i++) {
  12972. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12973. }
  12974. gl.drawBuffers(attachments);
  12975. }
  12976. for (var i = 0; i < textures.length; i++) {
  12977. var texture = textures[i];
  12978. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12979. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12980. gl.generateMipmap(gl.TEXTURE_2D);
  12981. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12982. }
  12983. }
  12984. if (onBeforeUnbind) {
  12985. if (textures[0]._MSAAFramebuffer) {
  12986. // Bind the correct framebuffer
  12987. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12988. }
  12989. onBeforeUnbind();
  12990. }
  12991. this.bindUnboundFramebuffer(null);
  12992. };
  12993. /**
  12994. * Force the mipmap generation for the given render target texture
  12995. * @param texture defines the render target texture to use
  12996. */
  12997. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12998. if (texture.generateMipMaps) {
  12999. var gl = this._gl;
  13000. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13001. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13002. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13003. }
  13004. };
  13005. /**
  13006. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13007. */
  13008. Engine.prototype.flushFramebuffer = function () {
  13009. this._gl.flush();
  13010. };
  13011. /**
  13012. * Unbind the current render target and bind the default framebuffer
  13013. */
  13014. Engine.prototype.restoreDefaultFramebuffer = function () {
  13015. if (this._currentRenderTarget) {
  13016. this.unBindFramebuffer(this._currentRenderTarget);
  13017. }
  13018. else {
  13019. this.bindUnboundFramebuffer(null);
  13020. }
  13021. if (this._cachedViewport) {
  13022. this.setViewport(this._cachedViewport);
  13023. }
  13024. this.wipeCaches();
  13025. };
  13026. // UBOs
  13027. /**
  13028. * Create an uniform buffer
  13029. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13030. * @param elements defines the content of the uniform buffer
  13031. * @returns the webGL uniform buffer
  13032. */
  13033. Engine.prototype.createUniformBuffer = function (elements) {
  13034. var ubo = this._gl.createBuffer();
  13035. if (!ubo) {
  13036. throw new Error("Unable to create uniform buffer");
  13037. }
  13038. this.bindUniformBuffer(ubo);
  13039. if (elements instanceof Float32Array) {
  13040. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13041. }
  13042. else {
  13043. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13044. }
  13045. this.bindUniformBuffer(null);
  13046. ubo.references = 1;
  13047. return ubo;
  13048. };
  13049. /**
  13050. * Create a dynamic uniform buffer
  13051. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13052. * @param elements defines the content of the uniform buffer
  13053. * @returns the webGL uniform buffer
  13054. */
  13055. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13056. var ubo = this._gl.createBuffer();
  13057. if (!ubo) {
  13058. throw new Error("Unable to create dynamic uniform buffer");
  13059. }
  13060. this.bindUniformBuffer(ubo);
  13061. if (elements instanceof Float32Array) {
  13062. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13063. }
  13064. else {
  13065. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13066. }
  13067. this.bindUniformBuffer(null);
  13068. ubo.references = 1;
  13069. return ubo;
  13070. };
  13071. /**
  13072. * Update an existing uniform buffer
  13073. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13074. * @param uniformBuffer defines the target uniform buffer
  13075. * @param elements defines the content to update
  13076. * @param offset defines the offset in the uniform buffer where update should start
  13077. * @param count defines the size of the data to update
  13078. */
  13079. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13080. this.bindUniformBuffer(uniformBuffer);
  13081. if (offset === undefined) {
  13082. offset = 0;
  13083. }
  13084. if (count === undefined) {
  13085. if (elements instanceof Float32Array) {
  13086. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13087. }
  13088. else {
  13089. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13090. }
  13091. }
  13092. else {
  13093. if (elements instanceof Float32Array) {
  13094. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13095. }
  13096. else {
  13097. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13098. }
  13099. }
  13100. this.bindUniformBuffer(null);
  13101. };
  13102. // VBOs
  13103. Engine.prototype._resetVertexBufferBinding = function () {
  13104. this.bindArrayBuffer(null);
  13105. this._cachedVertexBuffers = null;
  13106. };
  13107. /**
  13108. * Creates a vertex buffer
  13109. * @param data the data for the vertex buffer
  13110. * @returns the new WebGL static buffer
  13111. */
  13112. Engine.prototype.createVertexBuffer = function (data) {
  13113. var vbo = this._gl.createBuffer();
  13114. if (!vbo) {
  13115. throw new Error("Unable to create vertex buffer");
  13116. }
  13117. this.bindArrayBuffer(vbo);
  13118. if (data instanceof Array) {
  13119. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13120. }
  13121. else {
  13122. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13123. }
  13124. this._resetVertexBufferBinding();
  13125. vbo.references = 1;
  13126. return vbo;
  13127. };
  13128. /**
  13129. * Creates a dynamic vertex buffer
  13130. * @param data the data for the dynamic vertex buffer
  13131. * @returns the new WebGL dynamic buffer
  13132. */
  13133. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13134. var vbo = this._gl.createBuffer();
  13135. if (!vbo) {
  13136. throw new Error("Unable to create dynamic vertex buffer");
  13137. }
  13138. this.bindArrayBuffer(vbo);
  13139. if (data instanceof Array) {
  13140. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13141. }
  13142. else {
  13143. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13144. }
  13145. this._resetVertexBufferBinding();
  13146. vbo.references = 1;
  13147. return vbo;
  13148. };
  13149. /**
  13150. * Update a dynamic index buffer
  13151. * @param indexBuffer defines the target index buffer
  13152. * @param indices defines the data to update
  13153. * @param offset defines the offset in the target index buffer where update should start
  13154. */
  13155. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13156. if (offset === void 0) { offset = 0; }
  13157. // Force cache update
  13158. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13159. this.bindIndexBuffer(indexBuffer);
  13160. var arrayBuffer;
  13161. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13162. arrayBuffer = indices;
  13163. }
  13164. else {
  13165. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13166. }
  13167. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13168. this._resetIndexBufferBinding();
  13169. };
  13170. /**
  13171. * Updates a dynamic vertex buffer.
  13172. * @param vertexBuffer the vertex buffer to update
  13173. * @param data the data used to update the vertex buffer
  13174. * @param byteOffset the byte offset of the data
  13175. * @param byteLength the byte length of the data
  13176. */
  13177. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13178. this.bindArrayBuffer(vertexBuffer);
  13179. if (byteOffset === undefined) {
  13180. byteOffset = 0;
  13181. }
  13182. if (byteLength === undefined) {
  13183. if (data instanceof Array) {
  13184. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13185. }
  13186. else {
  13187. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13188. }
  13189. }
  13190. else {
  13191. if (data instanceof Array) {
  13192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13193. }
  13194. else {
  13195. if (data instanceof ArrayBuffer) {
  13196. data = new Uint8Array(data, byteOffset, byteLength);
  13197. }
  13198. else {
  13199. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13200. }
  13201. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13202. }
  13203. }
  13204. this._resetVertexBufferBinding();
  13205. };
  13206. Engine.prototype._resetIndexBufferBinding = function () {
  13207. this.bindIndexBuffer(null);
  13208. this._cachedIndexBuffer = null;
  13209. };
  13210. /**
  13211. * Creates a new index buffer
  13212. * @param indices defines the content of the index buffer
  13213. * @param updatable defines if the index buffer must be updatable
  13214. * @returns a new webGL buffer
  13215. */
  13216. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13217. var vbo = this._gl.createBuffer();
  13218. if (!vbo) {
  13219. throw new Error("Unable to create index buffer");
  13220. }
  13221. this.bindIndexBuffer(vbo);
  13222. // Check for 32 bits indices
  13223. var arrayBuffer;
  13224. var need32Bits = false;
  13225. if (indices instanceof Uint16Array) {
  13226. arrayBuffer = indices;
  13227. }
  13228. else {
  13229. //check 32 bit support
  13230. if (this._caps.uintIndices) {
  13231. if (indices instanceof Uint32Array) {
  13232. arrayBuffer = indices;
  13233. need32Bits = true;
  13234. }
  13235. else {
  13236. //number[] or Int32Array, check if 32 bit is necessary
  13237. for (var index = 0; index < indices.length; index++) {
  13238. if (indices[index] > 65535) {
  13239. need32Bits = true;
  13240. break;
  13241. }
  13242. }
  13243. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13244. }
  13245. }
  13246. else {
  13247. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13248. arrayBuffer = new Uint16Array(indices);
  13249. }
  13250. }
  13251. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13252. this._resetIndexBufferBinding();
  13253. vbo.references = 1;
  13254. vbo.is32Bits = need32Bits;
  13255. return vbo;
  13256. };
  13257. /**
  13258. * Bind a webGL buffer to the webGL context
  13259. * @param buffer defines the buffer to bind
  13260. */
  13261. Engine.prototype.bindArrayBuffer = function (buffer) {
  13262. if (!this._vaoRecordInProgress) {
  13263. this._unbindVertexArrayObject();
  13264. }
  13265. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13266. };
  13267. /**
  13268. * Bind an uniform buffer to the current webGL context
  13269. * @param buffer defines the buffer to bind
  13270. */
  13271. Engine.prototype.bindUniformBuffer = function (buffer) {
  13272. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13273. };
  13274. /**
  13275. * Bind a buffer to the current webGL context at a given location
  13276. * @param buffer defines the buffer to bind
  13277. * @param location defines the index where to bind the buffer
  13278. */
  13279. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13280. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13281. };
  13282. /**
  13283. * Bind a specific block at a given index in a specific shader program
  13284. * @param shaderProgram defines the shader program
  13285. * @param blockName defines the block name
  13286. * @param index defines the index where to bind the block
  13287. */
  13288. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13289. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13290. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13291. };
  13292. ;
  13293. Engine.prototype.bindIndexBuffer = function (buffer) {
  13294. if (!this._vaoRecordInProgress) {
  13295. this._unbindVertexArrayObject();
  13296. }
  13297. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13298. };
  13299. Engine.prototype.bindBuffer = function (buffer, target) {
  13300. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13301. this._gl.bindBuffer(target, buffer);
  13302. this._currentBoundBuffer[target] = buffer;
  13303. }
  13304. };
  13305. /**
  13306. * update the bound buffer with the given data
  13307. * @param data defines the data to update
  13308. */
  13309. Engine.prototype.updateArrayBuffer = function (data) {
  13310. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13311. };
  13312. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13313. var pointer = this._currentBufferPointers[indx];
  13314. var changed = false;
  13315. if (!pointer.active) {
  13316. changed = true;
  13317. pointer.active = true;
  13318. pointer.index = indx;
  13319. pointer.size = size;
  13320. pointer.type = type;
  13321. pointer.normalized = normalized;
  13322. pointer.stride = stride;
  13323. pointer.offset = offset;
  13324. pointer.buffer = buffer;
  13325. }
  13326. else {
  13327. if (pointer.buffer !== buffer) {
  13328. pointer.buffer = buffer;
  13329. changed = true;
  13330. }
  13331. if (pointer.size !== size) {
  13332. pointer.size = size;
  13333. changed = true;
  13334. }
  13335. if (pointer.type !== type) {
  13336. pointer.type = type;
  13337. changed = true;
  13338. }
  13339. if (pointer.normalized !== normalized) {
  13340. pointer.normalized = normalized;
  13341. changed = true;
  13342. }
  13343. if (pointer.stride !== stride) {
  13344. pointer.stride = stride;
  13345. changed = true;
  13346. }
  13347. if (pointer.offset !== offset) {
  13348. pointer.offset = offset;
  13349. changed = true;
  13350. }
  13351. }
  13352. if (changed || this._vaoRecordInProgress) {
  13353. this.bindArrayBuffer(buffer);
  13354. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13355. }
  13356. };
  13357. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13358. if (indexBuffer == null) {
  13359. return;
  13360. }
  13361. if (this._cachedIndexBuffer !== indexBuffer) {
  13362. this._cachedIndexBuffer = indexBuffer;
  13363. this.bindIndexBuffer(indexBuffer);
  13364. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13365. }
  13366. };
  13367. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13368. var attributes = effect.getAttributesNames();
  13369. if (!this._vaoRecordInProgress) {
  13370. this._unbindVertexArrayObject();
  13371. }
  13372. this.unbindAllAttributes();
  13373. for (var index = 0; index < attributes.length; index++) {
  13374. var order = effect.getAttributeLocation(index);
  13375. if (order >= 0) {
  13376. var vertexBuffer = vertexBuffers[attributes[index]];
  13377. if (!vertexBuffer) {
  13378. continue;
  13379. }
  13380. this._gl.enableVertexAttribArray(order);
  13381. if (!this._vaoRecordInProgress) {
  13382. this._vertexAttribArraysEnabled[order] = true;
  13383. }
  13384. var buffer = vertexBuffer.getBuffer();
  13385. if (buffer) {
  13386. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13387. if (vertexBuffer.getIsInstanced()) {
  13388. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13389. if (!this._vaoRecordInProgress) {
  13390. this._currentInstanceLocations.push(order);
  13391. this._currentInstanceBuffers.push(buffer);
  13392. }
  13393. }
  13394. }
  13395. }
  13396. }
  13397. };
  13398. /**
  13399. * Records a vertex array object
  13400. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13401. * @param vertexBuffers defines the list of vertex buffers to store
  13402. * @param indexBuffer defines the index buffer to store
  13403. * @param effect defines the effect to store
  13404. * @returns the new vertex array object
  13405. */
  13406. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13407. var vao = this._gl.createVertexArray();
  13408. this._vaoRecordInProgress = true;
  13409. this._gl.bindVertexArray(vao);
  13410. this._mustWipeVertexAttributes = true;
  13411. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13412. this.bindIndexBuffer(indexBuffer);
  13413. this._vaoRecordInProgress = false;
  13414. this._gl.bindVertexArray(null);
  13415. return vao;
  13416. };
  13417. /**
  13418. * Bind a specific vertex array object
  13419. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13420. * @param vertexArrayObject defines the vertex array object to bind
  13421. * @param indexBuffer defines the index buffer to bind
  13422. */
  13423. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13424. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13425. this._cachedVertexArrayObject = vertexArrayObject;
  13426. this._gl.bindVertexArray(vertexArrayObject);
  13427. this._cachedVertexBuffers = null;
  13428. this._cachedIndexBuffer = null;
  13429. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13430. this._mustWipeVertexAttributes = true;
  13431. }
  13432. };
  13433. /**
  13434. * Bind webGl buffers directly to the webGL context
  13435. * @param vertexBuffer defines the vertex buffer to bind
  13436. * @param indexBuffer defines the index buffer to bind
  13437. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13438. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13439. * @param effect defines the effect associated with the vertex buffer
  13440. */
  13441. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13442. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13443. this._cachedVertexBuffers = vertexBuffer;
  13444. this._cachedEffectForVertexBuffers = effect;
  13445. var attributesCount = effect.getAttributesCount();
  13446. this._unbindVertexArrayObject();
  13447. this.unbindAllAttributes();
  13448. var offset = 0;
  13449. for (var index = 0; index < attributesCount; index++) {
  13450. if (index < vertexDeclaration.length) {
  13451. var order = effect.getAttributeLocation(index);
  13452. if (order >= 0) {
  13453. this._gl.enableVertexAttribArray(order);
  13454. this._vertexAttribArraysEnabled[order] = true;
  13455. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13456. }
  13457. offset += vertexDeclaration[index] * 4;
  13458. }
  13459. }
  13460. }
  13461. this._bindIndexBufferWithCache(indexBuffer);
  13462. };
  13463. Engine.prototype._unbindVertexArrayObject = function () {
  13464. if (!this._cachedVertexArrayObject) {
  13465. return;
  13466. }
  13467. this._cachedVertexArrayObject = null;
  13468. this._gl.bindVertexArray(null);
  13469. };
  13470. /**
  13471. * Bind a list of vertex buffers to the webGL context
  13472. * @param vertexBuffers defines the list of vertex buffers to bind
  13473. * @param indexBuffer defines the index buffer to bind
  13474. * @param effect defines the effect associated with the vertex buffers
  13475. */
  13476. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13477. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13478. this._cachedVertexBuffers = vertexBuffers;
  13479. this._cachedEffectForVertexBuffers = effect;
  13480. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13481. }
  13482. this._bindIndexBufferWithCache(indexBuffer);
  13483. };
  13484. /**
  13485. * Unbind all instance attributes
  13486. */
  13487. Engine.prototype.unbindInstanceAttributes = function () {
  13488. var boundBuffer;
  13489. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13490. var instancesBuffer = this._currentInstanceBuffers[i];
  13491. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13492. boundBuffer = instancesBuffer;
  13493. this.bindArrayBuffer(instancesBuffer);
  13494. }
  13495. var offsetLocation = this._currentInstanceLocations[i];
  13496. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13497. }
  13498. this._currentInstanceBuffers.length = 0;
  13499. this._currentInstanceLocations.length = 0;
  13500. };
  13501. /**
  13502. * Release and free the memory of a vertex array object
  13503. * @param vao defines the vertex array object to delete
  13504. */
  13505. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13506. this._gl.deleteVertexArray(vao);
  13507. };
  13508. /** @hidden */
  13509. Engine.prototype._releaseBuffer = function (buffer) {
  13510. buffer.references--;
  13511. if (buffer.references === 0) {
  13512. this._gl.deleteBuffer(buffer);
  13513. return true;
  13514. }
  13515. return false;
  13516. };
  13517. /**
  13518. * Creates a webGL buffer to use with instanciation
  13519. * @param capacity defines the size of the buffer
  13520. * @returns the webGL buffer
  13521. */
  13522. Engine.prototype.createInstancesBuffer = function (capacity) {
  13523. var buffer = this._gl.createBuffer();
  13524. if (!buffer) {
  13525. throw new Error("Unable to create instance buffer");
  13526. }
  13527. buffer.capacity = capacity;
  13528. this.bindArrayBuffer(buffer);
  13529. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13530. return buffer;
  13531. };
  13532. /**
  13533. * Delete a webGL buffer used with instanciation
  13534. * @param buffer defines the webGL buffer to delete
  13535. */
  13536. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13537. this._gl.deleteBuffer(buffer);
  13538. };
  13539. /**
  13540. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13541. * @param instancesBuffer defines the webGL buffer to update and bind
  13542. * @param data defines the data to store in the buffer
  13543. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13544. */
  13545. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13546. this.bindArrayBuffer(instancesBuffer);
  13547. if (data) {
  13548. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13549. }
  13550. if (offsetLocations[0].index !== undefined) {
  13551. var stride = 0;
  13552. for (var i = 0; i < offsetLocations.length; i++) {
  13553. var ai = offsetLocations[i];
  13554. stride += ai.attributeSize * 4;
  13555. }
  13556. for (var i = 0; i < offsetLocations.length; i++) {
  13557. var ai = offsetLocations[i];
  13558. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13559. this._gl.enableVertexAttribArray(ai.index);
  13560. this._vertexAttribArraysEnabled[ai.index] = true;
  13561. }
  13562. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13563. this._gl.vertexAttribDivisor(ai.index, 1);
  13564. this._currentInstanceLocations.push(ai.index);
  13565. this._currentInstanceBuffers.push(instancesBuffer);
  13566. }
  13567. }
  13568. else {
  13569. for (var index = 0; index < 4; index++) {
  13570. var offsetLocation = offsetLocations[index];
  13571. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13572. this._gl.enableVertexAttribArray(offsetLocation);
  13573. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13574. }
  13575. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13576. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13577. this._currentInstanceLocations.push(offsetLocation);
  13578. this._currentInstanceBuffers.push(instancesBuffer);
  13579. }
  13580. }
  13581. };
  13582. /**
  13583. * Apply all cached states (depth, culling, stencil and alpha)
  13584. */
  13585. Engine.prototype.applyStates = function () {
  13586. this._depthCullingState.apply(this._gl);
  13587. this._stencilState.apply(this._gl);
  13588. this._alphaState.apply(this._gl);
  13589. };
  13590. /**
  13591. * Send a draw order
  13592. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13593. * @param indexStart defines the starting index
  13594. * @param indexCount defines the number of index to draw
  13595. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13596. */
  13597. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13598. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13599. };
  13600. /**
  13601. * Draw a list of points
  13602. * @param verticesStart defines the index of first vertex to draw
  13603. * @param verticesCount defines the count of vertices to draw
  13604. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13605. */
  13606. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13607. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13608. };
  13609. /**
  13610. * Draw a list of unindexed primitives
  13611. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13612. * @param verticesStart defines the index of first vertex to draw
  13613. * @param verticesCount defines the count of vertices to draw
  13614. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13615. */
  13616. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13617. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13618. };
  13619. /**
  13620. * Draw a list of indexed primitives
  13621. * @param fillMode defines the primitive to use
  13622. * @param indexStart defines the starting index
  13623. * @param indexCount defines the number of index to draw
  13624. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13625. */
  13626. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13627. // Apply states
  13628. this.applyStates();
  13629. this._drawCalls.addCount(1, false);
  13630. // Render
  13631. var drawMode = this._drawMode(fillMode);
  13632. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13633. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13634. if (instancesCount) {
  13635. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13636. }
  13637. else {
  13638. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13639. }
  13640. };
  13641. /**
  13642. * Draw a list of unindexed primitives
  13643. * @param fillMode defines the primitive to use
  13644. * @param verticesStart defines the index of first vertex to draw
  13645. * @param verticesCount defines the count of vertices to draw
  13646. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13647. */
  13648. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13649. // Apply states
  13650. this.applyStates();
  13651. this._drawCalls.addCount(1, false);
  13652. var drawMode = this._drawMode(fillMode);
  13653. if (instancesCount) {
  13654. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13655. }
  13656. else {
  13657. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13658. }
  13659. };
  13660. Engine.prototype._drawMode = function (fillMode) {
  13661. switch (fillMode) {
  13662. // Triangle views
  13663. case BABYLON.Material.TriangleFillMode:
  13664. return this._gl.TRIANGLES;
  13665. case BABYLON.Material.PointFillMode:
  13666. return this._gl.POINTS;
  13667. case BABYLON.Material.WireFrameFillMode:
  13668. return this._gl.LINES;
  13669. // Draw modes
  13670. case BABYLON.Material.PointListDrawMode:
  13671. return this._gl.POINTS;
  13672. case BABYLON.Material.LineListDrawMode:
  13673. return this._gl.LINES;
  13674. case BABYLON.Material.LineLoopDrawMode:
  13675. return this._gl.LINE_LOOP;
  13676. case BABYLON.Material.LineStripDrawMode:
  13677. return this._gl.LINE_STRIP;
  13678. case BABYLON.Material.TriangleStripDrawMode:
  13679. return this._gl.TRIANGLE_STRIP;
  13680. case BABYLON.Material.TriangleFanDrawMode:
  13681. return this._gl.TRIANGLE_FAN;
  13682. default:
  13683. return this._gl.TRIANGLES;
  13684. }
  13685. };
  13686. // Shaders
  13687. /** @hidden */
  13688. Engine.prototype._releaseEffect = function (effect) {
  13689. if (this._compiledEffects[effect._key]) {
  13690. delete this._compiledEffects[effect._key];
  13691. this._deleteProgram(effect.getProgram());
  13692. }
  13693. };
  13694. /** @hidden */
  13695. Engine.prototype._deleteProgram = function (program) {
  13696. if (program) {
  13697. program.__SPECTOR_rebuildProgram = null;
  13698. if (program.transformFeedback) {
  13699. this.deleteTransformFeedback(program.transformFeedback);
  13700. program.transformFeedback = null;
  13701. }
  13702. this._gl.deleteProgram(program);
  13703. }
  13704. };
  13705. /**
  13706. * Create a new effect (used to store vertex/fragment shaders)
  13707. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13708. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13709. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13710. * @param samplers defines an array of string used to represent textures
  13711. * @param defines defines the string containing the defines to use to compile the shaders
  13712. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13713. * @param onCompiled defines a function to call when the effect creation is successful
  13714. * @param onError defines a function to call when the effect creation has failed
  13715. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13716. * @returns the new Effect
  13717. */
  13718. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13719. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13720. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13721. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13722. if (this._compiledEffects[name]) {
  13723. var compiledEffect = this._compiledEffects[name];
  13724. if (onCompiled && compiledEffect.isReady()) {
  13725. onCompiled(compiledEffect);
  13726. }
  13727. return compiledEffect;
  13728. }
  13729. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13730. effect._key = name;
  13731. this._compiledEffects[name] = effect;
  13732. return effect;
  13733. };
  13734. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13735. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13736. };
  13737. ;
  13738. Engine.prototype._compileRawShader = function (source, type) {
  13739. var gl = this._gl;
  13740. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13741. gl.shaderSource(shader, source);
  13742. gl.compileShader(shader);
  13743. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13744. var log = gl.getShaderInfoLog(shader);
  13745. if (log) {
  13746. throw new Error(log);
  13747. }
  13748. }
  13749. if (!shader) {
  13750. throw new Error("Something went wrong while compile the shader.");
  13751. }
  13752. return shader;
  13753. };
  13754. ;
  13755. /**
  13756. * Directly creates a webGL program
  13757. * @param vertexCode defines the vertex shader code to use
  13758. * @param fragmentCode defines the fragment shader code to use
  13759. * @param context defines the webGL context to use (if not set, the current one will be used)
  13760. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13761. * @returns the new webGL program
  13762. */
  13763. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13764. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13765. context = context || this._gl;
  13766. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13767. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13768. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13769. };
  13770. /**
  13771. * Creates a webGL program
  13772. * @param vertexCode defines the vertex shader code to use
  13773. * @param fragmentCode defines the fragment shader code to use
  13774. * @param defines defines the string containing the defines to use to compile the shaders
  13775. * @param context defines the webGL context to use (if not set, the current one will be used)
  13776. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13777. * @returns the new webGL program
  13778. */
  13779. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13780. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13781. context = context || this._gl;
  13782. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13783. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13784. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13785. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13786. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13787. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13788. return program;
  13789. };
  13790. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13791. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13792. var shaderProgram = context.createProgram();
  13793. if (!shaderProgram) {
  13794. throw new Error("Unable to create program");
  13795. }
  13796. context.attachShader(shaderProgram, vertexShader);
  13797. context.attachShader(shaderProgram, fragmentShader);
  13798. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13799. var transformFeedback = this.createTransformFeedback();
  13800. this.bindTransformFeedback(transformFeedback);
  13801. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13802. shaderProgram.transformFeedback = transformFeedback;
  13803. }
  13804. context.linkProgram(shaderProgram);
  13805. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13806. this.bindTransformFeedback(null);
  13807. }
  13808. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13809. if (!linked) {
  13810. var error = context.getProgramInfoLog(shaderProgram);
  13811. if (error) {
  13812. throw new Error(error);
  13813. }
  13814. }
  13815. if (this.validateShaderPrograms) {
  13816. context.validateProgram(shaderProgram);
  13817. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13818. if (!validated) {
  13819. var error = context.getProgramInfoLog(shaderProgram);
  13820. if (error) {
  13821. throw new Error(error);
  13822. }
  13823. }
  13824. }
  13825. context.deleteShader(vertexShader);
  13826. context.deleteShader(fragmentShader);
  13827. return shaderProgram;
  13828. };
  13829. /**
  13830. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13831. * @param shaderProgram defines the webGL program to use
  13832. * @param uniformsNames defines the list of uniform names
  13833. * @returns an array of webGL uniform locations
  13834. */
  13835. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13836. var results = new Array();
  13837. for (var index = 0; index < uniformsNames.length; index++) {
  13838. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13839. }
  13840. return results;
  13841. };
  13842. /**
  13843. * Gets the lsit of active attributes for a given webGL program
  13844. * @param shaderProgram defines the webGL program to use
  13845. * @param attributesNames defines the list of attribute names to get
  13846. * @returns an array of indices indicating the offset of each attribute
  13847. */
  13848. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13849. var results = [];
  13850. for (var index = 0; index < attributesNames.length; index++) {
  13851. try {
  13852. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13853. }
  13854. catch (e) {
  13855. results.push(-1);
  13856. }
  13857. }
  13858. return results;
  13859. };
  13860. /**
  13861. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13862. * @param effect defines the effect to activate
  13863. */
  13864. Engine.prototype.enableEffect = function (effect) {
  13865. if (!effect || effect === this._currentEffect) {
  13866. return;
  13867. }
  13868. // Use program
  13869. this.bindSamplers(effect);
  13870. this._currentEffect = effect;
  13871. if (effect.onBind) {
  13872. effect.onBind(effect);
  13873. }
  13874. if (effect._onBindObservable) {
  13875. effect._onBindObservable.notifyObservers(effect);
  13876. }
  13877. };
  13878. /**
  13879. * Set the value of an uniform to an array of int32
  13880. * @param uniform defines the webGL uniform location where to store the value
  13881. * @param array defines the array of int32 to store
  13882. */
  13883. Engine.prototype.setIntArray = function (uniform, array) {
  13884. if (!uniform)
  13885. return;
  13886. this._gl.uniform1iv(uniform, array);
  13887. };
  13888. /**
  13889. * Set the value of an uniform to an array of int32 (stored as vec2)
  13890. * @param uniform defines the webGL uniform location where to store the value
  13891. * @param array defines the array of int32 to store
  13892. */
  13893. Engine.prototype.setIntArray2 = function (uniform, array) {
  13894. if (!uniform || array.length % 2 !== 0)
  13895. return;
  13896. this._gl.uniform2iv(uniform, array);
  13897. };
  13898. /**
  13899. * Set the value of an uniform to an array of int32 (stored as vec3)
  13900. * @param uniform defines the webGL uniform location where to store the value
  13901. * @param array defines the array of int32 to store
  13902. */
  13903. Engine.prototype.setIntArray3 = function (uniform, array) {
  13904. if (!uniform || array.length % 3 !== 0)
  13905. return;
  13906. this._gl.uniform3iv(uniform, array);
  13907. };
  13908. /**
  13909. * Set the value of an uniform to an array of int32 (stored as vec4)
  13910. * @param uniform defines the webGL uniform location where to store the value
  13911. * @param array defines the array of int32 to store
  13912. */
  13913. Engine.prototype.setIntArray4 = function (uniform, array) {
  13914. if (!uniform || array.length % 4 !== 0)
  13915. return;
  13916. this._gl.uniform4iv(uniform, array);
  13917. };
  13918. /**
  13919. * Set the value of an uniform to an array of float32
  13920. * @param uniform defines the webGL uniform location where to store the value
  13921. * @param array defines the array of float32 to store
  13922. */
  13923. Engine.prototype.setFloatArray = function (uniform, array) {
  13924. if (!uniform)
  13925. return;
  13926. this._gl.uniform1fv(uniform, array);
  13927. };
  13928. /**
  13929. * Set the value of an uniform to an array of float32 (stored as vec2)
  13930. * @param uniform defines the webGL uniform location where to store the value
  13931. * @param array defines the array of float32 to store
  13932. */
  13933. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13934. if (!uniform || array.length % 2 !== 0)
  13935. return;
  13936. this._gl.uniform2fv(uniform, array);
  13937. };
  13938. /**
  13939. * Set the value of an uniform to an array of float32 (stored as vec3)
  13940. * @param uniform defines the webGL uniform location where to store the value
  13941. * @param array defines the array of float32 to store
  13942. */
  13943. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13944. if (!uniform || array.length % 3 !== 0)
  13945. return;
  13946. this._gl.uniform3fv(uniform, array);
  13947. };
  13948. /**
  13949. * Set the value of an uniform to an array of float32 (stored as vec4)
  13950. * @param uniform defines the webGL uniform location where to store the value
  13951. * @param array defines the array of float32 to store
  13952. */
  13953. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13954. if (!uniform || array.length % 4 !== 0)
  13955. return;
  13956. this._gl.uniform4fv(uniform, array);
  13957. };
  13958. /**
  13959. * Set the value of an uniform to an array of number
  13960. * @param uniform defines the webGL uniform location where to store the value
  13961. * @param array defines the array of number to store
  13962. */
  13963. Engine.prototype.setArray = function (uniform, array) {
  13964. if (!uniform)
  13965. return;
  13966. this._gl.uniform1fv(uniform, array);
  13967. };
  13968. /**
  13969. * Set the value of an uniform to an array of number (stored as vec2)
  13970. * @param uniform defines the webGL uniform location where to store the value
  13971. * @param array defines the array of number to store
  13972. */
  13973. Engine.prototype.setArray2 = function (uniform, array) {
  13974. if (!uniform || array.length % 2 !== 0)
  13975. return;
  13976. this._gl.uniform2fv(uniform, array);
  13977. };
  13978. /**
  13979. * Set the value of an uniform to an array of number (stored as vec3)
  13980. * @param uniform defines the webGL uniform location where to store the value
  13981. * @param array defines the array of number to store
  13982. */
  13983. Engine.prototype.setArray3 = function (uniform, array) {
  13984. if (!uniform || array.length % 3 !== 0)
  13985. return;
  13986. this._gl.uniform3fv(uniform, array);
  13987. };
  13988. /**
  13989. * Set the value of an uniform to an array of number (stored as vec4)
  13990. * @param uniform defines the webGL uniform location where to store the value
  13991. * @param array defines the array of number to store
  13992. */
  13993. Engine.prototype.setArray4 = function (uniform, array) {
  13994. if (!uniform || array.length % 4 !== 0)
  13995. return;
  13996. this._gl.uniform4fv(uniform, array);
  13997. };
  13998. /**
  13999. * Set the value of an uniform to an array of float32 (stored as matrices)
  14000. * @param uniform defines the webGL uniform location where to store the value
  14001. * @param matrices defines the array of float32 to store
  14002. */
  14003. Engine.prototype.setMatrices = function (uniform, matrices) {
  14004. if (!uniform)
  14005. return;
  14006. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14007. };
  14008. /**
  14009. * Set the value of an uniform to a matrix
  14010. * @param uniform defines the webGL uniform location where to store the value
  14011. * @param matrix defines the matrix to store
  14012. */
  14013. Engine.prototype.setMatrix = function (uniform, matrix) {
  14014. if (!uniform)
  14015. return;
  14016. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14017. };
  14018. /**
  14019. * Set the value of an uniform to a matrix (3x3)
  14020. * @param uniform defines the webGL uniform location where to store the value
  14021. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14022. */
  14023. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14024. if (!uniform)
  14025. return;
  14026. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14027. };
  14028. /**
  14029. * Set the value of an uniform to a matrix (2x2)
  14030. * @param uniform defines the webGL uniform location where to store the value
  14031. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14032. */
  14033. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14034. if (!uniform)
  14035. return;
  14036. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14037. };
  14038. /**
  14039. * Set the value of an uniform to a number (int)
  14040. * @param uniform defines the webGL uniform location where to store the value
  14041. * @param value defines the int number to store
  14042. */
  14043. Engine.prototype.setInt = function (uniform, value) {
  14044. if (!uniform)
  14045. return;
  14046. this._gl.uniform1i(uniform, value);
  14047. };
  14048. /**
  14049. * Set the value of an uniform to a number (float)
  14050. * @param uniform defines the webGL uniform location where to store the value
  14051. * @param value defines the float number to store
  14052. */
  14053. Engine.prototype.setFloat = function (uniform, value) {
  14054. if (!uniform)
  14055. return;
  14056. this._gl.uniform1f(uniform, value);
  14057. };
  14058. /**
  14059. * Set the value of an uniform to a vec2
  14060. * @param uniform defines the webGL uniform location where to store the value
  14061. * @param x defines the 1st component of the value
  14062. * @param y defines the 2nd component of the value
  14063. */
  14064. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14065. if (!uniform)
  14066. return;
  14067. this._gl.uniform2f(uniform, x, y);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to a vec3
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param x defines the 1st component of the value
  14073. * @param y defines the 2nd component of the value
  14074. * @param z defines the 3rd component of the value
  14075. */
  14076. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14077. if (!uniform)
  14078. return;
  14079. this._gl.uniform3f(uniform, x, y, z);
  14080. };
  14081. /**
  14082. * Set the value of an uniform to a boolean
  14083. * @param uniform defines the webGL uniform location where to store the value
  14084. * @param bool defines the boolean to store
  14085. */
  14086. Engine.prototype.setBool = function (uniform, bool) {
  14087. if (!uniform)
  14088. return;
  14089. this._gl.uniform1i(uniform, bool);
  14090. };
  14091. /**
  14092. * Set the value of an uniform to a vec4
  14093. * @param uniform defines the webGL uniform location where to store the value
  14094. * @param x defines the 1st component of the value
  14095. * @param y defines the 2nd component of the value
  14096. * @param z defines the 3rd component of the value
  14097. * @param w defines the 4th component of the value
  14098. */
  14099. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14100. if (!uniform)
  14101. return;
  14102. this._gl.uniform4f(uniform, x, y, z, w);
  14103. };
  14104. /**
  14105. * Set the value of an uniform to a Color3
  14106. * @param uniform defines the webGL uniform location where to store the value
  14107. * @param color3 defines the color to store
  14108. */
  14109. Engine.prototype.setColor3 = function (uniform, color3) {
  14110. if (!uniform)
  14111. return;
  14112. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14113. };
  14114. /**
  14115. * Set the value of an uniform to a Color3 and an alpha value
  14116. * @param uniform defines the webGL uniform location where to store the value
  14117. * @param color3 defines the color to store
  14118. * @param alpha defines the alpha component to store
  14119. */
  14120. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14121. if (!uniform)
  14122. return;
  14123. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14124. };
  14125. /**
  14126. * Sets a Color4 on a uniform variable
  14127. * @param uniform defines the uniform location
  14128. * @param color4 defines the value to be set
  14129. */
  14130. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14131. if (!uniform)
  14132. return;
  14133. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14134. };
  14135. // States
  14136. /**
  14137. * Set various states to the webGL context
  14138. * @param culling defines backface culling state
  14139. * @param zOffset defines the value to apply to zOffset (0 by default)
  14140. * @param force defines if states must be applied even if cache is up to date
  14141. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14142. */
  14143. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14144. if (zOffset === void 0) { zOffset = 0; }
  14145. if (reverseSide === void 0) { reverseSide = false; }
  14146. // Culling
  14147. if (this._depthCullingState.cull !== culling || force) {
  14148. this._depthCullingState.cull = culling;
  14149. }
  14150. // Cull face
  14151. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14152. if (this._depthCullingState.cullFace !== cullFace || force) {
  14153. this._depthCullingState.cullFace = cullFace;
  14154. }
  14155. // Z offset
  14156. this.setZOffset(zOffset);
  14157. // Front face
  14158. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14159. if (this._depthCullingState.frontFace !== frontFace || force) {
  14160. this._depthCullingState.frontFace = frontFace;
  14161. }
  14162. };
  14163. /**
  14164. * Set the z offset to apply to current rendering
  14165. * @param value defines the offset to apply
  14166. */
  14167. Engine.prototype.setZOffset = function (value) {
  14168. this._depthCullingState.zOffset = value;
  14169. };
  14170. /**
  14171. * Gets the current value of the zOffset
  14172. * @returns the current zOffset state
  14173. */
  14174. Engine.prototype.getZOffset = function () {
  14175. return this._depthCullingState.zOffset;
  14176. };
  14177. /**
  14178. * Enable or disable depth buffering
  14179. * @param enable defines the state to set
  14180. */
  14181. Engine.prototype.setDepthBuffer = function (enable) {
  14182. this._depthCullingState.depthTest = enable;
  14183. };
  14184. /**
  14185. * Gets a boolean indicating if depth writing is enabled
  14186. * @returns the current depth writing state
  14187. */
  14188. Engine.prototype.getDepthWrite = function () {
  14189. return this._depthCullingState.depthMask;
  14190. };
  14191. /**
  14192. * Enable or disable depth writing
  14193. * @param enable defines the state to set
  14194. */
  14195. Engine.prototype.setDepthWrite = function (enable) {
  14196. this._depthCullingState.depthMask = enable;
  14197. };
  14198. /**
  14199. * Enable or disable color writing
  14200. * @param enable defines the state to set
  14201. */
  14202. Engine.prototype.setColorWrite = function (enable) {
  14203. this._gl.colorMask(enable, enable, enable, enable);
  14204. this._colorWrite = enable;
  14205. };
  14206. /**
  14207. * Gets a boolean indicating if color writing is enabled
  14208. * @returns the current color writing state
  14209. */
  14210. Engine.prototype.getColorWrite = function () {
  14211. return this._colorWrite;
  14212. };
  14213. /**
  14214. * Sets alpha constants used by some alpha blending modes
  14215. * @param r defines the red component
  14216. * @param g defines the green component
  14217. * @param b defines the blue component
  14218. * @param a defines the alpha component
  14219. */
  14220. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14221. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14222. };
  14223. /**
  14224. * Sets the current alpha mode
  14225. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14226. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14227. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14228. */
  14229. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14230. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14231. if (this._alphaMode === mode) {
  14232. return;
  14233. }
  14234. switch (mode) {
  14235. case Engine.ALPHA_DISABLE:
  14236. this._alphaState.alphaBlend = false;
  14237. break;
  14238. case Engine.ALPHA_PREMULTIPLIED:
  14239. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14240. this._alphaState.alphaBlend = true;
  14241. break;
  14242. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14243. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14244. this._alphaState.alphaBlend = true;
  14245. break;
  14246. case Engine.ALPHA_COMBINE:
  14247. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14248. this._alphaState.alphaBlend = true;
  14249. break;
  14250. case Engine.ALPHA_ONEONE:
  14251. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14252. this._alphaState.alphaBlend = true;
  14253. break;
  14254. case Engine.ALPHA_ADD:
  14255. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14256. this._alphaState.alphaBlend = true;
  14257. break;
  14258. case Engine.ALPHA_SUBTRACT:
  14259. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14260. this._alphaState.alphaBlend = true;
  14261. break;
  14262. case Engine.ALPHA_MULTIPLY:
  14263. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14264. this._alphaState.alphaBlend = true;
  14265. break;
  14266. case Engine.ALPHA_MAXIMIZED:
  14267. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14268. this._alphaState.alphaBlend = true;
  14269. break;
  14270. case Engine.ALPHA_INTERPOLATE:
  14271. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14272. this._alphaState.alphaBlend = true;
  14273. break;
  14274. case Engine.ALPHA_SCREENMODE:
  14275. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14276. this._alphaState.alphaBlend = true;
  14277. break;
  14278. }
  14279. if (!noDepthWriteChange) {
  14280. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14281. }
  14282. this._alphaMode = mode;
  14283. };
  14284. /**
  14285. * Gets the current alpha mode
  14286. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14287. * @returns the current alpha mode
  14288. */
  14289. Engine.prototype.getAlphaMode = function () {
  14290. return this._alphaMode;
  14291. };
  14292. // Textures
  14293. /**
  14294. * Clears the list of texture accessible through engine.
  14295. * This can help preventing texture load conflict due to name collision.
  14296. */
  14297. Engine.prototype.clearInternalTexturesCache = function () {
  14298. this._internalTexturesCache = [];
  14299. };
  14300. /**
  14301. * Force the entire cache to be cleared
  14302. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14303. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14304. */
  14305. Engine.prototype.wipeCaches = function (bruteForce) {
  14306. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14307. return;
  14308. }
  14309. this._currentEffect = null;
  14310. this._viewportCached.x = 0;
  14311. this._viewportCached.y = 0;
  14312. this._viewportCached.z = 0;
  14313. this._viewportCached.w = 0;
  14314. if (bruteForce) {
  14315. this.resetTextureCache();
  14316. this._currentProgram = null;
  14317. this._stencilState.reset();
  14318. this._depthCullingState.reset();
  14319. this.setDepthFunctionToLessOrEqual();
  14320. this._alphaState.reset();
  14321. this._unpackFlipYCached = null;
  14322. }
  14323. this._resetVertexBufferBinding();
  14324. this._cachedIndexBuffer = null;
  14325. this._cachedEffectForVertexBuffers = null;
  14326. this._unbindVertexArrayObject();
  14327. this.bindIndexBuffer(null);
  14328. };
  14329. /**
  14330. * Set the compressed texture format to use, based on the formats you have, and the formats
  14331. * supported by the hardware / browser.
  14332. *
  14333. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14334. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14335. * to API arguments needed to compressed textures. This puts the burden on the container
  14336. * generator to house the arcane code for determining these for current & future formats.
  14337. *
  14338. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14339. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14340. *
  14341. * Note: The result of this call is not taken into account when a texture is base64.
  14342. *
  14343. * @param formatsAvailable defines the list of those format families you have created
  14344. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14345. *
  14346. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14347. * @returns The extension selected.
  14348. */
  14349. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14350. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14351. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14352. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14353. return this._textureFormatInUse = this._texturesSupported[i];
  14354. }
  14355. }
  14356. }
  14357. // actively set format to nothing, to allow this to be called more than once
  14358. // and possibly fail the 2nd time
  14359. this._textureFormatInUse = null;
  14360. return null;
  14361. };
  14362. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14363. var gl = this._gl;
  14364. var magFilter = gl.NEAREST;
  14365. var minFilter = gl.NEAREST;
  14366. switch (samplingMode) {
  14367. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14368. magFilter = gl.LINEAR;
  14369. if (generateMipMaps) {
  14370. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14371. }
  14372. else {
  14373. minFilter = gl.LINEAR;
  14374. }
  14375. break;
  14376. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14377. magFilter = gl.LINEAR;
  14378. if (generateMipMaps) {
  14379. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14380. }
  14381. else {
  14382. minFilter = gl.LINEAR;
  14383. }
  14384. break;
  14385. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14386. magFilter = gl.NEAREST;
  14387. if (generateMipMaps) {
  14388. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14389. }
  14390. else {
  14391. minFilter = gl.NEAREST;
  14392. }
  14393. break;
  14394. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14395. magFilter = gl.NEAREST;
  14396. if (generateMipMaps) {
  14397. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14398. }
  14399. else {
  14400. minFilter = gl.NEAREST;
  14401. }
  14402. break;
  14403. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14404. magFilter = gl.NEAREST;
  14405. if (generateMipMaps) {
  14406. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14407. }
  14408. else {
  14409. minFilter = gl.LINEAR;
  14410. }
  14411. break;
  14412. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14413. magFilter = gl.NEAREST;
  14414. if (generateMipMaps) {
  14415. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14416. }
  14417. else {
  14418. minFilter = gl.LINEAR;
  14419. }
  14420. break;
  14421. case Engine.TEXTURE_NEAREST_LINEAR:
  14422. magFilter = gl.NEAREST;
  14423. minFilter = gl.LINEAR;
  14424. break;
  14425. case Engine.TEXTURE_NEAREST_NEAREST:
  14426. magFilter = gl.NEAREST;
  14427. minFilter = gl.NEAREST;
  14428. break;
  14429. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14430. magFilter = gl.LINEAR;
  14431. if (generateMipMaps) {
  14432. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14433. }
  14434. else {
  14435. minFilter = gl.NEAREST;
  14436. }
  14437. break;
  14438. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14439. magFilter = gl.LINEAR;
  14440. if (generateMipMaps) {
  14441. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14442. }
  14443. else {
  14444. minFilter = gl.NEAREST;
  14445. }
  14446. break;
  14447. case Engine.TEXTURE_LINEAR_LINEAR:
  14448. magFilter = gl.LINEAR;
  14449. minFilter = gl.LINEAR;
  14450. break;
  14451. case Engine.TEXTURE_LINEAR_NEAREST:
  14452. magFilter = gl.LINEAR;
  14453. minFilter = gl.NEAREST;
  14454. break;
  14455. }
  14456. return {
  14457. min: minFilter,
  14458. mag: magFilter
  14459. };
  14460. };
  14461. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14462. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14463. var img;
  14464. var onload = function () {
  14465. loadedImages[index] = img;
  14466. loadedImages._internalCount++;
  14467. if (scene) {
  14468. scene._removePendingData(img);
  14469. }
  14470. if (loadedImages._internalCount === 6) {
  14471. onfinish(loadedImages);
  14472. }
  14473. };
  14474. var onerror = function (message, exception) {
  14475. if (scene) {
  14476. scene._removePendingData(img);
  14477. }
  14478. if (onErrorCallBack) {
  14479. onErrorCallBack(message, exception);
  14480. }
  14481. };
  14482. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14483. if (scene) {
  14484. scene._addPendingData(img);
  14485. }
  14486. };
  14487. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14488. if (onError === void 0) { onError = null; }
  14489. var loadedImages = [];
  14490. loadedImages._internalCount = 0;
  14491. for (var index = 0; index < 6; index++) {
  14492. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14493. }
  14494. };
  14495. ;
  14496. /** @hidden */
  14497. Engine.prototype._createTexture = function () {
  14498. var texture = this._gl.createTexture();
  14499. if (!texture) {
  14500. throw new Error("Unable to create texture");
  14501. }
  14502. return texture;
  14503. };
  14504. /**
  14505. * Usually called from BABYLON.Texture.ts.
  14506. * Passed information to create a WebGLTexture
  14507. * @param urlArg defines a value which contains one of the following:
  14508. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14509. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14510. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14511. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14512. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14513. * @param scene needed for loading to the correct scene
  14514. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14515. * @param onLoad optional callback to be called upon successful completion
  14516. * @param onError optional callback to be called upon failure
  14517. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14518. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14519. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14520. * @param forcedExtension defines the extension to use to pick the right loader
  14521. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14522. */
  14523. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14524. var _this = this;
  14525. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14526. if (onLoad === void 0) { onLoad = null; }
  14527. if (onError === void 0) { onError = null; }
  14528. if (buffer === void 0) { buffer = null; }
  14529. if (fallback === void 0) { fallback = null; }
  14530. if (format === void 0) { format = null; }
  14531. if (forcedExtension === void 0) { forcedExtension = null; }
  14532. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14533. var fromData = url.substr(0, 5) === "data:";
  14534. var fromBlob = url.substr(0, 5) === "blob:";
  14535. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14536. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14537. // establish the file extension, if possible
  14538. var lastDot = url.lastIndexOf('.');
  14539. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14540. var loader = null;
  14541. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14542. var availableLoader = _a[_i];
  14543. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14544. loader = availableLoader;
  14545. break;
  14546. }
  14547. }
  14548. if (loader) {
  14549. url = loader.transformUrl(url, this._textureFormatInUse);
  14550. }
  14551. if (scene) {
  14552. scene._addPendingData(texture);
  14553. }
  14554. texture.url = url;
  14555. texture.generateMipMaps = !noMipmap;
  14556. texture.samplingMode = samplingMode;
  14557. texture.invertY = invertY;
  14558. if (!this._doNotHandleContextLost) {
  14559. // Keep a link to the buffer only if we plan to handle context lost
  14560. texture._buffer = buffer;
  14561. }
  14562. var onLoadObserver = null;
  14563. if (onLoad && !fallback) {
  14564. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14565. }
  14566. if (!fallback)
  14567. this._internalTexturesCache.push(texture);
  14568. var onInternalError = function (message, exception) {
  14569. if (scene) {
  14570. scene._removePendingData(texture);
  14571. }
  14572. var customFallback = false;
  14573. if (loader) {
  14574. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14575. if (fallbackUrl) {
  14576. // Add Back
  14577. customFallback = true;
  14578. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14579. }
  14580. }
  14581. if (!customFallback) {
  14582. if (onLoadObserver) {
  14583. texture.onLoadedObservable.remove(onLoadObserver);
  14584. }
  14585. if (BABYLON.Tools.UseFallbackTexture) {
  14586. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14587. }
  14588. }
  14589. if (onError) {
  14590. onError(message || "Unknown error", exception);
  14591. }
  14592. };
  14593. // processing for non-image formats
  14594. if (loader) {
  14595. var callback = function (data) {
  14596. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14597. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14598. done();
  14599. return false;
  14600. }, samplingMode);
  14601. });
  14602. };
  14603. if (!buffer) {
  14604. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14605. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14606. });
  14607. }
  14608. else {
  14609. callback(buffer);
  14610. }
  14611. }
  14612. else {
  14613. var onload = function (img) {
  14614. if (fromBlob && !_this._doNotHandleContextLost) {
  14615. // We need to store the image if we need to rebuild the texture
  14616. // in case of a webgl context lost
  14617. texture._buffer = img;
  14618. }
  14619. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14620. var gl = _this._gl;
  14621. var isPot = (img.width === potWidth && img.height === potHeight);
  14622. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14623. if (isPot) {
  14624. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14625. return false;
  14626. }
  14627. var maxTextureSize = _this._caps.maxTextureSize;
  14628. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14629. _this._prepareWorkingCanvas();
  14630. if (!_this._workingCanvas || !_this._workingContext) {
  14631. return false;
  14632. }
  14633. _this._workingCanvas.width = potWidth;
  14634. _this._workingCanvas.height = potHeight;
  14635. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14636. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14637. texture.width = potWidth;
  14638. texture.height = potHeight;
  14639. return false;
  14640. }
  14641. else {
  14642. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14643. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14644. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14645. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14649. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14650. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14651. _this._releaseTexture(source_1);
  14652. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14653. continuationCallback();
  14654. });
  14655. }
  14656. return true;
  14657. }, samplingMode);
  14658. };
  14659. if (!fromData || isBase64) {
  14660. if (buffer instanceof HTMLImageElement) {
  14661. onload(buffer);
  14662. }
  14663. else {
  14664. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14665. }
  14666. }
  14667. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14668. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14669. }
  14670. else {
  14671. onload(buffer);
  14672. }
  14673. }
  14674. return texture;
  14675. };
  14676. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14677. var _this = this;
  14678. var rtt = this.createRenderTargetTexture({
  14679. width: destination.width,
  14680. height: destination.height,
  14681. }, {
  14682. generateMipMaps: false,
  14683. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14684. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14685. generateDepthBuffer: false,
  14686. generateStencilBuffer: false
  14687. });
  14688. if (!this._rescalePostProcess) {
  14689. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14690. }
  14691. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14692. _this._rescalePostProcess.onApply = function (effect) {
  14693. effect._bindTexture("textureSampler", source);
  14694. };
  14695. var hostingScene = scene;
  14696. if (!hostingScene) {
  14697. hostingScene = _this.scenes[_this.scenes.length - 1];
  14698. }
  14699. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14700. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14701. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14702. _this.unBindFramebuffer(rtt);
  14703. _this._releaseTexture(rtt);
  14704. if (onComplete) {
  14705. onComplete();
  14706. }
  14707. });
  14708. };
  14709. /**
  14710. * Update a raw texture
  14711. * @param texture defines the texture to update
  14712. * @param data defines the data to store in the texture
  14713. * @param format defines the format of the data
  14714. * @param invertY defines if data must be stored with Y axis inverted
  14715. * @param compression defines the compression used (null by default)
  14716. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14717. */
  14718. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14719. if (compression === void 0) { compression = null; }
  14720. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14721. if (!texture) {
  14722. return;
  14723. }
  14724. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14725. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14726. // babylon's internalFormat but gl's texImage2D format
  14727. var internalFormat = this._getInternalFormat(format);
  14728. var textureType = this._getWebGLTextureType(type);
  14729. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14730. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14731. if (!this._doNotHandleContextLost) {
  14732. texture._bufferView = data;
  14733. texture.format = format;
  14734. texture.type = type;
  14735. texture.invertY = invertY;
  14736. texture._compression = compression;
  14737. }
  14738. if (texture.width % 4 !== 0) {
  14739. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14740. }
  14741. if (compression && data) {
  14742. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14743. }
  14744. else {
  14745. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14746. }
  14747. if (texture.generateMipMaps) {
  14748. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14749. }
  14750. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14751. // this.resetTextureCache();
  14752. texture.isReady = true;
  14753. };
  14754. /**
  14755. * Creates a raw texture
  14756. * @param data defines the data to store in the texture
  14757. * @param width defines the width of the texture
  14758. * @param height defines the height of the texture
  14759. * @param format defines the format of the data
  14760. * @param generateMipMaps defines if the engine should generate the mip levels
  14761. * @param invertY defines if data must be stored with Y axis inverted
  14762. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14763. * @param compression defines the compression used (null by default)
  14764. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14765. * @returns the raw texture inside an InternalTexture
  14766. */
  14767. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14768. if (compression === void 0) { compression = null; }
  14769. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14770. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14771. texture.baseWidth = width;
  14772. texture.baseHeight = height;
  14773. texture.width = width;
  14774. texture.height = height;
  14775. texture.format = format;
  14776. texture.generateMipMaps = generateMipMaps;
  14777. texture.samplingMode = samplingMode;
  14778. texture.invertY = invertY;
  14779. texture._compression = compression;
  14780. texture.type = type;
  14781. if (!this._doNotHandleContextLost) {
  14782. texture._bufferView = data;
  14783. }
  14784. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14785. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14786. // Filters
  14787. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14788. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14789. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14790. if (generateMipMaps) {
  14791. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14792. }
  14793. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14794. this._internalTexturesCache.push(texture);
  14795. return texture;
  14796. };
  14797. /** @hidden */
  14798. Engine.prototype._unpackFlipY = function (value) {
  14799. if (this._unpackFlipYCached !== value) {
  14800. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14801. if (this.enableUnpackFlipYCached) {
  14802. this._unpackFlipYCached = value;
  14803. }
  14804. }
  14805. };
  14806. /** @hidden */
  14807. Engine.prototype._getUnpackAlignement = function () {
  14808. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14809. };
  14810. /**
  14811. * Creates a dynamic texture
  14812. * @param width defines the width of the texture
  14813. * @param height defines the height of the texture
  14814. * @param generateMipMaps defines if the engine should generate the mip levels
  14815. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14816. * @returns the dynamic texture inside an InternalTexture
  14817. */
  14818. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14819. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14820. texture.baseWidth = width;
  14821. texture.baseHeight = height;
  14822. if (generateMipMaps) {
  14823. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14824. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14825. }
  14826. // this.resetTextureCache();
  14827. texture.width = width;
  14828. texture.height = height;
  14829. texture.isReady = false;
  14830. texture.generateMipMaps = generateMipMaps;
  14831. texture.samplingMode = samplingMode;
  14832. this.updateTextureSamplingMode(samplingMode, texture);
  14833. this._internalTexturesCache.push(texture);
  14834. return texture;
  14835. };
  14836. /**
  14837. * Update the sampling mode of a given texture
  14838. * @param samplingMode defines the required sampling mode
  14839. * @param texture defines the texture to update
  14840. */
  14841. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14842. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14843. if (texture.isCube) {
  14844. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14845. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14846. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14847. }
  14848. else if (texture.is3D) {
  14849. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14850. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14851. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14852. }
  14853. else {
  14854. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14855. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14856. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14857. }
  14858. texture.samplingMode = samplingMode;
  14859. };
  14860. /**
  14861. * Update the content of a dynamic texture
  14862. * @param texture defines the texture to update
  14863. * @param canvas defines the canvas containing the source
  14864. * @param invertY defines if data must be stored with Y axis inverted
  14865. * @param premulAlpha defines if alpha is stored as premultiplied
  14866. * @param format defines the format of the data
  14867. */
  14868. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14869. if (premulAlpha === void 0) { premulAlpha = false; }
  14870. if (!texture) {
  14871. return;
  14872. }
  14873. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14874. this._unpackFlipY(invertY);
  14875. if (premulAlpha) {
  14876. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14877. }
  14878. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14879. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14880. if (texture.generateMipMaps) {
  14881. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14882. }
  14883. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14884. if (premulAlpha) {
  14885. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14886. }
  14887. texture.isReady = true;
  14888. };
  14889. /**
  14890. * Update a video texture
  14891. * @param texture defines the texture to update
  14892. * @param video defines the video element to use
  14893. * @param invertY defines if data must be stored with Y axis inverted
  14894. */
  14895. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14896. if (!texture || texture._isDisabled) {
  14897. return;
  14898. }
  14899. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14900. this._unpackFlipY(!invertY); // Video are upside down by default
  14901. try {
  14902. // Testing video texture support
  14903. if (this._videoTextureSupported === undefined) {
  14904. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14905. if (this._gl.getError() !== 0) {
  14906. this._videoTextureSupported = false;
  14907. }
  14908. else {
  14909. this._videoTextureSupported = true;
  14910. }
  14911. }
  14912. // Copy video through the current working canvas if video texture is not supported
  14913. if (!this._videoTextureSupported) {
  14914. if (!texture._workingCanvas) {
  14915. texture._workingCanvas = document.createElement("canvas");
  14916. var context = texture._workingCanvas.getContext("2d");
  14917. if (!context) {
  14918. throw new Error("Unable to get 2d context");
  14919. }
  14920. texture._workingContext = context;
  14921. texture._workingCanvas.width = texture.width;
  14922. texture._workingCanvas.height = texture.height;
  14923. }
  14924. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14925. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14926. }
  14927. else {
  14928. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14929. }
  14930. if (texture.generateMipMaps) {
  14931. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14932. }
  14933. if (!wasPreviouslyBound) {
  14934. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14935. }
  14936. // this.resetTextureCache();
  14937. texture.isReady = true;
  14938. }
  14939. catch (ex) {
  14940. // Something unexpected
  14941. // Let's disable the texture
  14942. texture._isDisabled = true;
  14943. }
  14944. };
  14945. /**
  14946. * Updates a depth texture Comparison Mode and Function.
  14947. * If the comparison Function is equal to 0, the mode will be set to none.
  14948. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14949. * @param texture The texture to set the comparison function for
  14950. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14951. */
  14952. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14953. if (this.webGLVersion === 1) {
  14954. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14955. return;
  14956. }
  14957. var gl = this._gl;
  14958. if (texture.isCube) {
  14959. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14960. if (comparisonFunction === 0) {
  14961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14963. }
  14964. else {
  14965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14967. }
  14968. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14969. }
  14970. else {
  14971. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14972. if (comparisonFunction === 0) {
  14973. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14974. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14975. }
  14976. else {
  14977. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14979. }
  14980. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14981. }
  14982. texture._comparisonFunction = comparisonFunction;
  14983. };
  14984. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14985. var width = size.width || size;
  14986. var height = size.height || size;
  14987. internalTexture.baseWidth = width;
  14988. internalTexture.baseHeight = height;
  14989. internalTexture.width = width;
  14990. internalTexture.height = height;
  14991. internalTexture.isReady = true;
  14992. internalTexture.samples = 1;
  14993. internalTexture.generateMipMaps = false;
  14994. internalTexture._generateDepthBuffer = true;
  14995. internalTexture._generateStencilBuffer = generateStencil;
  14996. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14997. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14998. internalTexture._comparisonFunction = comparisonFunction;
  14999. var gl = this._gl;
  15000. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15001. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15002. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15003. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15004. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15005. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15006. if (comparisonFunction === 0) {
  15007. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15008. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15009. }
  15010. else {
  15011. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15012. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15013. }
  15014. };
  15015. /**
  15016. * Creates a depth stencil texture.
  15017. * This is only available in WebGL 2 or with the depth texture extension available.
  15018. * @param size The size of face edge in the texture.
  15019. * @param options The options defining the texture.
  15020. * @returns The texture
  15021. */
  15022. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15023. if (options.isCube) {
  15024. var width = size.width || size;
  15025. return this._createDepthStencilCubeTexture(width, options);
  15026. }
  15027. else {
  15028. return this._createDepthStencilTexture(size, options);
  15029. }
  15030. };
  15031. /**
  15032. * Creates a depth stencil texture.
  15033. * This is only available in WebGL 2 or with the depth texture extension available.
  15034. * @param size The size of face edge in the texture.
  15035. * @param options The options defining the texture.
  15036. * @returns The texture
  15037. */
  15038. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15039. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15040. if (!this._caps.depthTextureExtension) {
  15041. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15042. return internalTexture;
  15043. }
  15044. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15045. var gl = this._gl;
  15046. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15047. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15048. if (this.webGLVersion > 1) {
  15049. if (internalOptions.generateStencil) {
  15050. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15051. }
  15052. else {
  15053. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15054. }
  15055. }
  15056. else {
  15057. if (internalOptions.generateStencil) {
  15058. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15059. }
  15060. else {
  15061. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15062. }
  15063. }
  15064. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15065. return internalTexture;
  15066. };
  15067. /**
  15068. * Creates a depth stencil cube texture.
  15069. * This is only available in WebGL 2.
  15070. * @param size The size of face edge in the cube texture.
  15071. * @param options The options defining the cube texture.
  15072. * @returns The cube texture
  15073. */
  15074. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15075. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15076. internalTexture.isCube = true;
  15077. if (this.webGLVersion === 1) {
  15078. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15079. return internalTexture;
  15080. }
  15081. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15082. var gl = this._gl;
  15083. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15084. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15085. // Create the depth/stencil buffer
  15086. for (var face = 0; face < 6; face++) {
  15087. if (internalOptions.generateStencil) {
  15088. 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);
  15089. }
  15090. else {
  15091. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15092. }
  15093. }
  15094. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15095. return internalTexture;
  15096. };
  15097. /**
  15098. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15099. * @param renderTarget The render target to set the frame buffer for
  15100. */
  15101. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15102. // Create the framebuffer
  15103. var internalTexture = renderTarget.getInternalTexture();
  15104. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15105. return;
  15106. }
  15107. var gl = this._gl;
  15108. var depthStencilTexture = renderTarget.depthStencilTexture;
  15109. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15110. if (depthStencilTexture.isCube) {
  15111. if (depthStencilTexture._generateStencilBuffer) {
  15112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15113. }
  15114. else {
  15115. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15116. }
  15117. }
  15118. else {
  15119. if (depthStencilTexture._generateStencilBuffer) {
  15120. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15121. }
  15122. else {
  15123. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15124. }
  15125. }
  15126. this.bindUnboundFramebuffer(null);
  15127. };
  15128. /**
  15129. * Creates a new render target texture
  15130. * @param size defines the size of the texture
  15131. * @param options defines the options used to create the texture
  15132. * @returns a new render target texture stored in an InternalTexture
  15133. */
  15134. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15135. var fullOptions = new RenderTargetCreationOptions();
  15136. if (options !== undefined && typeof options === "object") {
  15137. fullOptions.generateMipMaps = options.generateMipMaps;
  15138. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15139. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15140. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15141. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15142. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15143. }
  15144. else {
  15145. fullOptions.generateMipMaps = options;
  15146. fullOptions.generateDepthBuffer = true;
  15147. fullOptions.generateStencilBuffer = false;
  15148. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15149. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15150. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15151. }
  15152. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15153. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15154. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15155. }
  15156. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15157. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15158. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15159. }
  15160. var gl = this._gl;
  15161. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15162. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15163. var width = size.width || size;
  15164. var height = size.height || size;
  15165. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15166. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15167. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15168. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15169. }
  15170. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15174. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15175. // Create the framebuffer
  15176. var currentFrameBuffer = this._currentFramebuffer;
  15177. var framebuffer = gl.createFramebuffer();
  15178. this.bindUnboundFramebuffer(framebuffer);
  15179. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15180. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15181. if (fullOptions.generateMipMaps) {
  15182. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15183. }
  15184. // Unbind
  15185. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15186. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15187. this.bindUnboundFramebuffer(currentFrameBuffer);
  15188. texture._framebuffer = framebuffer;
  15189. texture.baseWidth = width;
  15190. texture.baseHeight = height;
  15191. texture.width = width;
  15192. texture.height = height;
  15193. texture.isReady = true;
  15194. texture.samples = 1;
  15195. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15196. texture.samplingMode = fullOptions.samplingMode;
  15197. texture.type = fullOptions.type;
  15198. texture.format = fullOptions.format;
  15199. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15200. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15201. // this.resetTextureCache();
  15202. this._internalTexturesCache.push(texture);
  15203. return texture;
  15204. };
  15205. /**
  15206. * Create a multi render target texture
  15207. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15208. * @param size defines the size of the texture
  15209. * @param options defines the creation options
  15210. * @returns the cube texture as an InternalTexture
  15211. */
  15212. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15213. var generateMipMaps = false;
  15214. var generateDepthBuffer = true;
  15215. var generateStencilBuffer = false;
  15216. var generateDepthTexture = false;
  15217. var textureCount = 1;
  15218. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15219. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15220. var types = new Array();
  15221. var samplingModes = new Array();
  15222. if (options !== undefined) {
  15223. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15224. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15225. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15226. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15227. textureCount = options.textureCount || 1;
  15228. if (options.types) {
  15229. types = options.types;
  15230. }
  15231. if (options.samplingModes) {
  15232. samplingModes = options.samplingModes;
  15233. }
  15234. }
  15235. var gl = this._gl;
  15236. // Create the framebuffer
  15237. var framebuffer = gl.createFramebuffer();
  15238. this.bindUnboundFramebuffer(framebuffer);
  15239. var width = size.width || size;
  15240. var height = size.height || size;
  15241. var textures = [];
  15242. var attachments = [];
  15243. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15244. for (var i = 0; i < textureCount; i++) {
  15245. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15246. var type = types[i] || defaultType;
  15247. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15248. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15249. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15250. }
  15251. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15252. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15253. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15254. }
  15255. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15256. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15257. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15258. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15259. }
  15260. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15261. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15262. textures.push(texture);
  15263. attachments.push(attachment);
  15264. gl.activeTexture(gl["TEXTURE" + i]);
  15265. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15270. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15271. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15272. if (generateMipMaps) {
  15273. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15274. }
  15275. // Unbind
  15276. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15277. texture._framebuffer = framebuffer;
  15278. texture._depthStencilBuffer = depthStencilBuffer;
  15279. texture.baseWidth = width;
  15280. texture.baseHeight = height;
  15281. texture.width = width;
  15282. texture.height = height;
  15283. texture.isReady = true;
  15284. texture.samples = 1;
  15285. texture.generateMipMaps = generateMipMaps;
  15286. texture.samplingMode = samplingMode;
  15287. texture.type = type;
  15288. texture._generateDepthBuffer = generateDepthBuffer;
  15289. texture._generateStencilBuffer = generateStencilBuffer;
  15290. texture._attachments = attachments;
  15291. this._internalTexturesCache.push(texture);
  15292. }
  15293. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15294. // Depth texture
  15295. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15296. gl.activeTexture(gl.TEXTURE0);
  15297. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15302. 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);
  15303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15304. depthTexture._framebuffer = framebuffer;
  15305. depthTexture.baseWidth = width;
  15306. depthTexture.baseHeight = height;
  15307. depthTexture.width = width;
  15308. depthTexture.height = height;
  15309. depthTexture.isReady = true;
  15310. depthTexture.samples = 1;
  15311. depthTexture.generateMipMaps = generateMipMaps;
  15312. depthTexture.samplingMode = gl.NEAREST;
  15313. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15314. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15315. textures.push(depthTexture);
  15316. this._internalTexturesCache.push(depthTexture);
  15317. }
  15318. gl.drawBuffers(attachments);
  15319. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15320. this.bindUnboundFramebuffer(null);
  15321. this.resetTextureCache();
  15322. return textures;
  15323. };
  15324. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15325. if (samples === void 0) { samples = 1; }
  15326. var depthStencilBuffer = null;
  15327. var gl = this._gl;
  15328. // Create the depth/stencil buffer
  15329. if (generateStencilBuffer) {
  15330. depthStencilBuffer = gl.createRenderbuffer();
  15331. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15332. if (samples > 1) {
  15333. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15334. }
  15335. else {
  15336. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15337. }
  15338. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15339. }
  15340. else if (generateDepthBuffer) {
  15341. depthStencilBuffer = gl.createRenderbuffer();
  15342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15343. if (samples > 1) {
  15344. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15345. }
  15346. else {
  15347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15348. }
  15349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15350. }
  15351. return depthStencilBuffer;
  15352. };
  15353. /**
  15354. * Updates the sample count of a render target texture
  15355. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15356. * @param texture defines the texture to update
  15357. * @param samples defines the sample count to set
  15358. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15359. */
  15360. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15361. if (this.webGLVersion < 2 || !texture) {
  15362. return 1;
  15363. }
  15364. if (texture.samples === samples) {
  15365. return samples;
  15366. }
  15367. var gl = this._gl;
  15368. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15369. // Dispose previous render buffers
  15370. if (texture._depthStencilBuffer) {
  15371. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15372. texture._depthStencilBuffer = null;
  15373. }
  15374. if (texture._MSAAFramebuffer) {
  15375. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15376. texture._MSAAFramebuffer = null;
  15377. }
  15378. if (texture._MSAARenderBuffer) {
  15379. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15380. texture._MSAARenderBuffer = null;
  15381. }
  15382. if (samples > 1) {
  15383. var framebuffer = gl.createFramebuffer();
  15384. if (!framebuffer) {
  15385. throw new Error("Unable to create multi sampled framebuffer");
  15386. }
  15387. texture._MSAAFramebuffer = framebuffer;
  15388. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15389. var colorRenderbuffer = gl.createRenderbuffer();
  15390. if (!colorRenderbuffer) {
  15391. throw new Error("Unable to create multi sampled framebuffer");
  15392. }
  15393. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15394. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15395. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15396. texture._MSAARenderBuffer = colorRenderbuffer;
  15397. }
  15398. else {
  15399. this.bindUnboundFramebuffer(texture._framebuffer);
  15400. }
  15401. texture.samples = samples;
  15402. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15403. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15404. this.bindUnboundFramebuffer(null);
  15405. return samples;
  15406. };
  15407. /**
  15408. * Update the sample count for a given multiple render target texture
  15409. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15410. * @param textures defines the textures to update
  15411. * @param samples defines the sample count to set
  15412. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15413. */
  15414. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15415. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15416. return 1;
  15417. }
  15418. if (textures[0].samples === samples) {
  15419. return samples;
  15420. }
  15421. var gl = this._gl;
  15422. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15423. // Dispose previous render buffers
  15424. if (textures[0]._depthStencilBuffer) {
  15425. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15426. textures[0]._depthStencilBuffer = null;
  15427. }
  15428. if (textures[0]._MSAAFramebuffer) {
  15429. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15430. textures[0]._MSAAFramebuffer = null;
  15431. }
  15432. for (var i = 0; i < textures.length; i++) {
  15433. if (textures[i]._MSAARenderBuffer) {
  15434. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15435. textures[i]._MSAARenderBuffer = null;
  15436. }
  15437. }
  15438. if (samples > 1) {
  15439. var framebuffer = gl.createFramebuffer();
  15440. if (!framebuffer) {
  15441. throw new Error("Unable to create multi sampled framebuffer");
  15442. }
  15443. this.bindUnboundFramebuffer(framebuffer);
  15444. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15445. var attachments = [];
  15446. for (var i = 0; i < textures.length; i++) {
  15447. var texture = textures[i];
  15448. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15449. var colorRenderbuffer = gl.createRenderbuffer();
  15450. if (!colorRenderbuffer) {
  15451. throw new Error("Unable to create multi sampled framebuffer");
  15452. }
  15453. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15454. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15455. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15456. texture._MSAAFramebuffer = framebuffer;
  15457. texture._MSAARenderBuffer = colorRenderbuffer;
  15458. texture.samples = samples;
  15459. texture._depthStencilBuffer = depthStencilBuffer;
  15460. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15461. attachments.push(attachment);
  15462. }
  15463. gl.drawBuffers(attachments);
  15464. }
  15465. else {
  15466. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15467. }
  15468. this.bindUnboundFramebuffer(null);
  15469. return samples;
  15470. };
  15471. /** @hidden */
  15472. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15473. if (faceIndex === void 0) { faceIndex = 0; }
  15474. if (lod === void 0) { lod = 0; }
  15475. var gl = this._gl;
  15476. var target = gl.TEXTURE_2D;
  15477. if (texture.isCube) {
  15478. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15479. }
  15480. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15481. };
  15482. /** @hidden */
  15483. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15484. if (faceIndex === void 0) { faceIndex = 0; }
  15485. if (lod === void 0) { lod = 0; }
  15486. var gl = this._gl;
  15487. var textureType = this._getWebGLTextureType(texture.type);
  15488. var format = this._getInternalFormat(texture.format);
  15489. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15490. this._unpackFlipY(texture.invertY);
  15491. var target = gl.TEXTURE_2D;
  15492. if (texture.isCube) {
  15493. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15494. }
  15495. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15496. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15497. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15498. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15499. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15500. };
  15501. /** @hidden */
  15502. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15503. if (faceIndex === void 0) { faceIndex = 0; }
  15504. if (lod === void 0) { lod = 0; }
  15505. var gl = this._gl;
  15506. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15507. this._bindTextureDirectly(bindTarget, texture, true);
  15508. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15509. this._bindTextureDirectly(bindTarget, null, true);
  15510. };
  15511. /** @hidden */
  15512. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15513. if (faceIndex === void 0) { faceIndex = 0; }
  15514. if (lod === void 0) { lod = 0; }
  15515. var gl = this._gl;
  15516. var textureType = this._getWebGLTextureType(texture.type);
  15517. var format = this._getInternalFormat(texture.format);
  15518. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15519. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15520. this._bindTextureDirectly(bindTarget, texture, true);
  15521. this._unpackFlipY(texture.invertY);
  15522. var target = gl.TEXTURE_2D;
  15523. if (texture.isCube) {
  15524. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15525. }
  15526. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15527. this._bindTextureDirectly(bindTarget, null, true);
  15528. };
  15529. /**
  15530. * Creates a new render target cube texture
  15531. * @param size defines the size of the texture
  15532. * @param options defines the options used to create the texture
  15533. * @returns a new render target cube texture stored in an InternalTexture
  15534. */
  15535. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15536. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15537. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15538. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15539. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15540. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15541. }
  15542. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15543. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15544. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15545. }
  15546. var gl = this._gl;
  15547. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15548. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15549. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15550. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15551. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15552. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15553. }
  15554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15558. for (var face = 0; face < 6; face++) {
  15559. 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);
  15560. }
  15561. // Create the framebuffer
  15562. var framebuffer = gl.createFramebuffer();
  15563. this.bindUnboundFramebuffer(framebuffer);
  15564. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15565. // MipMaps
  15566. if (fullOptions.generateMipMaps) {
  15567. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15568. }
  15569. // Unbind
  15570. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15571. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15572. this.bindUnboundFramebuffer(null);
  15573. texture._framebuffer = framebuffer;
  15574. texture.width = size;
  15575. texture.height = size;
  15576. texture.isReady = true;
  15577. texture.isCube = true;
  15578. texture.samples = 1;
  15579. texture.generateMipMaps = fullOptions.generateMipMaps;
  15580. texture.samplingMode = fullOptions.samplingMode;
  15581. texture.type = fullOptions.type;
  15582. texture.format = fullOptions.format;
  15583. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15584. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15585. this._internalTexturesCache.push(texture);
  15586. return texture;
  15587. };
  15588. /**
  15589. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15590. * @param rootUrl defines the url where the file to load is located
  15591. * @param scene defines the current scene
  15592. * @param lodScale defines scale to apply to the mip map selection
  15593. * @param lodOffset defines offset to apply to the mip map selection
  15594. * @param onLoad defines an optional callback raised when the texture is loaded
  15595. * @param onError defines an optional callback raised if there is an issue to load the texture
  15596. * @param format defines the format of the data
  15597. * @param forcedExtension defines the extension to use to pick the right loader
  15598. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15599. * @returns the cube texture as an InternalTexture
  15600. */
  15601. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15602. var _this = this;
  15603. if (onLoad === void 0) { onLoad = null; }
  15604. if (onError === void 0) { onError = null; }
  15605. if (forcedExtension === void 0) { forcedExtension = null; }
  15606. if (createPolynomials === void 0) { createPolynomials = true; }
  15607. var callback = function (loadData) {
  15608. if (!loadData) {
  15609. if (onLoad) {
  15610. onLoad(null);
  15611. }
  15612. return;
  15613. }
  15614. var texture = loadData.texture;
  15615. if (!createPolynomials) {
  15616. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15617. }
  15618. else if (loadData.info.sphericalPolynomial) {
  15619. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15620. }
  15621. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15622. if (_this._caps.textureLOD) {
  15623. // Do not add extra process if texture lod is supported.
  15624. if (onLoad) {
  15625. onLoad(texture);
  15626. }
  15627. return;
  15628. }
  15629. var mipSlices = 3;
  15630. var gl = _this._gl;
  15631. var width = loadData.width;
  15632. if (!width) {
  15633. return;
  15634. }
  15635. var textures = [];
  15636. for (var i = 0; i < mipSlices; i++) {
  15637. //compute LOD from even spacing in smoothness (matching shader calculation)
  15638. var smoothness = i / (mipSlices - 1);
  15639. var roughness = 1 - smoothness;
  15640. var minLODIndex = lodOffset; // roughness = 0
  15641. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15642. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15643. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15644. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15645. glTextureFromLod.type = texture.type;
  15646. glTextureFromLod.format = texture.format;
  15647. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15648. glTextureFromLod.height = glTextureFromLod.width;
  15649. glTextureFromLod.isCube = true;
  15650. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15651. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15655. if (loadData.isDDS) {
  15656. var info = loadData.info;
  15657. var data = loadData.data;
  15658. _this._unpackFlipY(info.isCompressed);
  15659. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15660. }
  15661. else {
  15662. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15663. }
  15664. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15665. // Wrap in a base texture for easy binding.
  15666. var lodTexture = new BABYLON.BaseTexture(scene);
  15667. lodTexture.isCube = true;
  15668. lodTexture._texture = glTextureFromLod;
  15669. glTextureFromLod.isReady = true;
  15670. textures.push(lodTexture);
  15671. }
  15672. texture._lodTextureHigh = textures[2];
  15673. texture._lodTextureMid = textures[1];
  15674. texture._lodTextureLow = textures[0];
  15675. if (onLoad) {
  15676. onLoad(texture);
  15677. }
  15678. };
  15679. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15680. };
  15681. /**
  15682. * Creates a cube texture
  15683. * @param rootUrl defines the url where the files to load is located
  15684. * @param scene defines the current scene
  15685. * @param files defines the list of files to load (1 per face)
  15686. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15687. * @param onLoad defines an optional callback raised when the texture is loaded
  15688. * @param onError defines an optional callback raised if there is an issue to load the texture
  15689. * @param format defines the format of the data
  15690. * @param forcedExtension defines the extension to use to pick the right loader
  15691. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15692. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15693. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15694. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15695. * @returns the cube texture as an InternalTexture
  15696. */
  15697. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15698. var _this = this;
  15699. if (onLoad === void 0) { onLoad = null; }
  15700. if (onError === void 0) { onError = null; }
  15701. if (forcedExtension === void 0) { forcedExtension = null; }
  15702. if (createPolynomials === void 0) { createPolynomials = false; }
  15703. if (lodScale === void 0) { lodScale = 0; }
  15704. if (lodOffset === void 0) { lodOffset = 0; }
  15705. if (fallback === void 0) { fallback = null; }
  15706. var gl = this._gl;
  15707. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15708. texture.isCube = true;
  15709. texture.url = rootUrl;
  15710. texture.generateMipMaps = !noMipmap;
  15711. texture._lodGenerationScale = lodScale;
  15712. texture._lodGenerationOffset = lodOffset;
  15713. if (!this._doNotHandleContextLost) {
  15714. texture._extension = forcedExtension;
  15715. texture._files = files;
  15716. }
  15717. var lastDot = rootUrl.lastIndexOf('.');
  15718. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15719. var loader = null;
  15720. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15721. var availableLoader = _a[_i];
  15722. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15723. loader = availableLoader;
  15724. break;
  15725. }
  15726. }
  15727. var onInternalError = function (request, exception) {
  15728. if (loader) {
  15729. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15730. if (fallbackUrl) {
  15731. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15732. }
  15733. }
  15734. if (onError && request) {
  15735. onError(request.status + " " + request.statusText, exception);
  15736. }
  15737. };
  15738. if (loader) {
  15739. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15740. var onloaddata = function (data) {
  15741. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15742. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15743. };
  15744. if (files && files.length === 6) {
  15745. if (loader.supportCascades) {
  15746. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15747. }
  15748. else if (onError) {
  15749. onError("Textures type does not support cascades.");
  15750. }
  15751. }
  15752. else {
  15753. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15754. }
  15755. }
  15756. else {
  15757. if (!files) {
  15758. throw new Error("Cannot load cubemap because files were not defined");
  15759. }
  15760. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15761. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15762. var height = width;
  15763. _this._prepareWorkingCanvas();
  15764. if (!_this._workingCanvas || !_this._workingContext) {
  15765. return;
  15766. }
  15767. _this._workingCanvas.width = width;
  15768. _this._workingCanvas.height = height;
  15769. var faces = [
  15770. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15771. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15772. ];
  15773. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15774. _this._unpackFlipY(false);
  15775. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15776. for (var index = 0; index < faces.length; index++) {
  15777. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15778. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15779. }
  15780. if (!noMipmap) {
  15781. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15782. }
  15783. _this._setCubeMapTextureParams(!noMipmap);
  15784. texture.width = width;
  15785. texture.height = height;
  15786. texture.isReady = true;
  15787. if (format) {
  15788. texture.format = format;
  15789. }
  15790. texture.onLoadedObservable.notifyObservers(texture);
  15791. texture.onLoadedObservable.clear();
  15792. if (onLoad) {
  15793. onLoad();
  15794. }
  15795. }, files, onError);
  15796. }
  15797. this._internalTexturesCache.push(texture);
  15798. return texture;
  15799. };
  15800. /**
  15801. * @hidden
  15802. */
  15803. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15804. var gl = this._gl;
  15805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15809. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15810. // this.resetTextureCache();
  15811. };
  15812. /**
  15813. * Update a raw cube texture
  15814. * @param texture defines the texture to udpdate
  15815. * @param data defines the data to store
  15816. * @param format defines the data format
  15817. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15818. * @param invertY defines if data must be stored with Y axis inverted
  15819. * @param compression defines the compression used (null by default)
  15820. * @param level defines which level of the texture to update
  15821. */
  15822. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15823. if (compression === void 0) { compression = null; }
  15824. if (level === void 0) { level = 0; }
  15825. texture._bufferViewArray = data;
  15826. texture.format = format;
  15827. texture.type = type;
  15828. texture.invertY = invertY;
  15829. texture._compression = compression;
  15830. var gl = this._gl;
  15831. var textureType = this._getWebGLTextureType(type);
  15832. var internalFormat = this._getInternalFormat(format);
  15833. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15834. var needConversion = false;
  15835. if (internalFormat === gl.RGB) {
  15836. internalFormat = gl.RGBA;
  15837. needConversion = true;
  15838. }
  15839. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15840. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15841. if (texture.width % 4 !== 0) {
  15842. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15843. }
  15844. // Data are known to be in +X +Y +Z -X -Y -Z
  15845. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15846. var faceData = data[faceIndex];
  15847. if (compression) {
  15848. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15849. }
  15850. else {
  15851. if (needConversion) {
  15852. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15853. }
  15854. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15855. }
  15856. }
  15857. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15858. if (isPot && texture.generateMipMaps && level === 0) {
  15859. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15860. }
  15861. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15862. // this.resetTextureCache();
  15863. texture.isReady = true;
  15864. };
  15865. /**
  15866. * Creates a new raw cube texture
  15867. * @param data defines the array of data to use to create each face
  15868. * @param size defines the size of the textures
  15869. * @param format defines the format of the data
  15870. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15871. * @param generateMipMaps defines if the engine should generate the mip levels
  15872. * @param invertY defines if data must be stored with Y axis inverted
  15873. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15874. * @param compression defines the compression used (null by default)
  15875. * @returns the cube texture as an InternalTexture
  15876. */
  15877. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15878. if (compression === void 0) { compression = null; }
  15879. var gl = this._gl;
  15880. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15881. texture.isCube = true;
  15882. texture.format = format;
  15883. texture.type = type;
  15884. if (!this._doNotHandleContextLost) {
  15885. texture._bufferViewArray = data;
  15886. }
  15887. var textureType = this._getWebGLTextureType(type);
  15888. var internalFormat = this._getInternalFormat(format);
  15889. if (internalFormat === gl.RGB) {
  15890. internalFormat = gl.RGBA;
  15891. }
  15892. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15893. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15894. generateMipMaps = false;
  15895. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15896. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15897. }
  15898. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15899. generateMipMaps = false;
  15900. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15901. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15902. }
  15903. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15904. generateMipMaps = false;
  15905. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15906. }
  15907. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15908. generateMipMaps = false;
  15909. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15910. }
  15911. var width = size;
  15912. var height = width;
  15913. texture.width = width;
  15914. texture.height = height;
  15915. // Double check on POT to generate Mips.
  15916. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15917. if (!isPot) {
  15918. generateMipMaps = false;
  15919. }
  15920. // Upload data if needed. The texture won't be ready until then.
  15921. if (data) {
  15922. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15923. }
  15924. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15925. // Filters
  15926. if (data && generateMipMaps) {
  15927. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15928. }
  15929. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15934. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15935. texture.generateMipMaps = generateMipMaps;
  15936. return texture;
  15937. };
  15938. /**
  15939. * Creates a new raw cube texture from a specified url
  15940. * @param url defines the url where the data is located
  15941. * @param scene defines the current scene
  15942. * @param size defines the size of the textures
  15943. * @param format defines the format of the data
  15944. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15945. * @param noMipmap defines if the engine should avoid generating the mip levels
  15946. * @param callback defines a callback used to extract texture data from loaded data
  15947. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15948. * @param onLoad defines a callback called when texture is loaded
  15949. * @param onError defines a callback called if there is an error
  15950. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15951. * @param invertY defines if data must be stored with Y axis inverted
  15952. * @returns the cube texture as an InternalTexture
  15953. */
  15954. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15955. var _this = this;
  15956. if (onLoad === void 0) { onLoad = null; }
  15957. if (onError === void 0) { onError = null; }
  15958. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15959. if (invertY === void 0) { invertY = false; }
  15960. var gl = this._gl;
  15961. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15962. scene._addPendingData(texture);
  15963. texture.url = url;
  15964. this._internalTexturesCache.push(texture);
  15965. var onerror = function (request, exception) {
  15966. scene._removePendingData(texture);
  15967. if (onError && request) {
  15968. onError(request.status + " " + request.statusText, exception);
  15969. }
  15970. };
  15971. var internalCallback = function (data) {
  15972. var width = texture.width;
  15973. var faceDataArrays = callback(data);
  15974. if (!faceDataArrays) {
  15975. return;
  15976. }
  15977. if (mipmapGenerator) {
  15978. var textureType = _this._getWebGLTextureType(type);
  15979. var internalFormat = _this._getInternalFormat(format);
  15980. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15981. var needConversion = false;
  15982. if (internalFormat === gl.RGB) {
  15983. internalFormat = gl.RGBA;
  15984. needConversion = true;
  15985. }
  15986. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15987. _this._unpackFlipY(false);
  15988. var mipData = mipmapGenerator(faceDataArrays);
  15989. for (var level = 0; level < mipData.length; level++) {
  15990. var mipSize = width >> level;
  15991. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15992. var mipFaceData = mipData[level][faceIndex];
  15993. if (needConversion) {
  15994. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15995. }
  15996. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15997. }
  15998. }
  15999. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16000. }
  16001. else {
  16002. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16003. }
  16004. texture.isReady = true;
  16005. // this.resetTextureCache();
  16006. scene._removePendingData(texture);
  16007. if (onLoad) {
  16008. onLoad();
  16009. }
  16010. };
  16011. this._loadFile(url, function (data) {
  16012. internalCallback(data);
  16013. }, undefined, scene.database, true, onerror);
  16014. return texture;
  16015. };
  16016. ;
  16017. /**
  16018. * Update a raw 3D texture
  16019. * @param texture defines the texture to update
  16020. * @param data defines the data to store
  16021. * @param format defines the data format
  16022. * @param invertY defines if data must be stored with Y axis inverted
  16023. * @param compression defines the used compression (can be null)
  16024. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16025. */
  16026. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16027. if (compression === void 0) { compression = null; }
  16028. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16029. var internalType = this._getWebGLTextureType(textureType);
  16030. var internalFormat = this._getInternalFormat(format);
  16031. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16032. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16033. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16034. if (!this._doNotHandleContextLost) {
  16035. texture._bufferView = data;
  16036. texture.format = format;
  16037. texture.invertY = invertY;
  16038. texture._compression = compression;
  16039. }
  16040. if (texture.width % 4 !== 0) {
  16041. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16042. }
  16043. if (compression && data) {
  16044. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16045. }
  16046. else {
  16047. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16048. }
  16049. if (texture.generateMipMaps) {
  16050. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16051. }
  16052. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16053. // this.resetTextureCache();
  16054. texture.isReady = true;
  16055. };
  16056. /**
  16057. * Creates a new raw 3D texture
  16058. * @param data defines the data used to create the texture
  16059. * @param width defines the width of the texture
  16060. * @param height defines the height of the texture
  16061. * @param depth defines the depth of the texture
  16062. * @param format defines the format of the texture
  16063. * @param generateMipMaps defines if the engine must generate mip levels
  16064. * @param invertY defines if data must be stored with Y axis inverted
  16065. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16066. * @param compression defines the compressed used (can be null)
  16067. * @param textureType defines the compressed used (can be null)
  16068. * @returns a new raw 3D texture (stored in an InternalTexture)
  16069. */
  16070. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16071. if (compression === void 0) { compression = null; }
  16072. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16073. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16074. texture.baseWidth = width;
  16075. texture.baseHeight = height;
  16076. texture.baseDepth = depth;
  16077. texture.width = width;
  16078. texture.height = height;
  16079. texture.depth = depth;
  16080. texture.format = format;
  16081. texture.type = textureType;
  16082. texture.generateMipMaps = generateMipMaps;
  16083. texture.samplingMode = samplingMode;
  16084. texture.is3D = true;
  16085. if (!this._doNotHandleContextLost) {
  16086. texture._bufferView = data;
  16087. }
  16088. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16089. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16090. // Filters
  16091. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16092. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16093. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16094. if (generateMipMaps) {
  16095. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16096. }
  16097. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16098. this._internalTexturesCache.push(texture);
  16099. return texture;
  16100. };
  16101. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16102. var gl = this._gl;
  16103. if (!gl) {
  16104. return;
  16105. }
  16106. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16109. if (!noMipmap && !isCompressed) {
  16110. gl.generateMipmap(gl.TEXTURE_2D);
  16111. }
  16112. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16113. // this.resetTextureCache();
  16114. if (scene) {
  16115. scene._removePendingData(texture);
  16116. }
  16117. texture.onLoadedObservable.notifyObservers(texture);
  16118. texture.onLoadedObservable.clear();
  16119. };
  16120. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16121. var _this = this;
  16122. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16123. var maxTextureSize = this.getCaps().maxTextureSize;
  16124. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16125. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16126. var gl = this._gl;
  16127. if (!gl) {
  16128. return;
  16129. }
  16130. if (!texture._webGLTexture) {
  16131. // this.resetTextureCache();
  16132. if (scene) {
  16133. scene._removePendingData(texture);
  16134. }
  16135. return;
  16136. }
  16137. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16138. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16139. texture.baseWidth = width;
  16140. texture.baseHeight = height;
  16141. texture.width = potWidth;
  16142. texture.height = potHeight;
  16143. texture.isReady = true;
  16144. if (processFunction(potWidth, potHeight, function () {
  16145. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16146. })) {
  16147. // Returning as texture needs extra async steps
  16148. return;
  16149. }
  16150. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16151. };
  16152. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16153. // Create new RGBA data container.
  16154. var rgbaData;
  16155. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16156. rgbaData = new Float32Array(width * height * 4);
  16157. }
  16158. else {
  16159. rgbaData = new Uint32Array(width * height * 4);
  16160. }
  16161. // Convert each pixel.
  16162. for (var x = 0; x < width; x++) {
  16163. for (var y = 0; y < height; y++) {
  16164. var index = (y * width + x) * 3;
  16165. var newIndex = (y * width + x) * 4;
  16166. // Map Old Value to new value.
  16167. rgbaData[newIndex + 0] = rgbData[index + 0];
  16168. rgbaData[newIndex + 1] = rgbData[index + 1];
  16169. rgbaData[newIndex + 2] = rgbData[index + 2];
  16170. // Add fully opaque alpha channel.
  16171. rgbaData[newIndex + 3] = 1;
  16172. }
  16173. }
  16174. return rgbaData;
  16175. };
  16176. /** @hidden */
  16177. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16178. var gl = this._gl;
  16179. if (texture._framebuffer) {
  16180. gl.deleteFramebuffer(texture._framebuffer);
  16181. texture._framebuffer = null;
  16182. }
  16183. if (texture._depthStencilBuffer) {
  16184. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16185. texture._depthStencilBuffer = null;
  16186. }
  16187. if (texture._MSAAFramebuffer) {
  16188. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16189. texture._MSAAFramebuffer = null;
  16190. }
  16191. if (texture._MSAARenderBuffer) {
  16192. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16193. texture._MSAARenderBuffer = null;
  16194. }
  16195. };
  16196. /** @hidden */
  16197. Engine.prototype._releaseTexture = function (texture) {
  16198. var gl = this._gl;
  16199. this._releaseFramebufferObjects(texture);
  16200. gl.deleteTexture(texture._webGLTexture);
  16201. // Unbind channels
  16202. this.unbindAllTextures();
  16203. var index = this._internalTexturesCache.indexOf(texture);
  16204. if (index !== -1) {
  16205. this._internalTexturesCache.splice(index, 1);
  16206. }
  16207. // Integrated fixed lod samplers.
  16208. if (texture._lodTextureHigh) {
  16209. texture._lodTextureHigh.dispose();
  16210. }
  16211. if (texture._lodTextureMid) {
  16212. texture._lodTextureMid.dispose();
  16213. }
  16214. if (texture._lodTextureLow) {
  16215. texture._lodTextureLow.dispose();
  16216. }
  16217. // Set output texture of post process to null if the texture has been released/disposed
  16218. this.scenes.forEach(function (scene) {
  16219. scene.postProcesses.forEach(function (postProcess) {
  16220. if (postProcess._outputTexture == texture) {
  16221. postProcess._outputTexture = null;
  16222. }
  16223. });
  16224. scene.cameras.forEach(function (camera) {
  16225. camera._postProcesses.forEach(function (postProcess) {
  16226. if (postProcess) {
  16227. if (postProcess._outputTexture == texture) {
  16228. postProcess._outputTexture = null;
  16229. }
  16230. }
  16231. });
  16232. });
  16233. });
  16234. };
  16235. Engine.prototype.setProgram = function (program) {
  16236. if (this._currentProgram !== program) {
  16237. this._gl.useProgram(program);
  16238. this._currentProgram = program;
  16239. }
  16240. };
  16241. /**
  16242. * Binds an effect to the webGL context
  16243. * @param effect defines the effect to bind
  16244. */
  16245. Engine.prototype.bindSamplers = function (effect) {
  16246. this.setProgram(effect.getProgram());
  16247. var samplers = effect.getSamplers();
  16248. for (var index = 0; index < samplers.length; index++) {
  16249. var uniform = effect.getUniform(samplers[index]);
  16250. if (uniform) {
  16251. this._boundUniforms[index] = uniform;
  16252. }
  16253. }
  16254. this._currentEffect = null;
  16255. };
  16256. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16257. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16258. return;
  16259. }
  16260. // Remove
  16261. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16262. // Bind last to it
  16263. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16264. // Bind to dummy
  16265. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16266. };
  16267. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16268. if (!internalTexture) {
  16269. return -1;
  16270. }
  16271. internalTexture._initialSlot = channel;
  16272. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16273. if (channel !== internalTexture._designatedSlot) {
  16274. this._textureCollisions.addCount(1, false);
  16275. }
  16276. }
  16277. else {
  16278. if (channel !== internalTexture._designatedSlot) {
  16279. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16280. return internalTexture._designatedSlot;
  16281. }
  16282. else {
  16283. // No slot for this texture, let's pick a new one (if we find a free slot)
  16284. if (this._nextFreeTextureSlots.length) {
  16285. return this._nextFreeTextureSlots[0];
  16286. }
  16287. // We need to recycle the oldest bound texture, sorry.
  16288. this._textureCollisions.addCount(1, false);
  16289. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16290. }
  16291. }
  16292. }
  16293. return channel;
  16294. };
  16295. Engine.prototype._linkTrackers = function (previous, next) {
  16296. previous.next = next;
  16297. next.previous = previous;
  16298. };
  16299. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16300. var currentSlot = internalTexture._designatedSlot;
  16301. if (currentSlot === -1) {
  16302. return -1;
  16303. }
  16304. internalTexture._designatedSlot = -1;
  16305. if (this.disableTextureBindingOptimization) {
  16306. return -1;
  16307. }
  16308. // Remove from bound list
  16309. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16310. // Free the slot
  16311. this._boundTexturesCache[currentSlot] = null;
  16312. this._nextFreeTextureSlots.push(currentSlot);
  16313. return currentSlot;
  16314. };
  16315. Engine.prototype._activateCurrentTexture = function () {
  16316. if (this._currentTextureChannel !== this._activeChannel) {
  16317. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16318. this._currentTextureChannel = this._activeChannel;
  16319. }
  16320. };
  16321. /** @hidden */
  16322. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16323. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16324. if (force === void 0) { force = false; }
  16325. var wasPreviouslyBound = false;
  16326. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16327. this._activeChannel = texture._designatedSlot;
  16328. }
  16329. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16330. var isTextureForRendering = texture && texture._initialSlot > -1;
  16331. if (currentTextureBound !== texture || force) {
  16332. if (currentTextureBound) {
  16333. this._removeDesignatedSlot(currentTextureBound);
  16334. }
  16335. this._activateCurrentTexture();
  16336. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16337. this._boundTexturesCache[this._activeChannel] = texture;
  16338. if (texture) {
  16339. if (!this.disableTextureBindingOptimization) {
  16340. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16341. if (slotIndex > -1) {
  16342. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16343. }
  16344. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16345. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16346. }
  16347. texture._designatedSlot = this._activeChannel;
  16348. }
  16349. }
  16350. else if (forTextureDataUpdate) {
  16351. wasPreviouslyBound = true;
  16352. this._activateCurrentTexture();
  16353. }
  16354. if (isTextureForRendering && !forTextureDataUpdate) {
  16355. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16356. }
  16357. return wasPreviouslyBound;
  16358. };
  16359. /** @hidden */
  16360. Engine.prototype._bindTexture = function (channel, texture) {
  16361. if (channel < 0) {
  16362. return;
  16363. }
  16364. if (texture) {
  16365. channel = this._getCorrectTextureChannel(channel, texture);
  16366. }
  16367. this._activeChannel = channel;
  16368. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16369. };
  16370. /**
  16371. * Sets a texture to the webGL context from a postprocess
  16372. * @param channel defines the channel to use
  16373. * @param postProcess defines the source postprocess
  16374. */
  16375. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16376. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16377. };
  16378. /**
  16379. * Binds the output of the passed in post process to the texture channel specified
  16380. * @param channel The channel the texture should be bound to
  16381. * @param postProcess The post process which's output should be bound
  16382. */
  16383. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16384. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16385. };
  16386. /**
  16387. * Unbind all textures from the webGL context
  16388. */
  16389. Engine.prototype.unbindAllTextures = function () {
  16390. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16391. this._activeChannel = channel;
  16392. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16393. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16394. if (this.webGLVersion > 1) {
  16395. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16396. }
  16397. }
  16398. };
  16399. /**
  16400. * Sets a texture to the according uniform.
  16401. * @param channel The texture channel
  16402. * @param uniform The uniform to set
  16403. * @param texture The texture to apply
  16404. */
  16405. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16406. if (channel < 0) {
  16407. return;
  16408. }
  16409. if (uniform) {
  16410. this._boundUniforms[channel] = uniform;
  16411. }
  16412. this._setTexture(channel, texture);
  16413. };
  16414. /**
  16415. * Sets a depth stencil texture from a render target to the according uniform.
  16416. * @param channel The texture channel
  16417. * @param uniform The uniform to set
  16418. * @param texture The render target texture containing the depth stencil texture to apply
  16419. */
  16420. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16421. if (channel < 0) {
  16422. return;
  16423. }
  16424. if (uniform) {
  16425. this._boundUniforms[channel] = uniform;
  16426. }
  16427. if (!texture || !texture.depthStencilTexture) {
  16428. this._setTexture(channel, null);
  16429. }
  16430. else {
  16431. this._setTexture(channel, texture, false, true);
  16432. }
  16433. };
  16434. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16435. var uniform = this._boundUniforms[sourceSlot];
  16436. if (uniform._currentState === destination) {
  16437. return;
  16438. }
  16439. this._gl.uniform1i(uniform, destination);
  16440. uniform._currentState = destination;
  16441. };
  16442. Engine.prototype._getTextureWrapMode = function (mode) {
  16443. switch (mode) {
  16444. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16445. return this._gl.REPEAT;
  16446. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16447. return this._gl.CLAMP_TO_EDGE;
  16448. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16449. return this._gl.MIRRORED_REPEAT;
  16450. }
  16451. return this._gl.REPEAT;
  16452. };
  16453. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16454. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16455. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16456. // Not ready?
  16457. if (!texture) {
  16458. if (this._boundTexturesCache[channel] != null) {
  16459. this._activeChannel = channel;
  16460. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16461. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16462. if (this.webGLVersion > 1) {
  16463. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16464. }
  16465. }
  16466. return false;
  16467. }
  16468. // Video
  16469. if (texture.video) {
  16470. this._activeChannel = channel;
  16471. texture.update();
  16472. }
  16473. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16474. texture.delayLoad();
  16475. return false;
  16476. }
  16477. var internalTexture;
  16478. if (depthStencilTexture) {
  16479. internalTexture = texture.depthStencilTexture;
  16480. }
  16481. else if (texture.isReady()) {
  16482. internalTexture = texture.getInternalTexture();
  16483. }
  16484. else if (texture.isCube) {
  16485. internalTexture = this.emptyCubeTexture;
  16486. }
  16487. else if (texture.is3D) {
  16488. internalTexture = this.emptyTexture3D;
  16489. }
  16490. else {
  16491. internalTexture = this.emptyTexture;
  16492. }
  16493. if (!isPartOfTextureArray) {
  16494. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16495. }
  16496. var needToBind = true;
  16497. if (this._boundTexturesCache[channel] === internalTexture) {
  16498. this._moveBoundTextureOnTop(internalTexture);
  16499. if (!isPartOfTextureArray) {
  16500. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16501. }
  16502. needToBind = false;
  16503. }
  16504. this._activeChannel = channel;
  16505. if (internalTexture && internalTexture.is3D) {
  16506. if (needToBind) {
  16507. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16508. }
  16509. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16510. internalTexture._cachedWrapU = texture.wrapU;
  16511. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16512. }
  16513. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16514. internalTexture._cachedWrapV = texture.wrapV;
  16515. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16516. }
  16517. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16518. internalTexture._cachedWrapR = texture.wrapR;
  16519. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16520. }
  16521. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16522. }
  16523. else if (internalTexture && internalTexture.isCube) {
  16524. if (needToBind) {
  16525. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16526. }
  16527. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16528. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16529. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16530. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16531. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16532. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16533. }
  16534. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16535. }
  16536. else {
  16537. if (needToBind) {
  16538. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16539. }
  16540. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16541. internalTexture._cachedWrapU = texture.wrapU;
  16542. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16543. }
  16544. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16545. internalTexture._cachedWrapV = texture.wrapV;
  16546. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16547. }
  16548. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16549. }
  16550. return true;
  16551. };
  16552. /**
  16553. * Sets an array of texture to the webGL context
  16554. * @param channel defines the channel where the texture array must be set
  16555. * @param uniform defines the associated uniform location
  16556. * @param textures defines the array of textures to bind
  16557. */
  16558. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16559. if (channel < 0 || !uniform) {
  16560. return;
  16561. }
  16562. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16563. this._textureUnits = new Int32Array(textures.length);
  16564. }
  16565. for (var i = 0; i < textures.length; i++) {
  16566. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16567. }
  16568. this._gl.uniform1iv(uniform, this._textureUnits);
  16569. for (var index = 0; index < textures.length; index++) {
  16570. this._setTexture(this._textureUnits[index], textures[index], true);
  16571. }
  16572. };
  16573. /** @hidden */
  16574. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16575. var internalTexture = texture.getInternalTexture();
  16576. if (!internalTexture) {
  16577. return;
  16578. }
  16579. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16580. var value = texture.anisotropicFilteringLevel;
  16581. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16582. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16583. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16584. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16585. }
  16586. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16587. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16588. internalTexture._cachedAnisotropicFilteringLevel = value;
  16589. }
  16590. };
  16591. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16592. this._bindTextureDirectly(target, texture, true, true);
  16593. this._gl.texParameterf(target, parameter, value);
  16594. };
  16595. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16596. if (texture) {
  16597. this._bindTextureDirectly(target, texture, true, true);
  16598. }
  16599. this._gl.texParameteri(target, parameter, value);
  16600. };
  16601. /**
  16602. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16603. * @param x defines the x coordinate of the rectangle where pixels must be read
  16604. * @param y defines the y coordinate of the rectangle where pixels must be read
  16605. * @param width defines the width of the rectangle where pixels must be read
  16606. * @param height defines the height of the rectangle where pixels must be read
  16607. * @returns a Uint8Array containing RGBA colors
  16608. */
  16609. Engine.prototype.readPixels = function (x, y, width, height) {
  16610. var data = new Uint8Array(height * width * 4);
  16611. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16612. return data;
  16613. };
  16614. /**
  16615. * Add an externaly attached data from its key.
  16616. * This method call will fail and return false, if such key already exists.
  16617. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16618. * @param key the unique key that identifies the data
  16619. * @param data the data object to associate to the key for this Engine instance
  16620. * @return true if no such key were already present and the data was added successfully, false otherwise
  16621. */
  16622. Engine.prototype.addExternalData = function (key, data) {
  16623. if (!this._externalData) {
  16624. this._externalData = new BABYLON.StringDictionary();
  16625. }
  16626. return this._externalData.add(key, data);
  16627. };
  16628. /**
  16629. * Get an externaly attached data from its key
  16630. * @param key the unique key that identifies the data
  16631. * @return the associated data, if present (can be null), or undefined if not present
  16632. */
  16633. Engine.prototype.getExternalData = function (key) {
  16634. if (!this._externalData) {
  16635. this._externalData = new BABYLON.StringDictionary();
  16636. }
  16637. return this._externalData.get(key);
  16638. };
  16639. /**
  16640. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16641. * @param key the unique key that identifies the data
  16642. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16643. * @return the associated data, can be null if the factory returned null.
  16644. */
  16645. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16646. if (!this._externalData) {
  16647. this._externalData = new BABYLON.StringDictionary();
  16648. }
  16649. return this._externalData.getOrAddWithFactory(key, factory);
  16650. };
  16651. /**
  16652. * Remove an externaly attached data from the Engine instance
  16653. * @param key the unique key that identifies the data
  16654. * @return true if the data was successfully removed, false if it doesn't exist
  16655. */
  16656. Engine.prototype.removeExternalData = function (key) {
  16657. if (!this._externalData) {
  16658. this._externalData = new BABYLON.StringDictionary();
  16659. }
  16660. return this._externalData.remove(key);
  16661. };
  16662. /**
  16663. * Unbind all vertex attributes from the webGL context
  16664. */
  16665. Engine.prototype.unbindAllAttributes = function () {
  16666. if (this._mustWipeVertexAttributes) {
  16667. this._mustWipeVertexAttributes = false;
  16668. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16669. this._gl.disableVertexAttribArray(i);
  16670. this._vertexAttribArraysEnabled[i] = false;
  16671. this._currentBufferPointers[i].active = false;
  16672. }
  16673. return;
  16674. }
  16675. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16676. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16677. continue;
  16678. }
  16679. this._gl.disableVertexAttribArray(i);
  16680. this._vertexAttribArraysEnabled[i] = false;
  16681. this._currentBufferPointers[i].active = false;
  16682. }
  16683. };
  16684. /**
  16685. * 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
  16686. */
  16687. Engine.prototype.releaseEffects = function () {
  16688. for (var name in this._compiledEffects) {
  16689. this._deleteProgram(this._compiledEffects[name]._program);
  16690. }
  16691. this._compiledEffects = {};
  16692. };
  16693. /**
  16694. * Dispose and release all associated resources
  16695. */
  16696. Engine.prototype.dispose = function () {
  16697. this.hideLoadingUI();
  16698. this.stopRenderLoop();
  16699. // Release postProcesses
  16700. while (this.postProcesses.length) {
  16701. this.postProcesses[0].dispose();
  16702. }
  16703. // Empty texture
  16704. if (this._emptyTexture) {
  16705. this._releaseTexture(this._emptyTexture);
  16706. this._emptyTexture = null;
  16707. }
  16708. if (this._emptyCubeTexture) {
  16709. this._releaseTexture(this._emptyCubeTexture);
  16710. this._emptyCubeTexture = null;
  16711. }
  16712. // Rescale PP
  16713. if (this._rescalePostProcess) {
  16714. this._rescalePostProcess.dispose();
  16715. }
  16716. // Release scenes
  16717. while (this.scenes.length) {
  16718. this.scenes[0].dispose();
  16719. }
  16720. // Release audio engine
  16721. if (Engine.audioEngine) {
  16722. Engine.audioEngine.dispose();
  16723. }
  16724. // Release effects
  16725. this.releaseEffects();
  16726. // Unbind
  16727. this.unbindAllAttributes();
  16728. this._boundUniforms = [];
  16729. if (this._dummyFramebuffer) {
  16730. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16731. }
  16732. //WebVR
  16733. this.disableVR();
  16734. // Events
  16735. if (BABYLON.Tools.IsWindowObjectExist()) {
  16736. window.removeEventListener("blur", this._onBlur);
  16737. window.removeEventListener("focus", this._onFocus);
  16738. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16739. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16740. if (this._renderingCanvas) {
  16741. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16742. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16743. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16744. if (!this._doNotHandleContextLost) {
  16745. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16746. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16747. }
  16748. }
  16749. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16750. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16751. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16752. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16753. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16754. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16755. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16756. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16757. if (this._onVrDisplayConnect) {
  16758. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16759. if (this._onVrDisplayDisconnect) {
  16760. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16761. }
  16762. if (this._onVrDisplayPresentChange) {
  16763. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16764. }
  16765. this._onVrDisplayConnect = null;
  16766. this._onVrDisplayDisconnect = null;
  16767. }
  16768. }
  16769. // Remove from Instances
  16770. var index = Engine.Instances.indexOf(this);
  16771. if (index >= 0) {
  16772. Engine.Instances.splice(index, 1);
  16773. }
  16774. this._workingCanvas = null;
  16775. this._workingContext = null;
  16776. this._currentBufferPointers = [];
  16777. this._renderingCanvas = null;
  16778. this._currentProgram = null;
  16779. this._bindedRenderFunction = null;
  16780. this.onResizeObservable.clear();
  16781. this.onCanvasBlurObservable.clear();
  16782. this.onCanvasFocusObservable.clear();
  16783. this.onCanvasPointerOutObservable.clear();
  16784. this.onBeginFrameObservable.clear();
  16785. this.onEndFrameObservable.clear();
  16786. BABYLON.Effect.ResetCache();
  16787. // Abort active requests
  16788. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16789. var request = _a[_i];
  16790. request.abort();
  16791. }
  16792. };
  16793. // Loading screen
  16794. /**
  16795. * Display the loading screen
  16796. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16797. */
  16798. Engine.prototype.displayLoadingUI = function () {
  16799. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16800. return;
  16801. }
  16802. var loadingScreen = this.loadingScreen;
  16803. if (loadingScreen) {
  16804. loadingScreen.displayLoadingUI();
  16805. }
  16806. };
  16807. /**
  16808. * Hide the loading screen
  16809. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16810. */
  16811. Engine.prototype.hideLoadingUI = function () {
  16812. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16813. return;
  16814. }
  16815. var loadingScreen = this.loadingScreen;
  16816. if (loadingScreen) {
  16817. loadingScreen.hideLoadingUI();
  16818. }
  16819. };
  16820. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16821. /**
  16822. * Gets the current loading screen object
  16823. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16824. */
  16825. get: function () {
  16826. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16827. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16828. return this._loadingScreen;
  16829. },
  16830. /**
  16831. * Sets the current loading screen object
  16832. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16833. */
  16834. set: function (loadingScreen) {
  16835. this._loadingScreen = loadingScreen;
  16836. },
  16837. enumerable: true,
  16838. configurable: true
  16839. });
  16840. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16841. /**
  16842. * Sets the current loading screen text
  16843. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16844. */
  16845. set: function (text) {
  16846. this.loadingScreen.loadingUIText = text;
  16847. },
  16848. enumerable: true,
  16849. configurable: true
  16850. });
  16851. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16852. /**
  16853. * Sets the current loading screen background color
  16854. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16855. */
  16856. set: function (color) {
  16857. this.loadingScreen.loadingUIBackgroundColor = color;
  16858. },
  16859. enumerable: true,
  16860. configurable: true
  16861. });
  16862. /**
  16863. * Attach a new callback raised when context lost event is fired
  16864. * @param callback defines the callback to call
  16865. */
  16866. Engine.prototype.attachContextLostEvent = function (callback) {
  16867. if (this._renderingCanvas) {
  16868. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16869. }
  16870. };
  16871. /**
  16872. * Attach a new callback raised when context restored event is fired
  16873. * @param callback defines the callback to call
  16874. */
  16875. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16876. if (this._renderingCanvas) {
  16877. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16878. }
  16879. };
  16880. /**
  16881. * Gets the source code of the vertex shader associated with a specific webGL program
  16882. * @param program defines the program to use
  16883. * @returns a string containing the source code of the vertex shader associated with the program
  16884. */
  16885. Engine.prototype.getVertexShaderSource = function (program) {
  16886. var shaders = this._gl.getAttachedShaders(program);
  16887. if (!shaders) {
  16888. return null;
  16889. }
  16890. return this._gl.getShaderSource(shaders[0]);
  16891. };
  16892. /**
  16893. * Gets the source code of the fragment shader associated with a specific webGL program
  16894. * @param program defines the program to use
  16895. * @returns a string containing the source code of the fragment shader associated with the program
  16896. */
  16897. Engine.prototype.getFragmentShaderSource = function (program) {
  16898. var shaders = this._gl.getAttachedShaders(program);
  16899. if (!shaders) {
  16900. return null;
  16901. }
  16902. return this._gl.getShaderSource(shaders[1]);
  16903. };
  16904. /**
  16905. * Get the current error code of the webGL context
  16906. * @returns the error code
  16907. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16908. */
  16909. Engine.prototype.getError = function () {
  16910. return this._gl.getError();
  16911. };
  16912. // FPS
  16913. /**
  16914. * Gets the current framerate
  16915. * @returns a number representing the framerate
  16916. */
  16917. Engine.prototype.getFps = function () {
  16918. return this._fps;
  16919. };
  16920. /**
  16921. * Gets the time spent between current and previous frame
  16922. * @returns a number representing the delta time in ms
  16923. */
  16924. Engine.prototype.getDeltaTime = function () {
  16925. return this._deltaTime;
  16926. };
  16927. Engine.prototype._measureFps = function () {
  16928. this._performanceMonitor.sampleFrame();
  16929. this._fps = this._performanceMonitor.averageFPS;
  16930. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16931. };
  16932. /** @hidden */
  16933. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16934. if (faceIndex === void 0) { faceIndex = -1; }
  16935. if (level === void 0) { level = 0; }
  16936. var gl = this._gl;
  16937. if (!this._dummyFramebuffer) {
  16938. var dummy = gl.createFramebuffer();
  16939. if (!dummy) {
  16940. throw new Error("Unable to create dummy framebuffer");
  16941. }
  16942. this._dummyFramebuffer = dummy;
  16943. }
  16944. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16945. if (faceIndex > -1) {
  16946. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16947. }
  16948. else {
  16949. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16950. }
  16951. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16952. var buffer;
  16953. switch (readType) {
  16954. case gl.UNSIGNED_BYTE:
  16955. buffer = new Uint8Array(4 * width * height);
  16956. readType = gl.UNSIGNED_BYTE;
  16957. break;
  16958. default:
  16959. buffer = new Float32Array(4 * width * height);
  16960. readType = gl.FLOAT;
  16961. break;
  16962. }
  16963. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16964. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16965. return buffer;
  16966. };
  16967. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16968. if (this._webGLVersion > 1) {
  16969. return this._caps.colorBufferFloat;
  16970. }
  16971. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16972. };
  16973. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16974. if (this._webGLVersion > 1) {
  16975. return this._caps.colorBufferFloat;
  16976. }
  16977. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16978. };
  16979. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16980. Engine.prototype._canRenderToFramebuffer = function (type) {
  16981. var gl = this._gl;
  16982. //clear existing errors
  16983. while (gl.getError() !== gl.NO_ERROR) { }
  16984. var successful = true;
  16985. var texture = gl.createTexture();
  16986. gl.bindTexture(gl.TEXTURE_2D, texture);
  16987. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16988. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16989. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16990. var fb = gl.createFramebuffer();
  16991. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16992. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16993. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16994. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16995. successful = successful && (gl.getError() === gl.NO_ERROR);
  16996. //try render by clearing frame buffer's color buffer
  16997. if (successful) {
  16998. gl.clear(gl.COLOR_BUFFER_BIT);
  16999. successful = successful && (gl.getError() === gl.NO_ERROR);
  17000. }
  17001. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17002. if (successful) {
  17003. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17004. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17005. var readFormat = gl.RGBA;
  17006. var readType = gl.UNSIGNED_BYTE;
  17007. var buffer = new Uint8Array(4);
  17008. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17009. successful = successful && (gl.getError() === gl.NO_ERROR);
  17010. }
  17011. //clean up
  17012. gl.deleteTexture(texture);
  17013. gl.deleteFramebuffer(fb);
  17014. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17015. //clear accumulated errors
  17016. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17017. return successful;
  17018. };
  17019. /** @hidden */
  17020. Engine.prototype._getWebGLTextureType = function (type) {
  17021. if (this._webGLVersion === 1) {
  17022. switch (type) {
  17023. case Engine.TEXTURETYPE_FLOAT:
  17024. return this._gl.FLOAT;
  17025. case Engine.TEXTURETYPE_HALF_FLOAT:
  17026. return this._gl.HALF_FLOAT_OES;
  17027. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17028. return this._gl.UNSIGNED_BYTE;
  17029. }
  17030. return this._gl.UNSIGNED_BYTE;
  17031. }
  17032. switch (type) {
  17033. case Engine.TEXTURETYPE_BYTE:
  17034. return this._gl.BYTE;
  17035. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17036. return this._gl.UNSIGNED_BYTE;
  17037. case Engine.TEXTURETYPE_SHORT:
  17038. return this._gl.SHORT;
  17039. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17040. return this._gl.UNSIGNED_SHORT;
  17041. case Engine.TEXTURETYPE_INT:
  17042. return this._gl.INT;
  17043. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17044. return this._gl.UNSIGNED_INT;
  17045. case Engine.TEXTURETYPE_FLOAT:
  17046. return this._gl.FLOAT;
  17047. case Engine.TEXTURETYPE_HALF_FLOAT:
  17048. return this._gl.HALF_FLOAT;
  17049. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17050. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17051. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17052. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17053. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17054. return this._gl.UNSIGNED_SHORT_5_6_5;
  17055. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17056. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17057. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17058. return this._gl.UNSIGNED_INT_24_8;
  17059. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17060. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17061. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17062. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17063. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17064. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17065. }
  17066. return this._gl.UNSIGNED_BYTE;
  17067. };
  17068. ;
  17069. Engine.prototype._getInternalFormat = function (format) {
  17070. var internalFormat = this._gl.RGBA;
  17071. switch (format) {
  17072. case Engine.TEXTUREFORMAT_ALPHA:
  17073. internalFormat = this._gl.ALPHA;
  17074. break;
  17075. case Engine.TEXTUREFORMAT_LUMINANCE:
  17076. internalFormat = this._gl.LUMINANCE;
  17077. break;
  17078. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17079. internalFormat = this._gl.LUMINANCE_ALPHA;
  17080. break;
  17081. case Engine.TEXTUREFORMAT_RED:
  17082. internalFormat = this._gl.RED;
  17083. break;
  17084. case Engine.TEXTUREFORMAT_RG:
  17085. internalFormat = this._gl.RG;
  17086. break;
  17087. case Engine.TEXTUREFORMAT_RGB:
  17088. internalFormat = this._gl.RGB;
  17089. break;
  17090. case Engine.TEXTUREFORMAT_RGBA:
  17091. internalFormat = this._gl.RGBA;
  17092. break;
  17093. }
  17094. if (this._webGLVersion > 1) {
  17095. switch (format) {
  17096. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17097. internalFormat = this._gl.RED_INTEGER;
  17098. break;
  17099. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17100. internalFormat = this._gl.RG_INTEGER;
  17101. break;
  17102. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17103. internalFormat = this._gl.RGB_INTEGER;
  17104. break;
  17105. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17106. internalFormat = this._gl.RGBA_INTEGER;
  17107. break;
  17108. }
  17109. }
  17110. return internalFormat;
  17111. };
  17112. /** @hidden */
  17113. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17114. if (this._webGLVersion === 1) {
  17115. if (format !== undefined) {
  17116. switch (format) {
  17117. case Engine.TEXTUREFORMAT_ALPHA:
  17118. return this._gl.ALPHA;
  17119. case Engine.TEXTUREFORMAT_LUMINANCE:
  17120. return this._gl.LUMINANCE;
  17121. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17122. return this._gl.LUMINANCE_ALPHA;
  17123. }
  17124. }
  17125. return this._gl.RGBA;
  17126. }
  17127. switch (type) {
  17128. case Engine.TEXTURETYPE_BYTE:
  17129. switch (format) {
  17130. case Engine.TEXTUREFORMAT_RED:
  17131. return this._gl.R8_SNORM;
  17132. case Engine.TEXTUREFORMAT_RG:
  17133. return this._gl.RG8_SNORM;
  17134. case Engine.TEXTUREFORMAT_RGB:
  17135. return this._gl.RGB8_SNORM;
  17136. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17137. return this._gl.R8I;
  17138. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17139. return this._gl.RG8I;
  17140. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17141. return this._gl.RGB8I;
  17142. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17143. return this._gl.RGBA8I;
  17144. default:
  17145. return this._gl.RGBA8_SNORM;
  17146. }
  17147. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17148. switch (format) {
  17149. case Engine.TEXTUREFORMAT_RED:
  17150. return this._gl.R8;
  17151. case Engine.TEXTUREFORMAT_RG:
  17152. return this._gl.RG8;
  17153. case Engine.TEXTUREFORMAT_RGB:
  17154. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17155. case Engine.TEXTUREFORMAT_RGBA:
  17156. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17157. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17158. return this._gl.R8UI;
  17159. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17160. return this._gl.RG8UI;
  17161. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17162. return this._gl.RGB8UI;
  17163. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17164. return this._gl.RGBA8UI;
  17165. default:
  17166. return this._gl.RGBA8;
  17167. }
  17168. case Engine.TEXTURETYPE_SHORT:
  17169. switch (format) {
  17170. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17171. return this._gl.R16I;
  17172. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17173. return this._gl.RG16I;
  17174. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17175. return this._gl.RGB16I;
  17176. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17177. return this._gl.RGBA16I;
  17178. default:
  17179. return this._gl.RGBA16I;
  17180. }
  17181. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17182. switch (format) {
  17183. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17184. return this._gl.R16UI;
  17185. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17186. return this._gl.RG16UI;
  17187. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17188. return this._gl.RGB16UI;
  17189. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17190. return this._gl.RGBA16UI;
  17191. default:
  17192. return this._gl.RGBA16UI;
  17193. }
  17194. case Engine.TEXTURETYPE_INT:
  17195. switch (format) {
  17196. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17197. return this._gl.R32I;
  17198. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17199. return this._gl.RG32I;
  17200. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17201. return this._gl.RGB32I;
  17202. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17203. return this._gl.RGBA32I;
  17204. default:
  17205. return this._gl.RGBA32I;
  17206. }
  17207. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17208. switch (format) {
  17209. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17210. return this._gl.R32UI;
  17211. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17212. return this._gl.RG32UI;
  17213. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17214. return this._gl.RGB32UI;
  17215. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17216. return this._gl.RGBA32UI;
  17217. default:
  17218. return this._gl.RGBA32UI;
  17219. }
  17220. case Engine.TEXTURETYPE_FLOAT:
  17221. switch (format) {
  17222. case Engine.TEXTUREFORMAT_RED:
  17223. return this._gl.R32F; // By default. Other possibility is R16F.
  17224. case Engine.TEXTUREFORMAT_RG:
  17225. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17226. case Engine.TEXTUREFORMAT_RGB:
  17227. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17228. case Engine.TEXTUREFORMAT_RGBA:
  17229. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17230. default:
  17231. return this._gl.RGBA32F;
  17232. }
  17233. case Engine.TEXTURETYPE_HALF_FLOAT:
  17234. switch (format) {
  17235. case Engine.TEXTUREFORMAT_RED:
  17236. return this._gl.R16F;
  17237. case Engine.TEXTUREFORMAT_RG:
  17238. return this._gl.RG16F;
  17239. case Engine.TEXTUREFORMAT_RGB:
  17240. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17241. case Engine.TEXTUREFORMAT_RGBA:
  17242. return this._gl.RGBA16F;
  17243. default:
  17244. return this._gl.RGBA16F;
  17245. }
  17246. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17247. return this._gl.RGB565;
  17248. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17249. return this._gl.R11F_G11F_B10F;
  17250. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17251. return this._gl.RGB9_E5;
  17252. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17253. return this._gl.RGBA4;
  17254. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17255. return this._gl.RGB5_A1;
  17256. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17257. switch (format) {
  17258. case Engine.TEXTUREFORMAT_RGBA:
  17259. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17260. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17261. return this._gl.RGB10_A2UI;
  17262. default:
  17263. return this._gl.RGB10_A2;
  17264. }
  17265. }
  17266. return this._gl.RGBA8;
  17267. };
  17268. ;
  17269. /** @hidden */
  17270. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17271. if (type === Engine.TEXTURETYPE_FLOAT) {
  17272. return this._gl.RGBA32F;
  17273. }
  17274. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17275. return this._gl.RGBA16F;
  17276. }
  17277. return this._gl.RGBA8;
  17278. };
  17279. ;
  17280. /** @hidden */
  17281. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17282. var _this = this;
  17283. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17284. this._activeRequests.push(request);
  17285. request.onCompleteObservable.add(function (request) {
  17286. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17287. });
  17288. return request;
  17289. };
  17290. /** @hidden */
  17291. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17292. var _this = this;
  17293. return new Promise(function (resolve, reject) {
  17294. _this._loadFile(url, function (data) {
  17295. resolve(data);
  17296. }, undefined, database, useArrayBuffer, function (request, exception) {
  17297. reject(exception);
  17298. });
  17299. });
  17300. };
  17301. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17302. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17303. var onload = function (data) {
  17304. loadedFiles[index] = data;
  17305. loadedFiles._internalCount++;
  17306. if (loadedFiles._internalCount === 6) {
  17307. onfinish(loadedFiles);
  17308. }
  17309. };
  17310. var onerror = function (request, exception) {
  17311. if (onErrorCallBack && request) {
  17312. onErrorCallBack(request.status + " " + request.statusText, exception);
  17313. }
  17314. };
  17315. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17316. };
  17317. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17318. if (onError === void 0) { onError = null; }
  17319. var loadedFiles = [];
  17320. loadedFiles._internalCount = 0;
  17321. for (var index = 0; index < 6; index++) {
  17322. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17323. }
  17324. };
  17325. // Statics
  17326. /**
  17327. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17328. * @returns true if the engine can be created
  17329. * @ignorenaming
  17330. */
  17331. Engine.isSupported = function () {
  17332. try {
  17333. var tempcanvas = document.createElement("canvas");
  17334. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17335. return gl != null && !!window.WebGLRenderingContext;
  17336. }
  17337. catch (e) {
  17338. return false;
  17339. }
  17340. };
  17341. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17342. Engine.ExceptionList = [
  17343. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17344. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17345. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17346. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17347. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17348. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17349. ];
  17350. /** Gets the list of created engines */
  17351. Engine.Instances = new Array();
  17352. /**
  17353. * Hidden
  17354. */
  17355. Engine._TextureLoaders = [];
  17356. // Const statics
  17357. /** Defines that alpha blending is disabled */
  17358. Engine.ALPHA_DISABLE = 0;
  17359. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17360. Engine.ALPHA_ADD = 1;
  17361. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17362. Engine.ALPHA_COMBINE = 2;
  17363. /** Defines that alpha blending to DEST - SRC * DEST */
  17364. Engine.ALPHA_SUBTRACT = 3;
  17365. /** Defines that alpha blending to SRC * DEST */
  17366. Engine.ALPHA_MULTIPLY = 4;
  17367. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17368. Engine.ALPHA_MAXIMIZED = 5;
  17369. /** Defines that alpha blending to SRC + DEST */
  17370. Engine.ALPHA_ONEONE = 6;
  17371. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17372. Engine.ALPHA_PREMULTIPLIED = 7;
  17373. /**
  17374. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17375. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17376. */
  17377. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17378. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17379. Engine.ALPHA_INTERPOLATE = 9;
  17380. /**
  17381. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17382. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17383. */
  17384. Engine.ALPHA_SCREENMODE = 10;
  17385. /** Defines that the ressource is not delayed*/
  17386. Engine.DELAYLOADSTATE_NONE = 0;
  17387. /** Defines that the ressource was successfully delay loaded */
  17388. Engine.DELAYLOADSTATE_LOADED = 1;
  17389. /** Defines that the ressource is currently delay loading */
  17390. Engine.DELAYLOADSTATE_LOADING = 2;
  17391. /** Defines that the ressource is delayed and has not started loading */
  17392. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17393. // Depht or Stencil test Constants.
  17394. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17395. Engine.NEVER = 0x0200;
  17396. /** 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 */
  17397. Engine.ALWAYS = 0x0207;
  17398. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17399. Engine.LESS = 0x0201;
  17400. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17401. Engine.EQUAL = 0x0202;
  17402. /** 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 */
  17403. Engine.LEQUAL = 0x0203;
  17404. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17405. Engine.GREATER = 0x0204;
  17406. /** 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 */
  17407. Engine.GEQUAL = 0x0206;
  17408. /** 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 */
  17409. Engine.NOTEQUAL = 0x0205;
  17410. // Stencil Actions Constants.
  17411. /** Passed to stencilOperation to specify that stencil value must be kept */
  17412. Engine.KEEP = 0x1E00;
  17413. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17414. Engine.REPLACE = 0x1E01;
  17415. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17416. Engine.INCR = 0x1E02;
  17417. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17418. Engine.DECR = 0x1E03;
  17419. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17420. Engine.INVERT = 0x150A;
  17421. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17422. Engine.INCR_WRAP = 0x8507;
  17423. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17424. Engine.DECR_WRAP = 0x8508;
  17425. /** Texture is not repeating outside of 0..1 UVs */
  17426. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17427. /** Texture is repeating outside of 0..1 UVs */
  17428. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17429. /** Texture is repeating and mirrored */
  17430. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17431. /** ALPHA */
  17432. Engine.TEXTUREFORMAT_ALPHA = 0;
  17433. /** LUMINANCE */
  17434. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17435. /** LUMINANCE_ALPHA */
  17436. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17437. /** RGB */
  17438. Engine.TEXTUREFORMAT_RGB = 4;
  17439. /** RGBA */
  17440. Engine.TEXTUREFORMAT_RGBA = 5;
  17441. /** RED */
  17442. Engine.TEXTUREFORMAT_RED = 6;
  17443. /** RED (2nd reference) */
  17444. Engine.TEXTUREFORMAT_R = 6;
  17445. /** RG */
  17446. Engine.TEXTUREFORMAT_RG = 7;
  17447. /** RED_INTEGER */
  17448. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17449. /** RED_INTEGER (2nd reference) */
  17450. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17451. /** RG_INTEGER */
  17452. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17453. /** RGB_INTEGER */
  17454. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17455. /** RGBA_INTEGER */
  17456. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17457. /** UNSIGNED_BYTE */
  17458. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17459. /** UNSIGNED_BYTE (2nd reference) */
  17460. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17461. /** FLOAT */
  17462. Engine.TEXTURETYPE_FLOAT = 1;
  17463. /** HALF_FLOAT */
  17464. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17465. /** BYTE */
  17466. Engine.TEXTURETYPE_BYTE = 3;
  17467. /** SHORT */
  17468. Engine.TEXTURETYPE_SHORT = 4;
  17469. /** UNSIGNED_SHORT */
  17470. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17471. /** INT */
  17472. Engine.TEXTURETYPE_INT = 6;
  17473. /** UNSIGNED_INT */
  17474. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17475. /** UNSIGNED_SHORT_4_4_4_4 */
  17476. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17477. /** UNSIGNED_SHORT_5_5_5_1 */
  17478. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17479. /** UNSIGNED_SHORT_5_6_5 */
  17480. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17481. /** UNSIGNED_INT_2_10_10_10_REV */
  17482. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17483. /** UNSIGNED_INT_24_8 */
  17484. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17485. /** UNSIGNED_INT_10F_11F_11F_REV */
  17486. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17487. /** UNSIGNED_INT_5_9_9_9_REV */
  17488. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17489. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17490. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17491. /** nearest is mag = nearest and min = nearest and mip = linear */
  17492. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17493. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17494. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17495. /** Trilinear is mag = linear and min = linear and mip = linear */
  17496. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17497. /** nearest is mag = nearest and min = nearest and mip = linear */
  17498. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17499. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17500. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17501. /** Trilinear is mag = linear and min = linear and mip = linear */
  17502. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17503. /** mag = nearest and min = nearest and mip = nearest */
  17504. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17505. /** mag = nearest and min = linear and mip = nearest */
  17506. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17507. /** mag = nearest and min = linear and mip = linear */
  17508. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17509. /** mag = nearest and min = linear and mip = none */
  17510. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17511. /** mag = nearest and min = nearest and mip = none */
  17512. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17513. /** mag = linear and min = nearest and mip = nearest */
  17514. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17515. /** mag = linear and min = nearest and mip = linear */
  17516. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17517. /** mag = linear and min = linear and mip = none */
  17518. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17519. /** mag = linear and min = nearest and mip = none */
  17520. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17521. /** Explicit coordinates mode */
  17522. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17523. /** Spherical coordinates mode */
  17524. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17525. /** Planar coordinates mode */
  17526. Engine.TEXTURE_PLANAR_MODE = 2;
  17527. /** Cubic coordinates mode */
  17528. Engine.TEXTURE_CUBIC_MODE = 3;
  17529. /** Projection coordinates mode */
  17530. Engine.TEXTURE_PROJECTION_MODE = 4;
  17531. /** Skybox coordinates mode */
  17532. Engine.TEXTURE_SKYBOX_MODE = 5;
  17533. /** Inverse Cubic coordinates mode */
  17534. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17535. /** Equirectangular coordinates mode */
  17536. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17537. /** Equirectangular Fixed coordinates mode */
  17538. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17539. /** Equirectangular Fixed Mirrored coordinates mode */
  17540. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17541. // Texture rescaling mode
  17542. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17543. Engine.SCALEMODE_FLOOR = 1;
  17544. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17545. Engine.SCALEMODE_NEAREST = 2;
  17546. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17547. Engine.SCALEMODE_CEILING = 3;
  17548. // Updatable statics so stick with vars here
  17549. /**
  17550. * Gets or sets the epsilon value used by collision engine
  17551. */
  17552. Engine.CollisionsEpsilon = 0.001;
  17553. /**
  17554. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17555. */
  17556. Engine.CodeRepository = "src/";
  17557. /**
  17558. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17559. */
  17560. Engine.ShadersRepository = "src/Shaders/";
  17561. return Engine;
  17562. }());
  17563. BABYLON.Engine = Engine;
  17564. })(BABYLON || (BABYLON = {}));
  17565. //# sourceMappingURL=babylon.engine.js.map
  17566. var BABYLON;
  17567. (function (BABYLON) {
  17568. /**
  17569. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17570. */
  17571. var Node = /** @class */ (function () {
  17572. /**
  17573. * Creates a new Node
  17574. * @param {string} name - the name and id to be given to this node
  17575. * @param {BABYLON.Scene} the scene this node will be added to
  17576. */
  17577. function Node(name, scene) {
  17578. if (scene === void 0) { scene = null; }
  17579. /**
  17580. * Gets or sets a string used to store user defined state for the node
  17581. */
  17582. this.state = "";
  17583. /**
  17584. * Gets or sets an object used to store user defined information for the node
  17585. */
  17586. this.metadata = null;
  17587. /**
  17588. * Gets or sets a boolean used to define if the node must be serialized
  17589. */
  17590. this.doNotSerialize = false;
  17591. /** @hidden */
  17592. this._isDisposed = false;
  17593. /**
  17594. * Gets a list of Animations associated with the node
  17595. */
  17596. this.animations = new Array();
  17597. this._ranges = {};
  17598. this._isEnabled = true;
  17599. this._isReady = true;
  17600. /** @hidden */
  17601. this._currentRenderId = -1;
  17602. this._parentRenderId = -1;
  17603. this._childRenderId = -1;
  17604. /** @hidden */
  17605. this._worldMatrix = BABYLON.Matrix.Zero();
  17606. /** @hidden */
  17607. this._worldMatrixDeterminant = 0;
  17608. this._animationPropertiesOverride = null;
  17609. /**
  17610. * An event triggered when the mesh is disposed
  17611. */
  17612. this.onDisposeObservable = new BABYLON.Observable();
  17613. // Behaviors
  17614. this._behaviors = new Array();
  17615. this.name = name;
  17616. this.id = name;
  17617. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17618. this.uniqueId = this._scene.getUniqueId();
  17619. this._initCache();
  17620. this._scene.rootNodes.push(this);
  17621. }
  17622. /**
  17623. * Add a new node constructor
  17624. * @param type defines the type name of the node to construct
  17625. * @param constructorFunc defines the constructor function
  17626. */
  17627. Node.AddNodeConstructor = function (type, constructorFunc) {
  17628. this._NodeConstructors[type] = constructorFunc;
  17629. };
  17630. /**
  17631. * Returns a node constructor based on type name
  17632. * @param type defines the type name
  17633. * @param name defines the new node name
  17634. * @param scene defines the hosting scene
  17635. * @param options defines optional options to transmit to constructors
  17636. * @returns the new constructor or null
  17637. */
  17638. Node.Construct = function (type, name, scene, options) {
  17639. var constructorFunc = this._NodeConstructors[type];
  17640. if (!constructorFunc) {
  17641. return null;
  17642. }
  17643. return constructorFunc(name, scene, options);
  17644. };
  17645. /**
  17646. * Gets a boolean indicating if the node has been disposed
  17647. * @returns true if the node was disposed
  17648. */
  17649. Node.prototype.isDisposed = function () {
  17650. return this._isDisposed;
  17651. };
  17652. Object.defineProperty(Node.prototype, "parent", {
  17653. get: function () {
  17654. return this._parentNode;
  17655. },
  17656. /**
  17657. * Gets or sets the parent of the node
  17658. */
  17659. set: function (parent) {
  17660. if (this._parentNode === parent) {
  17661. return;
  17662. }
  17663. var previousParentNode = this._parentNode;
  17664. // Remove self from list of children of parent
  17665. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17666. var index = this._parentNode._children.indexOf(this);
  17667. if (index !== -1) {
  17668. this._parentNode._children.splice(index, 1);
  17669. }
  17670. if (!parent) {
  17671. // Need to add this node to the rootNodes
  17672. this._scene.rootNodes.push(this);
  17673. }
  17674. }
  17675. // Store new parent
  17676. this._parentNode = parent;
  17677. // Add as child to new parent
  17678. if (this._parentNode) {
  17679. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17680. this._parentNode._children = new Array();
  17681. }
  17682. this._parentNode._children.push(this);
  17683. if (!previousParentNode) {
  17684. // Need to remove from rootNodes
  17685. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17686. if (rootNodeIndex > -1) {
  17687. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17688. }
  17689. }
  17690. }
  17691. },
  17692. enumerable: true,
  17693. configurable: true
  17694. });
  17695. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17696. /**
  17697. * Gets or sets the animation properties override
  17698. */
  17699. get: function () {
  17700. if (!this._animationPropertiesOverride) {
  17701. return this._scene.animationPropertiesOverride;
  17702. }
  17703. return this._animationPropertiesOverride;
  17704. },
  17705. set: function (value) {
  17706. this._animationPropertiesOverride = value;
  17707. },
  17708. enumerable: true,
  17709. configurable: true
  17710. });
  17711. /**
  17712. * Gets a string idenfifying the name of the class
  17713. * @returns "Node" string
  17714. */
  17715. Node.prototype.getClassName = function () {
  17716. return "Node";
  17717. };
  17718. Object.defineProperty(Node.prototype, "onDispose", {
  17719. /**
  17720. * Sets a callback that will be raised when the node will be disposed
  17721. */
  17722. set: function (callback) {
  17723. if (this._onDisposeObserver) {
  17724. this.onDisposeObservable.remove(this._onDisposeObserver);
  17725. }
  17726. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. /**
  17732. * Gets the scene of the node
  17733. * @returns a {BABYLON.Scene}
  17734. */
  17735. Node.prototype.getScene = function () {
  17736. return this._scene;
  17737. };
  17738. /**
  17739. * Gets the engine of the node
  17740. * @returns a {BABYLON.Engine}
  17741. */
  17742. Node.prototype.getEngine = function () {
  17743. return this._scene.getEngine();
  17744. };
  17745. /**
  17746. * Attach a behavior to the node
  17747. * @see http://doc.babylonjs.com/features/behaviour
  17748. * @param behavior defines the behavior to attach
  17749. * @returns the current Node
  17750. */
  17751. Node.prototype.addBehavior = function (behavior) {
  17752. var _this = this;
  17753. var index = this._behaviors.indexOf(behavior);
  17754. if (index !== -1) {
  17755. return this;
  17756. }
  17757. behavior.init();
  17758. if (this._scene.isLoading) {
  17759. // We defer the attach when the scene will be loaded
  17760. this._scene.onDataLoadedObservable.addOnce(function () {
  17761. behavior.attach(_this);
  17762. });
  17763. }
  17764. else {
  17765. behavior.attach(this);
  17766. }
  17767. this._behaviors.push(behavior);
  17768. return this;
  17769. };
  17770. /**
  17771. * Remove an attached behavior
  17772. * @see http://doc.babylonjs.com/features/behaviour
  17773. * @param behavior defines the behavior to attach
  17774. * @returns the current Node
  17775. */
  17776. Node.prototype.removeBehavior = function (behavior) {
  17777. var index = this._behaviors.indexOf(behavior);
  17778. if (index === -1) {
  17779. return this;
  17780. }
  17781. this._behaviors[index].detach();
  17782. this._behaviors.splice(index, 1);
  17783. return this;
  17784. };
  17785. Object.defineProperty(Node.prototype, "behaviors", {
  17786. /**
  17787. * Gets the list of attached behaviors
  17788. * @see http://doc.babylonjs.com/features/behaviour
  17789. */
  17790. get: function () {
  17791. return this._behaviors;
  17792. },
  17793. enumerable: true,
  17794. configurable: true
  17795. });
  17796. /**
  17797. * Gets an attached behavior by name
  17798. * @param name defines the name of the behavior to look for
  17799. * @see http://doc.babylonjs.com/features/behaviour
  17800. * @returns null if behavior was not found else the requested behavior
  17801. */
  17802. Node.prototype.getBehaviorByName = function (name) {
  17803. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17804. var behavior = _a[_i];
  17805. if (behavior.name === name) {
  17806. return behavior;
  17807. }
  17808. }
  17809. return null;
  17810. };
  17811. /**
  17812. * Returns the latest update of the World matrix
  17813. * @returns a Matrix
  17814. */
  17815. Node.prototype.getWorldMatrix = function () {
  17816. if (this._currentRenderId !== this._scene.getRenderId()) {
  17817. this.computeWorldMatrix();
  17818. }
  17819. return this._worldMatrix;
  17820. };
  17821. /** @hidden */
  17822. Node.prototype._getWorldMatrixDeterminant = function () {
  17823. return this._worldMatrixDeterminant;
  17824. };
  17825. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17826. /**
  17827. * Returns directly the latest state of the mesh World matrix.
  17828. * A Matrix is returned.
  17829. */
  17830. get: function () {
  17831. return this._worldMatrix;
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. // override it in derived class if you add new variables to the cache
  17837. // and call the parent class method
  17838. /** @hidden */
  17839. Node.prototype._initCache = function () {
  17840. this._cache = {};
  17841. this._cache.parent = undefined;
  17842. };
  17843. /** @hidden */
  17844. Node.prototype.updateCache = function (force) {
  17845. if (!force && this.isSynchronized())
  17846. return;
  17847. this._cache.parent = this.parent;
  17848. this._updateCache();
  17849. };
  17850. // override it in derived class if you add new variables to the cache
  17851. // and call the parent class method if !ignoreParentClass
  17852. /** @hidden */
  17853. Node.prototype._updateCache = function (ignoreParentClass) {
  17854. };
  17855. // override it in derived class if you add new variables to the cache
  17856. /** @hidden */
  17857. Node.prototype._isSynchronized = function () {
  17858. return true;
  17859. };
  17860. /** @hidden */
  17861. Node.prototype._markSyncedWithParent = function () {
  17862. if (this._parentNode) {
  17863. this._parentRenderId = this._parentNode._childRenderId;
  17864. }
  17865. };
  17866. /** @hidden */
  17867. Node.prototype.isSynchronizedWithParent = function () {
  17868. if (!this._parentNode) {
  17869. return true;
  17870. }
  17871. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17872. return false;
  17873. }
  17874. return this._parentNode.isSynchronized();
  17875. };
  17876. /** @hidden */
  17877. Node.prototype.isSynchronized = function () {
  17878. if (this._cache.parent != this._parentNode) {
  17879. this._cache.parent = this._parentNode;
  17880. return false;
  17881. }
  17882. if (!this.isSynchronizedWithParent()) {
  17883. return false;
  17884. }
  17885. return this._isSynchronized();
  17886. };
  17887. /**
  17888. * Is this node ready to be used/rendered
  17889. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17890. * @return true if the node is ready
  17891. */
  17892. Node.prototype.isReady = function (completeCheck) {
  17893. if (completeCheck === void 0) { completeCheck = false; }
  17894. return this._isReady;
  17895. };
  17896. /**
  17897. * Is this node enabled?
  17898. * 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
  17899. * @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
  17900. * @return whether this node (and its parent) is enabled
  17901. */
  17902. Node.prototype.isEnabled = function (checkAncestors) {
  17903. if (checkAncestors === void 0) { checkAncestors = true; }
  17904. if (checkAncestors === false) {
  17905. return this._isEnabled;
  17906. }
  17907. if (this._isEnabled === false) {
  17908. return false;
  17909. }
  17910. if (this._parentNode !== undefined && this._parentNode !== null) {
  17911. return this._parentNode.isEnabled(checkAncestors);
  17912. }
  17913. return true;
  17914. };
  17915. /**
  17916. * Set the enabled state of this node
  17917. * @param value defines the new enabled state
  17918. */
  17919. Node.prototype.setEnabled = function (value) {
  17920. this._isEnabled = value;
  17921. };
  17922. /**
  17923. * Is this node a descendant of the given node?
  17924. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17925. * @param ancestor defines the parent node to inspect
  17926. * @returns a boolean indicating if this node is a descendant of the given node
  17927. */
  17928. Node.prototype.isDescendantOf = function (ancestor) {
  17929. if (this.parent) {
  17930. if (this.parent === ancestor) {
  17931. return true;
  17932. }
  17933. return this.parent.isDescendantOf(ancestor);
  17934. }
  17935. return false;
  17936. };
  17937. /** @hidden */
  17938. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17939. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17940. if (!this._children) {
  17941. return;
  17942. }
  17943. for (var index = 0; index < this._children.length; index++) {
  17944. var item = this._children[index];
  17945. if (!predicate || predicate(item)) {
  17946. results.push(item);
  17947. }
  17948. if (!directDescendantsOnly) {
  17949. item._getDescendants(results, false, predicate);
  17950. }
  17951. }
  17952. };
  17953. /**
  17954. * Will return all nodes that have this node as ascendant
  17955. * @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
  17956. * @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
  17957. * @return all children nodes of all types
  17958. */
  17959. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17960. var results = new Array();
  17961. this._getDescendants(results, directDescendantsOnly, predicate);
  17962. return results;
  17963. };
  17964. /**
  17965. * Get all child-meshes of this node
  17966. * @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
  17967. * @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
  17968. * @returns an array of {BABYLON.AbstractMesh}
  17969. */
  17970. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17971. var results = [];
  17972. this._getDescendants(results, directDescendantsOnly, function (node) {
  17973. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17974. });
  17975. return results;
  17976. };
  17977. /**
  17978. * Get all child-transformNodes of this node
  17979. * @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
  17980. * @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
  17981. * @returns an array of {BABYLON.TransformNode}
  17982. */
  17983. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17984. var results = [];
  17985. this._getDescendants(results, directDescendantsOnly, function (node) {
  17986. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17987. });
  17988. return results;
  17989. };
  17990. /**
  17991. * Get all direct children of this node
  17992. * @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
  17993. * @returns an array of {BABYLON.Node}
  17994. */
  17995. Node.prototype.getChildren = function (predicate) {
  17996. if (!predicate) {
  17997. return this._children;
  17998. }
  17999. return this.getDescendants(true, predicate);
  18000. };
  18001. /** @hidden */
  18002. Node.prototype._setReady = function (state) {
  18003. if (state === this._isReady) {
  18004. return;
  18005. }
  18006. if (!state) {
  18007. this._isReady = false;
  18008. return;
  18009. }
  18010. if (this.onReady) {
  18011. this.onReady(this);
  18012. }
  18013. this._isReady = true;
  18014. };
  18015. /**
  18016. * Get an animation by name
  18017. * @param name defines the name of the animation to look for
  18018. * @returns null if not found else the requested animation
  18019. */
  18020. Node.prototype.getAnimationByName = function (name) {
  18021. for (var i = 0; i < this.animations.length; i++) {
  18022. var animation = this.animations[i];
  18023. if (animation.name === name) {
  18024. return animation;
  18025. }
  18026. }
  18027. return null;
  18028. };
  18029. /**
  18030. * Creates an animation range for this node
  18031. * @param name defines the name of the range
  18032. * @param from defines the starting key
  18033. * @param to defines the end key
  18034. */
  18035. Node.prototype.createAnimationRange = function (name, from, to) {
  18036. // check name not already in use
  18037. if (!this._ranges[name]) {
  18038. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18039. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18040. if (this.animations[i]) {
  18041. this.animations[i].createRange(name, from, to);
  18042. }
  18043. }
  18044. }
  18045. };
  18046. /**
  18047. * Delete a specific animation range
  18048. * @param name defines the name of the range to delete
  18049. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18050. */
  18051. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18052. if (deleteFrames === void 0) { deleteFrames = true; }
  18053. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18054. if (this.animations[i]) {
  18055. this.animations[i].deleteRange(name, deleteFrames);
  18056. }
  18057. }
  18058. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18059. };
  18060. /**
  18061. * Get an animation range by name
  18062. * @param name defines the name of the animation range to look for
  18063. * @returns null if not found else the requested animation range
  18064. */
  18065. Node.prototype.getAnimationRange = function (name) {
  18066. return this._ranges[name];
  18067. };
  18068. /**
  18069. * Will start the animation sequence
  18070. * @param name defines the range frames for animation sequence
  18071. * @param loop defines if the animation should loop (false by default)
  18072. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18073. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18074. * @returns the object created for this animation. If range does not exist, it will return null
  18075. */
  18076. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18077. var range = this.getAnimationRange(name);
  18078. if (!range) {
  18079. return null;
  18080. }
  18081. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18082. };
  18083. /**
  18084. * Serialize animation ranges into a JSON compatible object
  18085. * @returns serialization object
  18086. */
  18087. Node.prototype.serializeAnimationRanges = function () {
  18088. var serializationRanges = [];
  18089. for (var name in this._ranges) {
  18090. var localRange = this._ranges[name];
  18091. if (!localRange) {
  18092. continue;
  18093. }
  18094. var range = {};
  18095. range.name = name;
  18096. range.from = localRange.from;
  18097. range.to = localRange.to;
  18098. serializationRanges.push(range);
  18099. }
  18100. return serializationRanges;
  18101. };
  18102. /**
  18103. * Computes the world matrix of the node
  18104. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18105. * @returns the world matrix
  18106. */
  18107. Node.prototype.computeWorldMatrix = function (force) {
  18108. if (!this._worldMatrix) {
  18109. this._worldMatrix = BABYLON.Matrix.Identity();
  18110. }
  18111. return this._worldMatrix;
  18112. };
  18113. /**
  18114. * Releases resources associated with this node.
  18115. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18116. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18117. */
  18118. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18119. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18120. if (!doNotRecurse) {
  18121. var nodes = this.getDescendants(true);
  18122. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18123. var node = nodes_1[_i];
  18124. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18125. }
  18126. }
  18127. else {
  18128. var transformNodes = this.getChildTransformNodes(true);
  18129. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18130. var transformNode = transformNodes_1[_a];
  18131. transformNode.parent = null;
  18132. transformNode.computeWorldMatrix(true);
  18133. }
  18134. }
  18135. if (!this.parent) {
  18136. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18137. if (rootNodeIndex > -1) {
  18138. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18139. }
  18140. }
  18141. else {
  18142. this.parent = null;
  18143. }
  18144. // Callback
  18145. this.onDisposeObservable.notifyObservers(this);
  18146. this.onDisposeObservable.clear();
  18147. // Behaviors
  18148. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18149. var behavior = _c[_b];
  18150. behavior.detach();
  18151. }
  18152. this._behaviors = [];
  18153. this._isDisposed = true;
  18154. };
  18155. /**
  18156. * Parse animation range data from a serialization object and store them into a given node
  18157. * @param node defines where to store the animation ranges
  18158. * @param parsedNode defines the serialization object to read data from
  18159. * @param scene defines the hosting scene
  18160. */
  18161. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18162. if (parsedNode.ranges) {
  18163. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18164. var data = parsedNode.ranges[index];
  18165. node.createAnimationRange(data.name, data.from, data.to);
  18166. }
  18167. }
  18168. };
  18169. Node._NodeConstructors = {};
  18170. __decorate([
  18171. BABYLON.serialize()
  18172. ], Node.prototype, "name", void 0);
  18173. __decorate([
  18174. BABYLON.serialize()
  18175. ], Node.prototype, "id", void 0);
  18176. __decorate([
  18177. BABYLON.serialize()
  18178. ], Node.prototype, "uniqueId", void 0);
  18179. __decorate([
  18180. BABYLON.serialize()
  18181. ], Node.prototype, "state", void 0);
  18182. __decorate([
  18183. BABYLON.serialize()
  18184. ], Node.prototype, "metadata", void 0);
  18185. return Node;
  18186. }());
  18187. BABYLON.Node = Node;
  18188. })(BABYLON || (BABYLON = {}));
  18189. //# sourceMappingURL=babylon.node.js.map
  18190. var BABYLON;
  18191. (function (BABYLON) {
  18192. // This matrix is used as a value to reset the bounding box.
  18193. var _identityMatrix = BABYLON.Matrix.Identity();
  18194. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18195. var BoundingSphere = /** @class */ (function () {
  18196. /**
  18197. * Creates a new bounding sphere
  18198. * @param min defines the minimum vector (in local space)
  18199. * @param max defines the maximum vector (in local space)
  18200. */
  18201. function BoundingSphere(min, max) {
  18202. this.center = BABYLON.Vector3.Zero();
  18203. this.centerWorld = BABYLON.Vector3.Zero();
  18204. this.reConstruct(min, max);
  18205. }
  18206. /**
  18207. * Recreates the entire bounding sphere from scratch
  18208. * @param min defines the new minimum vector (in local space)
  18209. * @param max defines the new maximum vector (in local space)
  18210. */
  18211. BoundingSphere.prototype.reConstruct = function (min, max) {
  18212. this.minimum = min.clone();
  18213. this.maximum = max.clone();
  18214. var distance = BABYLON.Vector3.Distance(min, max);
  18215. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18216. this.radius = distance * 0.5;
  18217. this.centerWorld.set(0, 0, 0);
  18218. this._update(_identityMatrix);
  18219. };
  18220. /**
  18221. * Scale the current bounding sphere by applying a scale factor
  18222. * @param factor defines the scale factor to apply
  18223. * @returns the current bounding box
  18224. */
  18225. BoundingSphere.prototype.scale = function (factor) {
  18226. var newRadius = this.radius * factor;
  18227. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18228. var min = this.center.subtract(_tempRadiusVector);
  18229. var max = this.center.add(_tempRadiusVector);
  18230. this.reConstruct(min, max);
  18231. return this;
  18232. };
  18233. // Methods
  18234. /** @hidden */
  18235. BoundingSphere.prototype._update = function (world) {
  18236. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18237. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18238. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18239. };
  18240. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18241. for (var i = 0; i < 6; i++) {
  18242. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18243. return false;
  18244. }
  18245. return true;
  18246. };
  18247. BoundingSphere.prototype.intersectsPoint = function (point) {
  18248. var x = this.centerWorld.x - point.x;
  18249. var y = this.centerWorld.y - point.y;
  18250. var z = this.centerWorld.z - point.z;
  18251. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18252. if (this.radiusWorld < distance)
  18253. return false;
  18254. return true;
  18255. };
  18256. // Statics
  18257. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18258. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18259. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18260. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18261. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18262. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18263. return false;
  18264. return true;
  18265. };
  18266. return BoundingSphere;
  18267. }());
  18268. BABYLON.BoundingSphere = BoundingSphere;
  18269. })(BABYLON || (BABYLON = {}));
  18270. //# sourceMappingURL=babylon.boundingSphere.js.map
  18271. var BABYLON;
  18272. (function (BABYLON) {
  18273. var BoundingBox = /** @class */ (function () {
  18274. /**
  18275. * Creates a new bounding box
  18276. * @param min defines the minimum vector (in local space)
  18277. * @param max defines the maximum vector (in local space)
  18278. */
  18279. function BoundingBox(min, max) {
  18280. this.vectorsWorld = new Array();
  18281. this.reConstruct(min, max);
  18282. }
  18283. // Methods
  18284. /**
  18285. * Recreates the entire bounding box from scratch
  18286. * @param min defines the new minimum vector (in local space)
  18287. * @param max defines the new maximum vector (in local space)
  18288. */
  18289. BoundingBox.prototype.reConstruct = function (min, max) {
  18290. this.minimum = min.clone();
  18291. this.maximum = max.clone();
  18292. // Bounding vectors
  18293. this.vectors = [
  18294. this.minimum.clone(),
  18295. this.maximum.clone(),
  18296. this.minimum.clone(),
  18297. this.minimum.clone(),
  18298. this.minimum.clone(),
  18299. this.maximum.clone(),
  18300. this.maximum.clone(),
  18301. this.maximum.clone()
  18302. ];
  18303. this.vectors[2].x = this.maximum.x;
  18304. this.vectors[3].y = this.maximum.y;
  18305. this.vectors[4].z = this.maximum.z;
  18306. this.vectors[5].z = this.minimum.z;
  18307. this.vectors[6].x = this.minimum.x;
  18308. this.vectors[7].y = this.minimum.y;
  18309. // OBB
  18310. this.center = this.maximum.add(this.minimum).scale(0.5);
  18311. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18312. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18313. // World
  18314. for (var index = 0; index < this.vectors.length; index++) {
  18315. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18316. }
  18317. this.minimumWorld = BABYLON.Vector3.Zero();
  18318. this.maximumWorld = BABYLON.Vector3.Zero();
  18319. this.centerWorld = BABYLON.Vector3.Zero();
  18320. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18321. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18322. };
  18323. /**
  18324. * Scale the current bounding box by applying a scale factor
  18325. * @param factor defines the scale factor to apply
  18326. * @returns the current bounding box
  18327. */
  18328. BoundingBox.prototype.scale = function (factor) {
  18329. var diff = this.maximum.subtract(this.minimum);
  18330. var distance = diff.length() * factor;
  18331. diff.normalize();
  18332. var newRadius = diff.scale(distance / 2);
  18333. var min = this.center.subtract(newRadius);
  18334. var max = this.center.add(newRadius);
  18335. this.reConstruct(min, max);
  18336. return this;
  18337. };
  18338. BoundingBox.prototype.getWorldMatrix = function () {
  18339. return this._worldMatrix;
  18340. };
  18341. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18342. this._worldMatrix.copyFrom(matrix);
  18343. return this;
  18344. };
  18345. /** @hidden */
  18346. BoundingBox.prototype._update = function (world) {
  18347. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18348. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18349. for (var index = 0; index < this.vectors.length; index++) {
  18350. var v = this.vectorsWorld[index];
  18351. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18352. if (v.x < this.minimumWorld.x)
  18353. this.minimumWorld.x = v.x;
  18354. if (v.y < this.minimumWorld.y)
  18355. this.minimumWorld.y = v.y;
  18356. if (v.z < this.minimumWorld.z)
  18357. this.minimumWorld.z = v.z;
  18358. if (v.x > this.maximumWorld.x)
  18359. this.maximumWorld.x = v.x;
  18360. if (v.y > this.maximumWorld.y)
  18361. this.maximumWorld.y = v.y;
  18362. if (v.z > this.maximumWorld.z)
  18363. this.maximumWorld.z = v.z;
  18364. }
  18365. // Extend
  18366. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18367. this.extendSizeWorld.scaleInPlace(0.5);
  18368. // OBB
  18369. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18370. this.centerWorld.scaleInPlace(0.5);
  18371. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18372. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18373. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18374. this._worldMatrix = world;
  18375. };
  18376. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18377. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18378. };
  18379. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18380. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18381. };
  18382. BoundingBox.prototype.intersectsPoint = function (point) {
  18383. var delta = -BABYLON.Epsilon;
  18384. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18385. return false;
  18386. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18387. return false;
  18388. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18389. return false;
  18390. return true;
  18391. };
  18392. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18393. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18394. };
  18395. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18396. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18397. return false;
  18398. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18399. return false;
  18400. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18401. return false;
  18402. return true;
  18403. };
  18404. // Statics
  18405. BoundingBox.Intersects = function (box0, box1) {
  18406. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18407. return false;
  18408. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18409. return false;
  18410. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18411. return false;
  18412. return true;
  18413. };
  18414. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18415. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18416. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18417. return (num <= (sphereRadius * sphereRadius));
  18418. };
  18419. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18420. for (var p = 0; p < 6; p++) {
  18421. for (var i = 0; i < 8; i++) {
  18422. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18423. return false;
  18424. }
  18425. }
  18426. }
  18427. return true;
  18428. };
  18429. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18430. for (var p = 0; p < 6; p++) {
  18431. var inCount = 8;
  18432. for (var i = 0; i < 8; i++) {
  18433. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18434. --inCount;
  18435. }
  18436. else {
  18437. break;
  18438. }
  18439. }
  18440. if (inCount === 0)
  18441. return false;
  18442. }
  18443. return true;
  18444. };
  18445. return BoundingBox;
  18446. }());
  18447. BABYLON.BoundingBox = BoundingBox;
  18448. })(BABYLON || (BABYLON = {}));
  18449. //# sourceMappingURL=babylon.boundingBox.js.map
  18450. var BABYLON;
  18451. (function (BABYLON) {
  18452. var computeBoxExtents = function (axis, box) {
  18453. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18454. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18455. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18456. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18457. var r = r0 + r1 + r2;
  18458. return {
  18459. min: p - r,
  18460. max: p + r
  18461. };
  18462. };
  18463. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18464. var axisOverlap = function (axis, box0, box1) {
  18465. var result0 = computeBoxExtents(axis, box0);
  18466. var result1 = computeBoxExtents(axis, box1);
  18467. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18468. };
  18469. var BoundingInfo = /** @class */ (function () {
  18470. function BoundingInfo(minimum, maximum) {
  18471. this.minimum = minimum;
  18472. this.maximum = maximum;
  18473. this._isLocked = false;
  18474. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18475. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18476. }
  18477. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18478. get: function () {
  18479. return this._isLocked;
  18480. },
  18481. set: function (value) {
  18482. this._isLocked = value;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. // Methods
  18488. BoundingInfo.prototype.update = function (world) {
  18489. if (this._isLocked) {
  18490. return;
  18491. }
  18492. this.boundingBox._update(world);
  18493. this.boundingSphere._update(world);
  18494. };
  18495. /**
  18496. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18497. * @param center New center of the bounding info
  18498. * @param extend New extend of the bounding info
  18499. */
  18500. BoundingInfo.prototype.centerOn = function (center, extend) {
  18501. this.minimum = center.subtract(extend);
  18502. this.maximum = center.add(extend);
  18503. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18504. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18505. return this;
  18506. };
  18507. /**
  18508. * Scale the current bounding info by applying a scale factor
  18509. * @param factor defines the scale factor to apply
  18510. * @returns the current bounding info
  18511. */
  18512. BoundingInfo.prototype.scale = function (factor) {
  18513. this.boundingBox.scale(factor);
  18514. this.boundingSphere.scale(factor);
  18515. return this;
  18516. };
  18517. /**
  18518. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18519. * @param frustumPlanes defines the frustum to test
  18520. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18521. * @returns true if the bounding info is in the frustum planes
  18522. */
  18523. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18524. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18525. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18526. return false;
  18527. }
  18528. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18529. return true;
  18530. }
  18531. return this.boundingBox.isInFrustum(frustumPlanes);
  18532. };
  18533. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18534. /**
  18535. * Gets the world distance between the min and max points of the bounding box
  18536. */
  18537. get: function () {
  18538. var boundingBox = this.boundingBox;
  18539. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18540. return size.length();
  18541. },
  18542. enumerable: true,
  18543. configurable: true
  18544. });
  18545. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18546. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18547. };
  18548. /** @hidden */
  18549. BoundingInfo.prototype._checkCollision = function (collider) {
  18550. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18551. };
  18552. BoundingInfo.prototype.intersectsPoint = function (point) {
  18553. if (!this.boundingSphere.centerWorld) {
  18554. return false;
  18555. }
  18556. if (!this.boundingSphere.intersectsPoint(point)) {
  18557. return false;
  18558. }
  18559. if (!this.boundingBox.intersectsPoint(point)) {
  18560. return false;
  18561. }
  18562. return true;
  18563. };
  18564. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18565. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18566. return false;
  18567. }
  18568. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18569. return false;
  18570. }
  18571. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18572. return false;
  18573. }
  18574. if (!precise) {
  18575. return true;
  18576. }
  18577. var box0 = this.boundingBox;
  18578. var box1 = boundingInfo.boundingBox;
  18579. if (!axisOverlap(box0.directions[0], box0, box1))
  18580. return false;
  18581. if (!axisOverlap(box0.directions[1], box0, box1))
  18582. return false;
  18583. if (!axisOverlap(box0.directions[2], box0, box1))
  18584. return false;
  18585. if (!axisOverlap(box1.directions[0], box0, box1))
  18586. return false;
  18587. if (!axisOverlap(box1.directions[1], box0, box1))
  18588. return false;
  18589. if (!axisOverlap(box1.directions[2], box0, box1))
  18590. return false;
  18591. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18592. return false;
  18593. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18594. return false;
  18595. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18596. return false;
  18597. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18598. return false;
  18599. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18600. return false;
  18601. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18602. return false;
  18603. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18604. return false;
  18605. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18606. return false;
  18607. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18608. return false;
  18609. return true;
  18610. };
  18611. return BoundingInfo;
  18612. }());
  18613. BABYLON.BoundingInfo = BoundingInfo;
  18614. })(BABYLON || (BABYLON = {}));
  18615. //# sourceMappingURL=babylon.boundingInfo.js.map
  18616. var BABYLON;
  18617. (function (BABYLON) {
  18618. var TransformNode = /** @class */ (function (_super) {
  18619. __extends(TransformNode, _super);
  18620. function TransformNode(name, scene, isPure) {
  18621. if (scene === void 0) { scene = null; }
  18622. if (isPure === void 0) { isPure = true; }
  18623. var _this = _super.call(this, name, scene) || this;
  18624. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18625. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18626. _this._up = new BABYLON.Vector3(0, 1, 0);
  18627. _this._right = new BABYLON.Vector3(1, 0, 0);
  18628. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18629. // Properties
  18630. _this._position = BABYLON.Vector3.Zero();
  18631. _this._rotation = BABYLON.Vector3.Zero();
  18632. _this._scaling = BABYLON.Vector3.One();
  18633. _this._isDirty = false;
  18634. /**
  18635. * Set the billboard mode. Default is 0.
  18636. *
  18637. * | Value | Type | Description |
  18638. * | --- | --- | --- |
  18639. * | 0 | BILLBOARDMODE_NONE | |
  18640. * | 1 | BILLBOARDMODE_X | |
  18641. * | 2 | BILLBOARDMODE_Y | |
  18642. * | 4 | BILLBOARDMODE_Z | |
  18643. * | 7 | BILLBOARDMODE_ALL | |
  18644. *
  18645. */
  18646. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18647. _this.scalingDeterminant = 1;
  18648. _this.infiniteDistance = false;
  18649. /**
  18650. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18651. * By default the system will update normals to compensate
  18652. */
  18653. _this.ignoreNonUniformScaling = false;
  18654. _this._localWorld = BABYLON.Matrix.Zero();
  18655. _this._absolutePosition = BABYLON.Vector3.Zero();
  18656. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18657. _this._postMultiplyPivotMatrix = false;
  18658. _this._isWorldMatrixFrozen = false;
  18659. /**
  18660. * An event triggered after the world matrix is updated
  18661. */
  18662. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18663. _this._nonUniformScaling = false;
  18664. if (isPure) {
  18665. _this.getScene().addTransformNode(_this);
  18666. }
  18667. return _this;
  18668. }
  18669. /**
  18670. * Gets a string identifying the name of the class
  18671. * @returns "TransformNode" string
  18672. */
  18673. TransformNode.prototype.getClassName = function () {
  18674. return "TransformNode";
  18675. };
  18676. Object.defineProperty(TransformNode.prototype, "position", {
  18677. /**
  18678. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18679. */
  18680. get: function () {
  18681. return this._position;
  18682. },
  18683. set: function (newPosition) {
  18684. this._position = newPosition;
  18685. this._isDirty = true;
  18686. },
  18687. enumerable: true,
  18688. configurable: true
  18689. });
  18690. Object.defineProperty(TransformNode.prototype, "rotation", {
  18691. /**
  18692. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18693. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18694. */
  18695. get: function () {
  18696. return this._rotation;
  18697. },
  18698. set: function (newRotation) {
  18699. this._rotation = newRotation;
  18700. this._isDirty = true;
  18701. },
  18702. enumerable: true,
  18703. configurable: true
  18704. });
  18705. Object.defineProperty(TransformNode.prototype, "scaling", {
  18706. /**
  18707. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18708. */
  18709. get: function () {
  18710. return this._scaling;
  18711. },
  18712. set: function (newScaling) {
  18713. this._scaling = newScaling;
  18714. this._isDirty = true;
  18715. },
  18716. enumerable: true,
  18717. configurable: true
  18718. });
  18719. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18720. /**
  18721. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18722. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18723. */
  18724. get: function () {
  18725. return this._rotationQuaternion;
  18726. },
  18727. set: function (quaternion) {
  18728. this._rotationQuaternion = quaternion;
  18729. //reset the rotation vector.
  18730. if (quaternion && this.rotation.length()) {
  18731. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18732. }
  18733. },
  18734. enumerable: true,
  18735. configurable: true
  18736. });
  18737. Object.defineProperty(TransformNode.prototype, "forward", {
  18738. /**
  18739. * The forward direction of that transform in world space.
  18740. */
  18741. get: function () {
  18742. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18743. },
  18744. enumerable: true,
  18745. configurable: true
  18746. });
  18747. Object.defineProperty(TransformNode.prototype, "up", {
  18748. /**
  18749. * The up direction of that transform in world space.
  18750. */
  18751. get: function () {
  18752. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18753. },
  18754. enumerable: true,
  18755. configurable: true
  18756. });
  18757. Object.defineProperty(TransformNode.prototype, "right", {
  18758. /**
  18759. * The right direction of that transform in world space.
  18760. */
  18761. get: function () {
  18762. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18763. },
  18764. enumerable: true,
  18765. configurable: true
  18766. });
  18767. /**
  18768. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18769. * Returns the TransformNode.
  18770. */
  18771. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18772. this._poseMatrix.copyFrom(matrix);
  18773. return this;
  18774. };
  18775. /**
  18776. * Returns the mesh Pose matrix.
  18777. * Returned object : Matrix
  18778. */
  18779. TransformNode.prototype.getPoseMatrix = function () {
  18780. return this._poseMatrix;
  18781. };
  18782. /** @hidden */
  18783. TransformNode.prototype._isSynchronized = function () {
  18784. if (this._isDirty) {
  18785. return false;
  18786. }
  18787. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18788. return false;
  18789. if (this._cache.pivotMatrixUpdated) {
  18790. return false;
  18791. }
  18792. if (this.infiniteDistance) {
  18793. return false;
  18794. }
  18795. if (!this._cache.position.equals(this._position))
  18796. return false;
  18797. if (this._rotationQuaternion) {
  18798. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18799. return false;
  18800. }
  18801. if (!this._cache.rotation.equals(this._rotation))
  18802. return false;
  18803. if (!this._cache.scaling.equals(this._scaling))
  18804. return false;
  18805. return true;
  18806. };
  18807. /** @hidden */
  18808. TransformNode.prototype._initCache = function () {
  18809. _super.prototype._initCache.call(this);
  18810. this._cache.localMatrixUpdated = false;
  18811. this._cache.position = BABYLON.Vector3.Zero();
  18812. this._cache.scaling = BABYLON.Vector3.Zero();
  18813. this._cache.rotation = BABYLON.Vector3.Zero();
  18814. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18815. this._cache.billboardMode = -1;
  18816. };
  18817. TransformNode.prototype.markAsDirty = function (property) {
  18818. if (property === "rotation") {
  18819. this.rotationQuaternion = null;
  18820. }
  18821. this._currentRenderId = Number.MAX_VALUE;
  18822. this._isDirty = true;
  18823. return this;
  18824. };
  18825. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18826. /**
  18827. * Returns the current mesh absolute position.
  18828. * Returns a Vector3.
  18829. */
  18830. get: function () {
  18831. return this._absolutePosition;
  18832. },
  18833. enumerable: true,
  18834. configurable: true
  18835. });
  18836. /**
  18837. * Sets a new matrix to apply before all other transformation
  18838. * @param matrix defines the transform matrix
  18839. * @returns the current TransformNode
  18840. */
  18841. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18842. return this.setPivotMatrix(matrix, false);
  18843. };
  18844. /**
  18845. * Sets a new pivot matrix to the current node
  18846. * @param matrix defines the new pivot matrix to use
  18847. * @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
  18848. * @returns the current TransformNode
  18849. */
  18850. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18851. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18852. this._pivotMatrix = matrix.clone();
  18853. this._cache.pivotMatrixUpdated = true;
  18854. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18855. if (this._postMultiplyPivotMatrix) {
  18856. if (!this._pivotMatrixInverse) {
  18857. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18858. }
  18859. else {
  18860. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18861. }
  18862. }
  18863. return this;
  18864. };
  18865. /**
  18866. * Returns the mesh pivot matrix.
  18867. * Default : Identity.
  18868. * A Matrix is returned.
  18869. */
  18870. TransformNode.prototype.getPivotMatrix = function () {
  18871. return this._pivotMatrix;
  18872. };
  18873. /**
  18874. * Prevents the World matrix to be computed any longer.
  18875. * Returns the TransformNode.
  18876. */
  18877. TransformNode.prototype.freezeWorldMatrix = function () {
  18878. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18879. this.computeWorldMatrix(true);
  18880. this._isWorldMatrixFrozen = true;
  18881. return this;
  18882. };
  18883. /**
  18884. * Allows back the World matrix computation.
  18885. * Returns the TransformNode.
  18886. */
  18887. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18888. this._isWorldMatrixFrozen = false;
  18889. this.computeWorldMatrix(true);
  18890. return this;
  18891. };
  18892. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18893. /**
  18894. * True if the World matrix has been frozen.
  18895. * Returns a boolean.
  18896. */
  18897. get: function () {
  18898. return this._isWorldMatrixFrozen;
  18899. },
  18900. enumerable: true,
  18901. configurable: true
  18902. });
  18903. /**
  18904. * Retuns the mesh absolute position in the World.
  18905. * Returns a Vector3.
  18906. */
  18907. TransformNode.prototype.getAbsolutePosition = function () {
  18908. this.computeWorldMatrix();
  18909. return this._absolutePosition;
  18910. };
  18911. /**
  18912. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18913. * Returns the TransformNode.
  18914. */
  18915. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18916. if (!absolutePosition) {
  18917. return this;
  18918. }
  18919. var absolutePositionX;
  18920. var absolutePositionY;
  18921. var absolutePositionZ;
  18922. if (absolutePosition.x === undefined) {
  18923. if (arguments.length < 3) {
  18924. return this;
  18925. }
  18926. absolutePositionX = arguments[0];
  18927. absolutePositionY = arguments[1];
  18928. absolutePositionZ = arguments[2];
  18929. }
  18930. else {
  18931. absolutePositionX = absolutePosition.x;
  18932. absolutePositionY = absolutePosition.y;
  18933. absolutePositionZ = absolutePosition.z;
  18934. }
  18935. if (this.parent) {
  18936. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18937. invertParentWorldMatrix.invert();
  18938. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18939. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18940. }
  18941. else {
  18942. this.position.x = absolutePositionX;
  18943. this.position.y = absolutePositionY;
  18944. this.position.z = absolutePositionZ;
  18945. }
  18946. return this;
  18947. };
  18948. /**
  18949. * Sets the mesh position in its local space.
  18950. * Returns the TransformNode.
  18951. */
  18952. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18953. this.computeWorldMatrix();
  18954. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18955. return this;
  18956. };
  18957. /**
  18958. * Returns the mesh position in the local space from the current World matrix values.
  18959. * Returns a new Vector3.
  18960. */
  18961. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18962. this.computeWorldMatrix();
  18963. var invLocalWorldMatrix = this._localWorld.clone();
  18964. invLocalWorldMatrix.invert();
  18965. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18966. };
  18967. /**
  18968. * Translates the mesh along the passed Vector3 in its local space.
  18969. * Returns the TransformNode.
  18970. */
  18971. TransformNode.prototype.locallyTranslate = function (vector3) {
  18972. this.computeWorldMatrix(true);
  18973. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18974. return this;
  18975. };
  18976. /**
  18977. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18978. * @param targetPoint the position (must be in same space as current mesh) to look at
  18979. * @param yawCor optional yaw (y-axis) correction in radians
  18980. * @param pitchCor optional pitch (x-axis) correction in radians
  18981. * @param rollCor optional roll (z-axis) correction in radians
  18982. * @param space the choosen space of the target
  18983. * @returns the TransformNode.
  18984. */
  18985. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18986. if (yawCor === void 0) { yawCor = 0; }
  18987. if (pitchCor === void 0) { pitchCor = 0; }
  18988. if (rollCor === void 0) { rollCor = 0; }
  18989. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18990. var dv = TransformNode._lookAtVectorCache;
  18991. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18992. targetPoint.subtractToRef(pos, dv);
  18993. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18994. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18995. var pitch = Math.atan2(dv.y, len);
  18996. if (this.rotationQuaternion) {
  18997. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18998. }
  18999. else {
  19000. this.rotation.x = pitch + pitchCor;
  19001. this.rotation.y = yaw + yawCor;
  19002. this.rotation.z = rollCor;
  19003. }
  19004. return this;
  19005. };
  19006. /**
  19007. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19008. * This Vector3 is expressed in the World space.
  19009. */
  19010. TransformNode.prototype.getDirection = function (localAxis) {
  19011. var result = BABYLON.Vector3.Zero();
  19012. this.getDirectionToRef(localAxis, result);
  19013. return result;
  19014. };
  19015. /**
  19016. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19017. * localAxis is expressed in the mesh local space.
  19018. * result is computed in the Wordl space from the mesh World matrix.
  19019. * Returns the TransformNode.
  19020. */
  19021. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19022. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19023. return this;
  19024. };
  19025. /**
  19026. * Sets a new pivot point to the current node
  19027. * @param point defines the new pivot point to use
  19028. * @param space defines if the point is in world or local space (local by default)
  19029. * @returns the current TransformNode
  19030. */
  19031. TransformNode.prototype.setPivotPoint = function (point, space) {
  19032. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19033. if (this.getScene().getRenderId() == 0) {
  19034. this.computeWorldMatrix(true);
  19035. }
  19036. var wm = this.getWorldMatrix();
  19037. if (space == BABYLON.Space.WORLD) {
  19038. var tmat = BABYLON.Tmp.Matrix[0];
  19039. wm.invertToRef(tmat);
  19040. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19041. }
  19042. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19043. };
  19044. /**
  19045. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19046. */
  19047. TransformNode.prototype.getPivotPoint = function () {
  19048. var point = BABYLON.Vector3.Zero();
  19049. this.getPivotPointToRef(point);
  19050. return point;
  19051. };
  19052. /**
  19053. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19054. * Returns the TransformNode.
  19055. */
  19056. TransformNode.prototype.getPivotPointToRef = function (result) {
  19057. result.x = -this._pivotMatrix.m[12];
  19058. result.y = -this._pivotMatrix.m[13];
  19059. result.z = -this._pivotMatrix.m[14];
  19060. return this;
  19061. };
  19062. /**
  19063. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19064. */
  19065. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19066. var point = BABYLON.Vector3.Zero();
  19067. this.getAbsolutePivotPointToRef(point);
  19068. return point;
  19069. };
  19070. /**
  19071. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19072. * Returns the TransformNode.
  19073. */
  19074. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19075. result.x = this._pivotMatrix.m[12];
  19076. result.y = this._pivotMatrix.m[13];
  19077. result.z = this._pivotMatrix.m[14];
  19078. this.getPivotPointToRef(result);
  19079. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19080. return this;
  19081. };
  19082. /**
  19083. * Defines the passed node as the parent of the current node.
  19084. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19085. * Returns the TransformNode.
  19086. */
  19087. TransformNode.prototype.setParent = function (node) {
  19088. if (!node && !this.parent) {
  19089. return this;
  19090. }
  19091. if (!node) {
  19092. var rotation = BABYLON.Tmp.Quaternion[0];
  19093. var position = BABYLON.Tmp.Vector3[0];
  19094. var scale = BABYLON.Tmp.Vector3[1];
  19095. if (this.parent && this.parent.computeWorldMatrix) {
  19096. this.parent.computeWorldMatrix(true);
  19097. }
  19098. this.computeWorldMatrix(true);
  19099. this.getWorldMatrix().decompose(scale, rotation, position);
  19100. if (this.rotationQuaternion) {
  19101. this.rotationQuaternion.copyFrom(rotation);
  19102. }
  19103. else {
  19104. rotation.toEulerAnglesToRef(this.rotation);
  19105. }
  19106. this.scaling.x = scale.x;
  19107. this.scaling.y = scale.y;
  19108. this.scaling.z = scale.z;
  19109. this.position.x = position.x;
  19110. this.position.y = position.y;
  19111. this.position.z = position.z;
  19112. }
  19113. else {
  19114. var rotation = BABYLON.Tmp.Quaternion[0];
  19115. var position = BABYLON.Tmp.Vector3[0];
  19116. var scale = BABYLON.Tmp.Vector3[1];
  19117. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19118. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19119. this.computeWorldMatrix(true);
  19120. node.computeWorldMatrix(true);
  19121. node.getWorldMatrix().invertToRef(invParentMatrix);
  19122. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19123. diffMatrix.decompose(scale, rotation, position);
  19124. if (this.rotationQuaternion) {
  19125. this.rotationQuaternion.copyFrom(rotation);
  19126. }
  19127. else {
  19128. rotation.toEulerAnglesToRef(this.rotation);
  19129. }
  19130. this.position.x = position.x;
  19131. this.position.y = position.y;
  19132. this.position.z = position.z;
  19133. this.scaling.x = scale.x;
  19134. this.scaling.y = scale.y;
  19135. this.scaling.z = scale.z;
  19136. }
  19137. this.parent = node;
  19138. return this;
  19139. };
  19140. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19141. get: function () {
  19142. return this._nonUniformScaling;
  19143. },
  19144. enumerable: true,
  19145. configurable: true
  19146. });
  19147. /** @hidden */
  19148. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19149. if (this._nonUniformScaling === value) {
  19150. return false;
  19151. }
  19152. this._nonUniformScaling = value;
  19153. return true;
  19154. };
  19155. /**
  19156. * Attach the current TransformNode to another TransformNode associated with a bone
  19157. * @param bone Bone affecting the TransformNode
  19158. * @param affectedTransformNode TransformNode associated with the bone
  19159. */
  19160. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19161. this._transformToBoneReferal = affectedTransformNode;
  19162. this.parent = bone;
  19163. if (bone.getWorldMatrix().determinant() < 0) {
  19164. this.scalingDeterminant *= -1;
  19165. }
  19166. return this;
  19167. };
  19168. TransformNode.prototype.detachFromBone = function () {
  19169. if (!this.parent) {
  19170. return this;
  19171. }
  19172. if (this.parent.getWorldMatrix().determinant() < 0) {
  19173. this.scalingDeterminant *= -1;
  19174. }
  19175. this._transformToBoneReferal = null;
  19176. this.parent = null;
  19177. return this;
  19178. };
  19179. /**
  19180. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19181. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19182. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19183. * The passed axis is also normalized.
  19184. * Returns the TransformNode.
  19185. */
  19186. TransformNode.prototype.rotate = function (axis, amount, space) {
  19187. axis.normalize();
  19188. if (!this.rotationQuaternion) {
  19189. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19190. this.rotation = BABYLON.Vector3.Zero();
  19191. }
  19192. var rotationQuaternion;
  19193. if (!space || space === BABYLON.Space.LOCAL) {
  19194. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19195. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19196. }
  19197. else {
  19198. if (this.parent) {
  19199. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19200. invertParentWorldMatrix.invert();
  19201. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19202. }
  19203. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19204. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19205. }
  19206. return this;
  19207. };
  19208. /**
  19209. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19210. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19211. * The passed axis is also normalized.
  19212. * Returns the TransformNode.
  19213. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19214. */
  19215. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19216. axis.normalize();
  19217. if (!this.rotationQuaternion) {
  19218. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19219. this.rotation.copyFromFloats(0, 0, 0);
  19220. }
  19221. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19222. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19223. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19224. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19225. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19226. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19227. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19228. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19229. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19230. return this;
  19231. };
  19232. /**
  19233. * Translates the mesh along the axis vector for the passed distance in the given space.
  19234. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19235. * Returns the TransformNode.
  19236. */
  19237. TransformNode.prototype.translate = function (axis, distance, space) {
  19238. var displacementVector = axis.scale(distance);
  19239. if (!space || space === BABYLON.Space.LOCAL) {
  19240. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19241. this.setPositionWithLocalVector(tempV3);
  19242. }
  19243. else {
  19244. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19245. }
  19246. return this;
  19247. };
  19248. /**
  19249. * Adds a rotation step to the mesh current rotation.
  19250. * x, y, z are Euler angles expressed in radians.
  19251. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19252. * This means this rotation is made in the mesh local space only.
  19253. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19254. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19255. * ```javascript
  19256. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19257. * ```
  19258. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19259. * 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.
  19260. * Returns the TransformNode.
  19261. */
  19262. TransformNode.prototype.addRotation = function (x, y, z) {
  19263. var rotationQuaternion;
  19264. if (this.rotationQuaternion) {
  19265. rotationQuaternion = this.rotationQuaternion;
  19266. }
  19267. else {
  19268. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19269. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19270. }
  19271. var accumulation = BABYLON.Tmp.Quaternion[0];
  19272. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19273. rotationQuaternion.multiplyInPlace(accumulation);
  19274. if (!this.rotationQuaternion) {
  19275. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19276. }
  19277. return this;
  19278. };
  19279. /**
  19280. * Computes the world matrix of the node
  19281. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19282. * @returns the world matrix
  19283. */
  19284. TransformNode.prototype.computeWorldMatrix = function (force) {
  19285. if (this._isWorldMatrixFrozen) {
  19286. return this._worldMatrix;
  19287. }
  19288. if (!force && this.isSynchronized()) {
  19289. this._currentRenderId = this.getScene().getRenderId();
  19290. return this._worldMatrix;
  19291. }
  19292. this._updateCache();
  19293. this._cache.position.copyFrom(this.position);
  19294. this._cache.scaling.copyFrom(this.scaling);
  19295. this._cache.pivotMatrixUpdated = false;
  19296. this._cache.billboardMode = this.billboardMode;
  19297. this._currentRenderId = this.getScene().getRenderId();
  19298. this._childRenderId = this.getScene().getRenderId();
  19299. this._isDirty = false;
  19300. // Scaling
  19301. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19302. // Rotation
  19303. //rotate, if quaternion is set and rotation was used
  19304. if (this.rotationQuaternion) {
  19305. var len = this.rotation.length();
  19306. if (len) {
  19307. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19308. this.rotation.copyFromFloats(0, 0, 0);
  19309. }
  19310. }
  19311. if (this.rotationQuaternion) {
  19312. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19313. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19314. }
  19315. else {
  19316. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19317. this._cache.rotation.copyFrom(this.rotation);
  19318. }
  19319. // Translation
  19320. var camera = this.getScene().activeCamera;
  19321. if (this.infiniteDistance && !this.parent && camera) {
  19322. var cameraWorldMatrix = camera.getWorldMatrix();
  19323. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19324. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19325. }
  19326. else {
  19327. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19328. }
  19329. // Composing transformations
  19330. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19331. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19332. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19333. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19334. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19335. // Need to decompose each rotation here
  19336. var currentPosition = BABYLON.Tmp.Vector3[3];
  19337. if (this.parent && this.parent.getWorldMatrix) {
  19338. if (this._transformToBoneReferal) {
  19339. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19340. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19341. }
  19342. else {
  19343. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19344. }
  19345. }
  19346. else {
  19347. currentPosition.copyFrom(this.position);
  19348. }
  19349. currentPosition.subtractInPlace(camera.globalPosition);
  19350. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19351. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19352. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19353. }
  19354. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19355. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19356. }
  19357. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19358. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19359. }
  19360. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19361. }
  19362. else {
  19363. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19364. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19365. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19366. }
  19367. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19368. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19369. }
  19370. // Post multiply inverse of pivotMatrix
  19371. if (this._postMultiplyPivotMatrix) {
  19372. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19373. }
  19374. // Local world
  19375. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19376. // Parent
  19377. if (this.parent && this.parent.getWorldMatrix) {
  19378. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19379. if (this._transformToBoneReferal) {
  19380. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19381. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19382. }
  19383. else {
  19384. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19385. }
  19386. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19387. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19388. this._worldMatrix.copyFrom(this._localWorld);
  19389. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19390. }
  19391. else {
  19392. if (this._transformToBoneReferal) {
  19393. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19394. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19395. }
  19396. else {
  19397. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19398. }
  19399. }
  19400. this._markSyncedWithParent();
  19401. }
  19402. else {
  19403. this._worldMatrix.copyFrom(this._localWorld);
  19404. }
  19405. // Normal matrix
  19406. if (!this.ignoreNonUniformScaling) {
  19407. if (this.scaling.isNonUniform) {
  19408. this._updateNonUniformScalingState(true);
  19409. }
  19410. else if (this.parent && this.parent._nonUniformScaling) {
  19411. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19412. }
  19413. else {
  19414. this._updateNonUniformScalingState(false);
  19415. }
  19416. }
  19417. else {
  19418. this._updateNonUniformScalingState(false);
  19419. }
  19420. this._afterComputeWorldMatrix();
  19421. // Absolute position
  19422. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19423. // Callbacks
  19424. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19425. if (!this._poseMatrix) {
  19426. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19427. }
  19428. // Cache the determinant
  19429. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19430. return this._worldMatrix;
  19431. };
  19432. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19433. };
  19434. /**
  19435. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19436. * @param func: callback function to add
  19437. *
  19438. * Returns the TransformNode.
  19439. */
  19440. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19441. this.onAfterWorldMatrixUpdateObservable.add(func);
  19442. return this;
  19443. };
  19444. /**
  19445. * Removes a registered callback function.
  19446. * Returns the TransformNode.
  19447. */
  19448. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19449. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19450. return this;
  19451. };
  19452. /**
  19453. * Clone the current transform node
  19454. * Returns the new transform node
  19455. * @param name Name of the new clone
  19456. * @param newParent New parent for the clone
  19457. * @param doNotCloneChildren Do not clone children hierarchy
  19458. */
  19459. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19460. var _this = this;
  19461. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19462. result.name = name;
  19463. result.id = name;
  19464. if (newParent) {
  19465. result.parent = newParent;
  19466. }
  19467. if (!doNotCloneChildren) {
  19468. // Children
  19469. var directDescendants = this.getDescendants(true);
  19470. for (var index = 0; index < directDescendants.length; index++) {
  19471. var child = directDescendants[index];
  19472. if (child.clone) {
  19473. child.clone(name + "." + child.name, result);
  19474. }
  19475. }
  19476. }
  19477. return result;
  19478. };
  19479. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19480. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19481. serializationObject.type = this.getClassName();
  19482. // Parent
  19483. if (this.parent) {
  19484. serializationObject.parentId = this.parent.id;
  19485. }
  19486. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19487. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19488. }
  19489. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19490. serializationObject.isEnabled = this.isEnabled();
  19491. // Parent
  19492. if (this.parent) {
  19493. serializationObject.parentId = this.parent.id;
  19494. }
  19495. return serializationObject;
  19496. };
  19497. // Statics
  19498. /**
  19499. * Returns a new TransformNode object parsed from the source provided.
  19500. * The parameter `parsedMesh` is the source.
  19501. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19502. */
  19503. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19504. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19505. if (BABYLON.Tags) {
  19506. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19507. }
  19508. if (parsedTransformNode.localMatrix) {
  19509. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19510. }
  19511. else if (parsedTransformNode.pivotMatrix) {
  19512. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19513. }
  19514. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19515. // Parent
  19516. if (parsedTransformNode.parentId) {
  19517. transformNode._waitingParentId = parsedTransformNode.parentId;
  19518. }
  19519. return transformNode;
  19520. };
  19521. /**
  19522. * Releases resources associated with this transform node.
  19523. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19524. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19525. */
  19526. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19527. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19528. // Animations
  19529. this.getScene().stopAnimation(this);
  19530. // Remove from scene
  19531. this.getScene().removeTransformNode(this);
  19532. this.onAfterWorldMatrixUpdateObservable.clear();
  19533. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19534. };
  19535. // Statics
  19536. TransformNode.BILLBOARDMODE_NONE = 0;
  19537. TransformNode.BILLBOARDMODE_X = 1;
  19538. TransformNode.BILLBOARDMODE_Y = 2;
  19539. TransformNode.BILLBOARDMODE_Z = 4;
  19540. TransformNode.BILLBOARDMODE_ALL = 7;
  19541. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19542. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19543. __decorate([
  19544. BABYLON.serializeAsVector3("position")
  19545. ], TransformNode.prototype, "_position", void 0);
  19546. __decorate([
  19547. BABYLON.serializeAsVector3("rotation")
  19548. ], TransformNode.prototype, "_rotation", void 0);
  19549. __decorate([
  19550. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19551. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19552. __decorate([
  19553. BABYLON.serializeAsVector3("scaling")
  19554. ], TransformNode.prototype, "_scaling", void 0);
  19555. __decorate([
  19556. BABYLON.serialize()
  19557. ], TransformNode.prototype, "billboardMode", void 0);
  19558. __decorate([
  19559. BABYLON.serialize()
  19560. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19561. __decorate([
  19562. BABYLON.serialize()
  19563. ], TransformNode.prototype, "infiniteDistance", void 0);
  19564. __decorate([
  19565. BABYLON.serialize()
  19566. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19567. return TransformNode;
  19568. }(BABYLON.Node));
  19569. BABYLON.TransformNode = TransformNode;
  19570. })(BABYLON || (BABYLON = {}));
  19571. //# sourceMappingURL=babylon.transformNode.js.map
  19572. var BABYLON;
  19573. (function (BABYLON) {
  19574. /**
  19575. * Class used to store all common mesh properties
  19576. */
  19577. var AbstractMesh = /** @class */ (function (_super) {
  19578. __extends(AbstractMesh, _super);
  19579. // Constructor
  19580. /**
  19581. * Creates a new AbstractMesh
  19582. * @param name defines the name of the mesh
  19583. * @param scene defines the hosting scene
  19584. */
  19585. function AbstractMesh(name, scene) {
  19586. if (scene === void 0) { scene = null; }
  19587. var _this = _super.call(this, name, scene, false) || this;
  19588. _this._facetNb = 0; // facet number
  19589. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19590. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19591. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19592. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19593. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19594. _this._subDiv = {
  19595. max: 1,
  19596. X: 1,
  19597. Y: 1,
  19598. Z: 1
  19599. };
  19600. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19601. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19602. /** Gets ot sets the culling strategy to use to find visible meshes */
  19603. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19604. // Events
  19605. /**
  19606. * An event triggered when this mesh collides with another one
  19607. */
  19608. _this.onCollideObservable = new BABYLON.Observable();
  19609. /**
  19610. * An event triggered when the collision's position changes
  19611. */
  19612. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19613. /**
  19614. * An event triggered when material is changed
  19615. */
  19616. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19617. // Properties
  19618. /**
  19619. * Gets or sets the orientation for POV movement & rotation
  19620. */
  19621. _this.definedFacingForward = true;
  19622. /**
  19623. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19624. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19625. * * 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.
  19626. * @see http://doc.babylonjs.com/features/occlusionquery
  19627. */
  19628. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19629. /**
  19630. * 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:
  19631. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19632. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19633. * * 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.
  19634. * @see http://doc.babylonjs.com/features/occlusionquery
  19635. */
  19636. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19637. /**
  19638. * 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.
  19639. * The default value is -1 which means don't break the query and wait till the result
  19640. * @see http://doc.babylonjs.com/features/occlusionquery
  19641. */
  19642. _this.occlusionRetryCount = -1;
  19643. /** @hidden */
  19644. _this._occlusionInternalRetryCounter = 0;
  19645. /** @hidden */
  19646. _this._isOccluded = false;
  19647. /** @hidden */
  19648. _this._isOcclusionQueryInProgress = false;
  19649. _this._visibility = 1.0;
  19650. /** Gets or sets the alpha index used to sort transparent meshes
  19651. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19652. */
  19653. _this.alphaIndex = Number.MAX_VALUE;
  19654. /**
  19655. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19656. */
  19657. _this.isVisible = true;
  19658. /**
  19659. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19660. */
  19661. _this.isPickable = true;
  19662. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19663. _this.showSubMeshesBoundingBox = false;
  19664. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19665. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19666. */
  19667. _this.isBlocker = false;
  19668. /**
  19669. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19670. */
  19671. _this.enablePointerMoveEvents = false;
  19672. /**
  19673. * Specifies the rendering group id for this mesh (0 by default)
  19674. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19675. */
  19676. _this.renderingGroupId = 0;
  19677. _this._receiveShadows = false;
  19678. /** Defines color to use when rendering outline */
  19679. _this.outlineColor = BABYLON.Color3.Red();
  19680. /** Define width to use when rendering outline */
  19681. _this.outlineWidth = 0.02;
  19682. /** Defines color to use when rendering overlay */
  19683. _this.overlayColor = BABYLON.Color3.Red();
  19684. /** Defines alpha to use when rendering overlay */
  19685. _this.overlayAlpha = 0.5;
  19686. _this._hasVertexAlpha = false;
  19687. _this._useVertexColors = true;
  19688. _this._computeBonesUsingShaders = true;
  19689. _this._numBoneInfluencers = 4;
  19690. _this._applyFog = true;
  19691. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19692. _this.useOctreeForRenderingSelection = true;
  19693. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19694. _this.useOctreeForPicking = true;
  19695. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19696. _this.useOctreeForCollisions = true;
  19697. _this._layerMask = 0x0FFFFFFF;
  19698. /**
  19699. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19700. */
  19701. _this.alwaysSelectAsActiveMesh = false;
  19702. /**
  19703. * Gets or sets the current action manager
  19704. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19705. */
  19706. _this.actionManager = null;
  19707. /**
  19708. * Gets or sets impostor used for physic simulation
  19709. * @see http://doc.babylonjs.com/features/physics_engine
  19710. */
  19711. _this.physicsImpostor = null;
  19712. // Collisions
  19713. _this._checkCollisions = false;
  19714. _this._collisionMask = -1;
  19715. _this._collisionGroup = -1;
  19716. /**
  19717. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19718. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19719. */
  19720. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19721. /**
  19722. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19723. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19724. */
  19725. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19726. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19727. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19728. // Edges
  19729. /**
  19730. * Defines edge width used when edgesRenderer is enabled
  19731. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19732. */
  19733. _this.edgesWidth = 1;
  19734. /**
  19735. * Defines edge color used when edgesRenderer is enabled
  19736. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19737. */
  19738. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19739. // Cache
  19740. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19741. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19742. /** @hidden */
  19743. _this._renderId = 0;
  19744. /** @hidden */
  19745. _this._intersectionsInProgress = new Array();
  19746. /** @hidden */
  19747. _this._unIndexed = false;
  19748. /** @hidden */
  19749. _this._lightSources = new Array();
  19750. /**
  19751. * An event triggered when the mesh is rebuilt.
  19752. */
  19753. _this.onRebuildObservable = new BABYLON.Observable();
  19754. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19755. if (collidedMesh === void 0) { collidedMesh = null; }
  19756. //TODO move this to the collision coordinator!
  19757. if (_this.getScene().workerCollisions)
  19758. newPosition.multiplyInPlace(_this._collider._radius);
  19759. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19760. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19761. _this.position.addInPlace(_this._diffPositionForCollisions);
  19762. }
  19763. if (collidedMesh) {
  19764. _this.onCollideObservable.notifyObservers(collidedMesh);
  19765. }
  19766. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19767. };
  19768. _this.getScene().addMesh(_this);
  19769. _this._resyncLightSources();
  19770. return _this;
  19771. }
  19772. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19773. /**
  19774. * No billboard
  19775. */
  19776. get: function () {
  19777. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19783. /** Billboard on X axis */
  19784. get: function () {
  19785. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19786. },
  19787. enumerable: true,
  19788. configurable: true
  19789. });
  19790. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19791. /** Billboard on Y axis */
  19792. get: function () {
  19793. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19799. /** Billboard on Z axis */
  19800. get: function () {
  19801. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19807. /** Billboard on all axes */
  19808. get: function () {
  19809. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19815. /**
  19816. * Gets the number of facets in the mesh
  19817. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19818. */
  19819. get: function () {
  19820. return this._facetNb;
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19826. /**
  19827. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19828. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19829. */
  19830. get: function () {
  19831. return this._partitioningSubdivisions;
  19832. },
  19833. set: function (nb) {
  19834. this._partitioningSubdivisions = nb;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19840. /**
  19841. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19842. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19843. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19844. */
  19845. get: function () {
  19846. return this._partitioningBBoxRatio;
  19847. },
  19848. set: function (ratio) {
  19849. this._partitioningBBoxRatio = ratio;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19855. /**
  19856. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19857. * Works only for updatable meshes.
  19858. * Doesn't work with multi-materials
  19859. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19860. */
  19861. get: function () {
  19862. return this._facetDepthSort;
  19863. },
  19864. set: function (sort) {
  19865. this._facetDepthSort = sort;
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19871. /**
  19872. * The location (Vector3) where the facet depth sort must be computed from.
  19873. * By default, the active camera position.
  19874. * Used only when facet depth sort is enabled
  19875. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19876. */
  19877. get: function () {
  19878. return this._facetDepthSortFrom;
  19879. },
  19880. set: function (location) {
  19881. this._facetDepthSortFrom = location;
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19887. /**
  19888. * gets a boolean indicating if facetData is enabled
  19889. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19890. */
  19891. get: function () {
  19892. return this._facetDataEnabled;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. /** @hidden */
  19898. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19899. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19900. return false;
  19901. }
  19902. this._markSubMeshesAsMiscDirty();
  19903. return true;
  19904. };
  19905. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19906. /** Set a function to call when this mesh collides with another one */
  19907. set: function (callback) {
  19908. if (this._onCollideObserver) {
  19909. this.onCollideObservable.remove(this._onCollideObserver);
  19910. }
  19911. this._onCollideObserver = this.onCollideObservable.add(callback);
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19917. /** Set a function to call when the collision's position changes */
  19918. set: function (callback) {
  19919. if (this._onCollisionPositionChangeObserver) {
  19920. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19921. }
  19922. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19923. },
  19924. enumerable: true,
  19925. configurable: true
  19926. });
  19927. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19928. /**
  19929. * 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
  19930. * @see http://doc.babylonjs.com/features/occlusionquery
  19931. */
  19932. get: function () {
  19933. return this._isOccluded;
  19934. },
  19935. set: function (value) {
  19936. this._isOccluded = value;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19942. /**
  19943. * Flag to check the progress status of the query
  19944. * @see http://doc.babylonjs.com/features/occlusionquery
  19945. */
  19946. get: function () {
  19947. return this._isOcclusionQueryInProgress;
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19953. /**
  19954. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19955. */
  19956. get: function () {
  19957. return this._visibility;
  19958. },
  19959. /**
  19960. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19961. */
  19962. set: function (value) {
  19963. if (this._visibility === value) {
  19964. return;
  19965. }
  19966. this._visibility = value;
  19967. this._markSubMeshesAsMiscDirty();
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(AbstractMesh.prototype, "material", {
  19973. /** Gets or sets current material */
  19974. get: function () {
  19975. return this._material;
  19976. },
  19977. set: function (value) {
  19978. if (this._material === value) {
  19979. return;
  19980. }
  19981. this._material = value;
  19982. if (this.onMaterialChangedObservable.hasObservers) {
  19983. this.onMaterialChangedObservable.notifyObservers(this);
  19984. }
  19985. if (!this.subMeshes) {
  19986. return;
  19987. }
  19988. this._unBindEffect();
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19994. /**
  19995. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19996. * @see http://doc.babylonjs.com/babylon101/shadows
  19997. */
  19998. get: function () {
  19999. return this._receiveShadows;
  20000. },
  20001. set: function (value) {
  20002. if (this._receiveShadows === value) {
  20003. return;
  20004. }
  20005. this._receiveShadows = value;
  20006. this._markSubMeshesAsLightDirty();
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20012. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20013. get: function () {
  20014. return this._hasVertexAlpha;
  20015. },
  20016. set: function (value) {
  20017. if (this._hasVertexAlpha === value) {
  20018. return;
  20019. }
  20020. this._hasVertexAlpha = value;
  20021. this._markSubMeshesAsAttributesDirty();
  20022. this._markSubMeshesAsMiscDirty();
  20023. },
  20024. enumerable: true,
  20025. configurable: true
  20026. });
  20027. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20028. /** 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) */
  20029. get: function () {
  20030. return this._useVertexColors;
  20031. },
  20032. set: function (value) {
  20033. if (this._useVertexColors === value) {
  20034. return;
  20035. }
  20036. this._useVertexColors = value;
  20037. this._markSubMeshesAsAttributesDirty();
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20043. /**
  20044. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20045. */
  20046. get: function () {
  20047. return this._computeBonesUsingShaders;
  20048. },
  20049. set: function (value) {
  20050. if (this._computeBonesUsingShaders === value) {
  20051. return;
  20052. }
  20053. this._computeBonesUsingShaders = value;
  20054. this._markSubMeshesAsAttributesDirty();
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20060. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20061. get: function () {
  20062. return this._numBoneInfluencers;
  20063. },
  20064. set: function (value) {
  20065. if (this._numBoneInfluencers === value) {
  20066. return;
  20067. }
  20068. this._numBoneInfluencers = value;
  20069. this._markSubMeshesAsAttributesDirty();
  20070. },
  20071. enumerable: true,
  20072. configurable: true
  20073. });
  20074. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20075. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20076. get: function () {
  20077. return this._applyFog;
  20078. },
  20079. set: function (value) {
  20080. if (this._applyFog === value) {
  20081. return;
  20082. }
  20083. this._applyFog = value;
  20084. this._markSubMeshesAsMiscDirty();
  20085. },
  20086. enumerable: true,
  20087. configurable: true
  20088. });
  20089. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20090. /**
  20091. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20092. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20093. */
  20094. get: function () {
  20095. return this._layerMask;
  20096. },
  20097. set: function (value) {
  20098. if (value === this._layerMask) {
  20099. return;
  20100. }
  20101. this._layerMask = value;
  20102. this._resyncLightSources();
  20103. },
  20104. enumerable: true,
  20105. configurable: true
  20106. });
  20107. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20108. /**
  20109. * Gets or sets a collision mask used to mask collisions (default is -1).
  20110. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20111. */
  20112. get: function () {
  20113. return this._collisionMask;
  20114. },
  20115. set: function (mask) {
  20116. this._collisionMask = !isNaN(mask) ? mask : -1;
  20117. },
  20118. enumerable: true,
  20119. configurable: true
  20120. });
  20121. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20122. /**
  20123. * Gets or sets the current collision group mask (-1 by default).
  20124. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20125. */
  20126. get: function () {
  20127. return this._collisionGroup;
  20128. },
  20129. set: function (mask) {
  20130. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20131. },
  20132. enumerable: true,
  20133. configurable: true
  20134. });
  20135. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20136. /** @hidden */
  20137. get: function () {
  20138. return null;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20144. get: function () {
  20145. return this._skeleton;
  20146. },
  20147. /**
  20148. * Gets or sets a skeleton to apply skining transformations
  20149. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20150. */
  20151. set: function (value) {
  20152. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20153. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20154. }
  20155. if (value && value.needInitialSkinMatrix) {
  20156. value._registerMeshWithPoseMatrix(this);
  20157. }
  20158. this._skeleton = value;
  20159. if (!this._skeleton) {
  20160. this._bonesTransformMatrices = null;
  20161. }
  20162. this._markSubMeshesAsAttributesDirty();
  20163. },
  20164. enumerable: true,
  20165. configurable: true
  20166. });
  20167. /**
  20168. * Returns the string "AbstractMesh"
  20169. * @returns "AbstractMesh"
  20170. */
  20171. AbstractMesh.prototype.getClassName = function () {
  20172. return "AbstractMesh";
  20173. };
  20174. /**
  20175. * Gets a string representation of the current mesh
  20176. * @param fullDetails defines a boolean indicating if full details must be included
  20177. * @returns a string representation of the current mesh
  20178. */
  20179. AbstractMesh.prototype.toString = function (fullDetails) {
  20180. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20181. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20182. if (this._skeleton) {
  20183. ret += ", skeleton: " + this._skeleton.name;
  20184. }
  20185. if (fullDetails) {
  20186. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20187. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20188. }
  20189. return ret;
  20190. };
  20191. /** @hidden */
  20192. AbstractMesh.prototype._rebuild = function () {
  20193. this.onRebuildObservable.notifyObservers(this);
  20194. if (this._occlusionQuery) {
  20195. this._occlusionQuery = null;
  20196. }
  20197. if (!this.subMeshes) {
  20198. return;
  20199. }
  20200. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20201. var subMesh = _a[_i];
  20202. subMesh._rebuild();
  20203. }
  20204. };
  20205. /** @hidden */
  20206. AbstractMesh.prototype._resyncLightSources = function () {
  20207. this._lightSources.length = 0;
  20208. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20209. var light = _a[_i];
  20210. if (!light.isEnabled()) {
  20211. continue;
  20212. }
  20213. if (light.canAffectMesh(this)) {
  20214. this._lightSources.push(light);
  20215. }
  20216. }
  20217. this._markSubMeshesAsLightDirty();
  20218. };
  20219. /** @hidden */
  20220. AbstractMesh.prototype._resyncLighSource = function (light) {
  20221. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20222. var index = this._lightSources.indexOf(light);
  20223. if (index === -1) {
  20224. if (!isIn) {
  20225. return;
  20226. }
  20227. this._lightSources.push(light);
  20228. }
  20229. else {
  20230. if (isIn) {
  20231. return;
  20232. }
  20233. this._lightSources.splice(index, 1);
  20234. }
  20235. this._markSubMeshesAsLightDirty();
  20236. };
  20237. /** @hidden */
  20238. AbstractMesh.prototype._unBindEffect = function () {
  20239. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20240. var subMesh = _a[_i];
  20241. subMesh.setEffect(null);
  20242. }
  20243. };
  20244. /** @hidden */
  20245. AbstractMesh.prototype._removeLightSource = function (light) {
  20246. var index = this._lightSources.indexOf(light);
  20247. if (index === -1) {
  20248. return;
  20249. }
  20250. this._lightSources.splice(index, 1);
  20251. this._markSubMeshesAsLightDirty();
  20252. };
  20253. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20254. if (!this.subMeshes) {
  20255. return;
  20256. }
  20257. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20258. var subMesh = _a[_i];
  20259. if (subMesh._materialDefines) {
  20260. func(subMesh._materialDefines);
  20261. }
  20262. }
  20263. };
  20264. /** @hidden */
  20265. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20266. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20267. };
  20268. /** @hidden */
  20269. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20270. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20271. };
  20272. /** @hidden */
  20273. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20274. if (!this.subMeshes) {
  20275. return;
  20276. }
  20277. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20278. var subMesh = _a[_i];
  20279. var material = subMesh.getMaterial();
  20280. if (material) {
  20281. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20282. }
  20283. }
  20284. };
  20285. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20286. /**
  20287. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20288. */
  20289. get: function () {
  20290. return this._scaling;
  20291. },
  20292. set: function (newScaling) {
  20293. this._scaling = newScaling;
  20294. if (this.physicsImpostor) {
  20295. this.physicsImpostor.forceUpdate();
  20296. }
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20302. // Methods
  20303. /**
  20304. * Returns true if the mesh is blocked. Implemented by child classes
  20305. */
  20306. get: function () {
  20307. return false;
  20308. },
  20309. enumerable: true,
  20310. configurable: true
  20311. });
  20312. /**
  20313. * Returns the mesh itself by default. Implemented by child classes
  20314. * @param camera defines the camera to use to pick the right LOD level
  20315. * @returns the currentAbstractMesh
  20316. */
  20317. AbstractMesh.prototype.getLOD = function (camera) {
  20318. return this;
  20319. };
  20320. /**
  20321. * Returns 0 by default. Implemented by child classes
  20322. * @returns an integer
  20323. */
  20324. AbstractMesh.prototype.getTotalVertices = function () {
  20325. return 0;
  20326. };
  20327. /**
  20328. * Returns null by default. Implemented by child classes
  20329. * @returns null
  20330. */
  20331. AbstractMesh.prototype.getIndices = function () {
  20332. return null;
  20333. };
  20334. /**
  20335. * Returns the array of the requested vertex data kind. Implemented by child classes
  20336. * @param kind defines the vertex data kind to use
  20337. * @returns null
  20338. */
  20339. AbstractMesh.prototype.getVerticesData = function (kind) {
  20340. return null;
  20341. };
  20342. /**
  20343. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20344. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20345. * Note that a new underlying VertexBuffer object is created each call.
  20346. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20347. * @param kind defines vertex data kind:
  20348. * * BABYLON.VertexBuffer.PositionKind
  20349. * * BABYLON.VertexBuffer.UVKind
  20350. * * BABYLON.VertexBuffer.UV2Kind
  20351. * * BABYLON.VertexBuffer.UV3Kind
  20352. * * BABYLON.VertexBuffer.UV4Kind
  20353. * * BABYLON.VertexBuffer.UV5Kind
  20354. * * BABYLON.VertexBuffer.UV6Kind
  20355. * * BABYLON.VertexBuffer.ColorKind
  20356. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20357. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20358. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20359. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20360. * @param data defines the data source
  20361. * @param updatable defines if the data must be flagged as updatable (or static)
  20362. * @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
  20363. * @returns the current mesh
  20364. */
  20365. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20366. return this;
  20367. };
  20368. /**
  20369. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20370. * If the mesh has no geometry, it is simply returned as it is.
  20371. * @param kind defines vertex data kind:
  20372. * * BABYLON.VertexBuffer.PositionKind
  20373. * * BABYLON.VertexBuffer.UVKind
  20374. * * BABYLON.VertexBuffer.UV2Kind
  20375. * * BABYLON.VertexBuffer.UV3Kind
  20376. * * BABYLON.VertexBuffer.UV4Kind
  20377. * * BABYLON.VertexBuffer.UV5Kind
  20378. * * BABYLON.VertexBuffer.UV6Kind
  20379. * * BABYLON.VertexBuffer.ColorKind
  20380. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20381. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20382. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20383. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20384. * @param data defines the data source
  20385. * @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
  20386. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20387. * @returns the current mesh
  20388. */
  20389. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20390. return this;
  20391. };
  20392. /**
  20393. * Sets the mesh indices,
  20394. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20395. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20396. * @param totalVertices Defines the total number of vertices
  20397. * @returns the current mesh
  20398. */
  20399. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20400. return this;
  20401. };
  20402. /**
  20403. * Gets a boolean indicating if specific vertex data is present
  20404. * @param kind defines the vertex data kind to use
  20405. * @returns true is data kind is present
  20406. */
  20407. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20408. return false;
  20409. };
  20410. /**
  20411. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20412. * @returns a BoundingInfo
  20413. */
  20414. AbstractMesh.prototype.getBoundingInfo = function () {
  20415. if (this._masterMesh) {
  20416. return this._masterMesh.getBoundingInfo();
  20417. }
  20418. if (!this._boundingInfo) {
  20419. // this._boundingInfo is being created here
  20420. this._updateBoundingInfo();
  20421. }
  20422. // cannot be null.
  20423. return this._boundingInfo;
  20424. };
  20425. /**
  20426. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20427. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20428. * @returns the current mesh
  20429. */
  20430. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20431. if (includeDescendants === void 0) { includeDescendants = true; }
  20432. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20433. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20434. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20435. if (maxDimension === 0) {
  20436. return this;
  20437. }
  20438. var scale = 1 / maxDimension;
  20439. this.scaling.scaleInPlace(scale);
  20440. return this;
  20441. };
  20442. /**
  20443. * Overwrite the current bounding info
  20444. * @param boundingInfo defines the new bounding info
  20445. * @returns the current mesh
  20446. */
  20447. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20448. this._boundingInfo = boundingInfo;
  20449. return this;
  20450. };
  20451. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20452. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20453. get: function () {
  20454. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20455. },
  20456. enumerable: true,
  20457. configurable: true
  20458. });
  20459. /** @hidden */
  20460. AbstractMesh.prototype._preActivate = function () {
  20461. };
  20462. /** @hidden */
  20463. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20464. };
  20465. /** @hidden */
  20466. AbstractMesh.prototype._activate = function (renderId) {
  20467. this._renderId = renderId;
  20468. };
  20469. /**
  20470. * Gets the current world matrix
  20471. * @returns a Matrix
  20472. */
  20473. AbstractMesh.prototype.getWorldMatrix = function () {
  20474. if (this._masterMesh) {
  20475. return this._masterMesh.getWorldMatrix();
  20476. }
  20477. return _super.prototype.getWorldMatrix.call(this);
  20478. };
  20479. /** @hidden */
  20480. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20481. if (this._masterMesh) {
  20482. return this._masterMesh._getWorldMatrixDeterminant();
  20483. }
  20484. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20485. };
  20486. // ================================== Point of View Movement =================================
  20487. /**
  20488. * Perform relative position change from the point of view of behind the front of the mesh.
  20489. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20490. * Supports definition of mesh facing forward or backward
  20491. * @param amountRight defines the distance on the right axis
  20492. * @param amountUp defines the distance on the up axis
  20493. * @param amountForward defines the distance on the forward axis
  20494. * @returns the current mesh
  20495. */
  20496. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20497. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20498. return this;
  20499. };
  20500. /**
  20501. * Calculate relative position change from the point of view of behind the front of the mesh.
  20502. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20503. * Supports definition of mesh facing forward or backward
  20504. * @param amountRight defines the distance on the right axis
  20505. * @param amountUp defines the distance on the up axis
  20506. * @param amountForward defines the distance on the forward axis
  20507. * @returns the new displacement vector
  20508. */
  20509. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20510. var rotMatrix = new BABYLON.Matrix();
  20511. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20512. rotQuaternion.toRotationMatrix(rotMatrix);
  20513. var translationDelta = BABYLON.Vector3.Zero();
  20514. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20515. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20516. return translationDelta;
  20517. };
  20518. // ================================== Point of View Rotation =================================
  20519. /**
  20520. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20521. * Supports definition of mesh facing forward or backward
  20522. * @param flipBack defines the flip
  20523. * @param twirlClockwise defines the twirl
  20524. * @param tiltRight defines the tilt
  20525. * @returns the current mesh
  20526. */
  20527. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20528. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20529. return this;
  20530. };
  20531. /**
  20532. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20533. * Supports definition of mesh facing forward or backward.
  20534. * @param flipBack defines the flip
  20535. * @param twirlClockwise defines the twirl
  20536. * @param tiltRight defines the tilt
  20537. * @returns the new rotation vector
  20538. */
  20539. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20540. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20541. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20542. };
  20543. /**
  20544. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20545. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20546. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20547. * @returns the new bounding vectors
  20548. */
  20549. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20550. if (includeDescendants === void 0) { includeDescendants = true; }
  20551. if (predicate === void 0) { predicate = null; }
  20552. // Ensures that all world matrix will be recomputed.
  20553. this.getScene().incrementRenderId();
  20554. this.computeWorldMatrix(true);
  20555. var min;
  20556. var max;
  20557. var boundingInfo = this.getBoundingInfo();
  20558. if (!this.subMeshes) {
  20559. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20560. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20561. }
  20562. else {
  20563. min = boundingInfo.boundingBox.minimumWorld;
  20564. max = boundingInfo.boundingBox.maximumWorld;
  20565. }
  20566. if (includeDescendants) {
  20567. var descendants = this.getDescendants(false);
  20568. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20569. var descendant = descendants_1[_i];
  20570. var childMesh = descendant;
  20571. childMesh.computeWorldMatrix(true);
  20572. // Filters meshes based on custom predicate function.
  20573. if (predicate && !predicate(childMesh)) {
  20574. continue;
  20575. }
  20576. //make sure we have the needed params to get mix and max
  20577. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20578. continue;
  20579. }
  20580. var childBoundingInfo = childMesh.getBoundingInfo();
  20581. var boundingBox = childBoundingInfo.boundingBox;
  20582. var minBox = boundingBox.minimumWorld;
  20583. var maxBox = boundingBox.maximumWorld;
  20584. BABYLON.Tools.CheckExtends(minBox, min, max);
  20585. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20586. }
  20587. }
  20588. return {
  20589. min: min,
  20590. max: max
  20591. };
  20592. };
  20593. /** @hidden */
  20594. AbstractMesh.prototype._updateBoundingInfo = function () {
  20595. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20596. this._boundingInfo.update(this.worldMatrixFromCache);
  20597. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20598. return this;
  20599. };
  20600. /** @hidden */
  20601. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20602. if (!this.subMeshes) {
  20603. return this;
  20604. }
  20605. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20606. var subMesh = this.subMeshes[subIndex];
  20607. if (!subMesh.IsGlobal) {
  20608. subMesh.updateBoundingInfo(matrix);
  20609. }
  20610. }
  20611. return this;
  20612. };
  20613. /** @hidden */
  20614. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20615. // Bounding info
  20616. this._updateBoundingInfo();
  20617. };
  20618. /**
  20619. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20620. * A mesh is in the frustum if its bounding box intersects the frustum
  20621. * @param frustumPlanes defines the frustum to test
  20622. * @returns true if the mesh is in the frustum planes
  20623. */
  20624. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20625. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20626. };
  20627. /**
  20628. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20629. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20630. * @param frustumPlanes defines the frustum to test
  20631. * @returns true if the mesh is completely in the frustum planes
  20632. */
  20633. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20634. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20635. };
  20636. /**
  20637. * True if the mesh intersects another mesh or a SolidParticle object
  20638. * @param mesh defines a target mesh or SolidParticle to test
  20639. * @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)
  20640. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20641. * @returns true if there is an intersection
  20642. */
  20643. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20644. if (precise === void 0) { precise = false; }
  20645. if (!this._boundingInfo || !mesh._boundingInfo) {
  20646. return false;
  20647. }
  20648. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20649. return true;
  20650. }
  20651. if (includeDescendants) {
  20652. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20653. var child = _a[_i];
  20654. if (child.intersectsMesh(mesh, precise, true)) {
  20655. return true;
  20656. }
  20657. }
  20658. }
  20659. return false;
  20660. };
  20661. /**
  20662. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20663. * @param point defines the point to test
  20664. * @returns true if there is an intersection
  20665. */
  20666. AbstractMesh.prototype.intersectsPoint = function (point) {
  20667. if (!this._boundingInfo) {
  20668. return false;
  20669. }
  20670. return this._boundingInfo.intersectsPoint(point);
  20671. };
  20672. /**
  20673. * Gets the current physics impostor
  20674. * @see http://doc.babylonjs.com/features/physics_engine
  20675. * @returns a physics impostor or null
  20676. */
  20677. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20678. return this.physicsImpostor;
  20679. };
  20680. /**
  20681. * Gets the position of the current mesh in camera space
  20682. * @param camera defines the camera to use
  20683. * @returns a position
  20684. */
  20685. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20686. if (camera === void 0) { camera = null; }
  20687. if (!camera) {
  20688. camera = this.getScene().activeCamera;
  20689. }
  20690. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20691. };
  20692. /**
  20693. * Returns the distance from the mesh to the active camera
  20694. * @param camera defines the camera to use
  20695. * @returns the distance
  20696. */
  20697. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20698. if (camera === void 0) { camera = null; }
  20699. if (!camera) {
  20700. camera = this.getScene().activeCamera;
  20701. }
  20702. return this.absolutePosition.subtract(camera.position).length();
  20703. };
  20704. /**
  20705. * Apply a physic impulse to the mesh
  20706. * @param force defines the force to apply
  20707. * @param contactPoint defines where to apply the force
  20708. * @returns the current mesh
  20709. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20710. */
  20711. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20712. if (!this.physicsImpostor) {
  20713. return this;
  20714. }
  20715. this.physicsImpostor.applyImpulse(force, contactPoint);
  20716. return this;
  20717. };
  20718. /**
  20719. * Creates a physic joint between two meshes
  20720. * @param otherMesh defines the other mesh to use
  20721. * @param pivot1 defines the pivot to use on this mesh
  20722. * @param pivot2 defines the pivot to use on the other mesh
  20723. * @param options defines additional options (can be plugin dependent)
  20724. * @returns the current mesh
  20725. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20726. */
  20727. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20728. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20729. return this;
  20730. }
  20731. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20732. mainPivot: pivot1,
  20733. connectedPivot: pivot2,
  20734. nativeParams: options
  20735. });
  20736. return this;
  20737. };
  20738. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20739. // Collisions
  20740. /**
  20741. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20742. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20743. */
  20744. get: function () {
  20745. return this._checkCollisions;
  20746. },
  20747. set: function (collisionEnabled) {
  20748. this._checkCollisions = collisionEnabled;
  20749. if (this.getScene().workerCollisions) {
  20750. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20751. }
  20752. },
  20753. enumerable: true,
  20754. configurable: true
  20755. });
  20756. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20757. /**
  20758. * Gets Collider object used to compute collisions (not physics)
  20759. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20760. */
  20761. get: function () {
  20762. return this._collider;
  20763. },
  20764. enumerable: true,
  20765. configurable: true
  20766. });
  20767. /**
  20768. * Move the mesh using collision engine
  20769. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20770. * @param displacement defines the requested displacement vector
  20771. * @returns the current mesh
  20772. */
  20773. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20774. var globalPosition = this.getAbsolutePosition();
  20775. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20776. if (!this._collider) {
  20777. this._collider = new BABYLON.Collider();
  20778. }
  20779. this._collider._radius = this.ellipsoid;
  20780. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20781. return this;
  20782. };
  20783. // Collisions
  20784. /** @hidden */
  20785. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20786. this._generatePointsArray();
  20787. if (!this._positions) {
  20788. return this;
  20789. }
  20790. // Transformation
  20791. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20792. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20793. subMesh._lastColliderWorldVertices = [];
  20794. subMesh._trianglePlanes = [];
  20795. var start = subMesh.verticesStart;
  20796. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20797. for (var i = start; i < end; i++) {
  20798. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20799. }
  20800. }
  20801. // Collide
  20802. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20803. if (collider.collisionFound) {
  20804. collider.collidedMesh = this;
  20805. }
  20806. return this;
  20807. };
  20808. /** @hidden */
  20809. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20810. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20811. var len = subMeshes.length;
  20812. for (var index = 0; index < len; index++) {
  20813. var subMesh = subMeshes.data[index];
  20814. // Bounding test
  20815. if (len > 1 && !subMesh._checkCollision(collider))
  20816. continue;
  20817. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20818. }
  20819. return this;
  20820. };
  20821. /** @hidden */
  20822. AbstractMesh.prototype._checkCollision = function (collider) {
  20823. // Bounding box test
  20824. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20825. return this;
  20826. // Transformation matrix
  20827. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20828. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20829. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20830. return this;
  20831. };
  20832. // Picking
  20833. /** @hidden */
  20834. AbstractMesh.prototype._generatePointsArray = function () {
  20835. return false;
  20836. };
  20837. /**
  20838. * Checks if the passed Ray intersects with the mesh
  20839. * @param ray defines the ray to use
  20840. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20841. * @returns the picking info
  20842. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20843. */
  20844. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20845. var pickingInfo = new BABYLON.PickingInfo();
  20846. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20847. return pickingInfo;
  20848. }
  20849. if (!this._generatePointsArray()) {
  20850. return pickingInfo;
  20851. }
  20852. var intersectInfo = null;
  20853. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20854. var len = subMeshes.length;
  20855. for (var index = 0; index < len; index++) {
  20856. var subMesh = subMeshes.data[index];
  20857. // Bounding test
  20858. if (len > 1 && !subMesh.canIntersects(ray))
  20859. continue;
  20860. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20861. if (currentIntersectInfo) {
  20862. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20863. intersectInfo = currentIntersectInfo;
  20864. intersectInfo.subMeshId = index;
  20865. if (fastCheck) {
  20866. break;
  20867. }
  20868. }
  20869. }
  20870. }
  20871. if (intersectInfo) {
  20872. // Get picked point
  20873. var world = this.getWorldMatrix();
  20874. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20875. var direction = ray.direction.clone();
  20876. direction = direction.scale(intersectInfo.distance);
  20877. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20878. var pickedPoint = worldOrigin.add(worldDirection);
  20879. // Return result
  20880. pickingInfo.hit = true;
  20881. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20882. pickingInfo.pickedPoint = pickedPoint;
  20883. pickingInfo.pickedMesh = this;
  20884. pickingInfo.bu = intersectInfo.bu || 0;
  20885. pickingInfo.bv = intersectInfo.bv || 0;
  20886. pickingInfo.faceId = intersectInfo.faceId;
  20887. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20888. return pickingInfo;
  20889. }
  20890. return pickingInfo;
  20891. };
  20892. /**
  20893. * Clones the current mesh
  20894. * @param name defines the mesh name
  20895. * @param newParent defines the new mesh parent
  20896. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20897. * @returns the new mesh
  20898. */
  20899. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20900. return null;
  20901. };
  20902. /**
  20903. * Disposes all the submeshes of the current meshnp
  20904. * @returns the current mesh
  20905. */
  20906. AbstractMesh.prototype.releaseSubMeshes = function () {
  20907. if (this.subMeshes) {
  20908. while (this.subMeshes.length) {
  20909. this.subMeshes[0].dispose();
  20910. }
  20911. }
  20912. else {
  20913. this.subMeshes = new Array();
  20914. }
  20915. return this;
  20916. };
  20917. /**
  20918. * Releases resources associated with this abstract mesh.
  20919. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20920. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20921. */
  20922. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20923. var _this = this;
  20924. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20925. var index;
  20926. // Smart Array Retainers.
  20927. this.getScene().freeActiveMeshes();
  20928. this.getScene().freeRenderingGroups();
  20929. // Action manager
  20930. if (this.actionManager !== undefined && this.actionManager !== null) {
  20931. this.actionManager.dispose();
  20932. this.actionManager = null;
  20933. }
  20934. // Skeleton
  20935. this._skeleton = null;
  20936. // Physics
  20937. if (this.physicsImpostor) {
  20938. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20939. }
  20940. // Intersections in progress
  20941. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20942. var other = this._intersectionsInProgress[index];
  20943. var pos = other._intersectionsInProgress.indexOf(this);
  20944. other._intersectionsInProgress.splice(pos, 1);
  20945. }
  20946. this._intersectionsInProgress = [];
  20947. // Lights
  20948. var lights = this.getScene().lights;
  20949. lights.forEach(function (light) {
  20950. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20951. if (meshIndex !== -1) {
  20952. light.includedOnlyMeshes.splice(meshIndex, 1);
  20953. }
  20954. meshIndex = light.excludedMeshes.indexOf(_this);
  20955. if (meshIndex !== -1) {
  20956. light.excludedMeshes.splice(meshIndex, 1);
  20957. }
  20958. // Shadow generators
  20959. var generator = light.getShadowGenerator();
  20960. if (generator) {
  20961. var shadowMap = generator.getShadowMap();
  20962. if (shadowMap && shadowMap.renderList) {
  20963. meshIndex = shadowMap.renderList.indexOf(_this);
  20964. if (meshIndex !== -1) {
  20965. shadowMap.renderList.splice(meshIndex, 1);
  20966. }
  20967. }
  20968. }
  20969. });
  20970. // SubMeshes
  20971. if (this.getClassName() !== "InstancedMesh") {
  20972. this.releaseSubMeshes();
  20973. }
  20974. // Query
  20975. var engine = this.getScene().getEngine();
  20976. if (this._occlusionQuery) {
  20977. this._isOcclusionQueryInProgress = false;
  20978. engine.deleteQuery(this._occlusionQuery);
  20979. this._occlusionQuery = null;
  20980. }
  20981. // Engine
  20982. engine.wipeCaches();
  20983. // Remove from scene
  20984. this.getScene().removeMesh(this);
  20985. if (disposeMaterialAndTextures) {
  20986. if (this.material) {
  20987. this.material.dispose(false, true);
  20988. }
  20989. }
  20990. if (!doNotRecurse) {
  20991. // Particles
  20992. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20993. if (this.getScene().particleSystems[index].emitter === this) {
  20994. this.getScene().particleSystems[index].dispose();
  20995. index--;
  20996. }
  20997. }
  20998. }
  20999. // facet data
  21000. if (this._facetDataEnabled) {
  21001. this.disableFacetData();
  21002. }
  21003. this.onAfterWorldMatrixUpdateObservable.clear();
  21004. this.onCollideObservable.clear();
  21005. this.onCollisionPositionChangeObservable.clear();
  21006. this.onRebuildObservable.clear();
  21007. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21008. };
  21009. /**
  21010. * Adds the passed mesh as a child to the current mesh
  21011. * @param mesh defines the child mesh
  21012. * @returns the current mesh
  21013. */
  21014. AbstractMesh.prototype.addChild = function (mesh) {
  21015. mesh.setParent(this);
  21016. return this;
  21017. };
  21018. /**
  21019. * Removes the passed mesh from the current mesh children list
  21020. * @param mesh defines the child mesh
  21021. * @returns the current mesh
  21022. */
  21023. AbstractMesh.prototype.removeChild = function (mesh) {
  21024. mesh.setParent(null);
  21025. return this;
  21026. };
  21027. // Facet data
  21028. /** @hidden */
  21029. AbstractMesh.prototype._initFacetData = function () {
  21030. if (!this._facetNormals) {
  21031. this._facetNormals = new Array();
  21032. }
  21033. if (!this._facetPositions) {
  21034. this._facetPositions = new Array();
  21035. }
  21036. if (!this._facetPartitioning) {
  21037. this._facetPartitioning = new Array();
  21038. }
  21039. this._facetNb = (this.getIndices().length / 3) | 0;
  21040. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21041. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21042. for (var f = 0; f < this._facetNb; f++) {
  21043. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21044. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21045. }
  21046. this._facetDataEnabled = true;
  21047. return this;
  21048. };
  21049. /**
  21050. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21051. * This method can be called within the render loop.
  21052. * 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
  21053. * @returns the current mesh
  21054. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21055. */
  21056. AbstractMesh.prototype.updateFacetData = function () {
  21057. if (!this._facetDataEnabled) {
  21058. this._initFacetData();
  21059. }
  21060. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21061. var indices = this.getIndices();
  21062. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21063. var bInfo = this.getBoundingInfo();
  21064. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21065. // init arrays, matrix and sort function on first call
  21066. this._facetDepthSortEnabled = true;
  21067. if (indices instanceof Uint16Array) {
  21068. this._depthSortedIndices = new Uint16Array(indices);
  21069. }
  21070. else if (indices instanceof Uint32Array) {
  21071. this._depthSortedIndices = new Uint32Array(indices);
  21072. }
  21073. else {
  21074. var needs32bits = false;
  21075. for (var i = 0; i < indices.length; i++) {
  21076. if (indices[i] > 65535) {
  21077. needs32bits = true;
  21078. break;
  21079. }
  21080. }
  21081. if (needs32bits) {
  21082. this._depthSortedIndices = new Uint32Array(indices);
  21083. }
  21084. else {
  21085. this._depthSortedIndices = new Uint16Array(indices);
  21086. }
  21087. }
  21088. this._facetDepthSortFunction = function (f1, f2) {
  21089. return (f2.sqDistance - f1.sqDistance);
  21090. };
  21091. if (!this._facetDepthSortFrom) {
  21092. var camera = this.getScene().activeCamera;
  21093. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21094. }
  21095. this._depthSortedFacets = [];
  21096. for (var f = 0; f < this._facetNb; f++) {
  21097. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21098. this._depthSortedFacets.push(depthSortedFacet);
  21099. }
  21100. this._invertedMatrix = BABYLON.Matrix.Identity();
  21101. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21102. }
  21103. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21104. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21105. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21106. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21107. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21108. this._subDiv.max = this._partitioningSubdivisions;
  21109. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21110. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21111. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21112. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21113. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21114. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21115. // set the parameters for ComputeNormals()
  21116. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21117. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21118. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21119. this._facetParameters.bInfo = bInfo;
  21120. this._facetParameters.bbSize = this._bbSize;
  21121. this._facetParameters.subDiv = this._subDiv;
  21122. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21123. this._facetParameters.depthSort = this._facetDepthSort;
  21124. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21125. this.computeWorldMatrix(true);
  21126. this._worldMatrix.invertToRef(this._invertedMatrix);
  21127. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21128. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21129. }
  21130. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21131. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21132. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21133. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21134. var l = (this._depthSortedIndices.length / 3) | 0;
  21135. for (var f = 0; f < l; f++) {
  21136. var sind = this._depthSortedFacets[f].ind;
  21137. this._depthSortedIndices[f * 3] = indices[sind];
  21138. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21139. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21140. }
  21141. this.updateIndices(this._depthSortedIndices);
  21142. }
  21143. return this;
  21144. };
  21145. /**
  21146. * Returns the facetLocalNormals array.
  21147. * The normals are expressed in the mesh local spac
  21148. * @returns an array of Vector3
  21149. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21150. */
  21151. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21152. if (!this._facetNormals) {
  21153. this.updateFacetData();
  21154. }
  21155. return this._facetNormals;
  21156. };
  21157. /**
  21158. * Returns the facetLocalPositions array.
  21159. * The facet positions are expressed in the mesh local space
  21160. * @returns an array of Vector3
  21161. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21162. */
  21163. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21164. if (!this._facetPositions) {
  21165. this.updateFacetData();
  21166. }
  21167. return this._facetPositions;
  21168. };
  21169. /**
  21170. * Returns the facetLocalPartioning array
  21171. * @returns an array of array of numbers
  21172. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21173. */
  21174. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21175. if (!this._facetPartitioning) {
  21176. this.updateFacetData();
  21177. }
  21178. return this._facetPartitioning;
  21179. };
  21180. /**
  21181. * Returns the i-th facet position in the world system.
  21182. * This method allocates a new Vector3 per call
  21183. * @param i defines the facet index
  21184. * @returns a new Vector3
  21185. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21186. */
  21187. AbstractMesh.prototype.getFacetPosition = function (i) {
  21188. var pos = BABYLON.Vector3.Zero();
  21189. this.getFacetPositionToRef(i, pos);
  21190. return pos;
  21191. };
  21192. /**
  21193. * Sets the reference Vector3 with the i-th facet position in the world system
  21194. * @param i defines the facet index
  21195. * @param ref defines the target vector
  21196. * @returns the current mesh
  21197. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21198. */
  21199. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21200. var localPos = (this.getFacetLocalPositions())[i];
  21201. var world = this.getWorldMatrix();
  21202. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21203. return this;
  21204. };
  21205. /**
  21206. * Returns the i-th facet normal in the world system.
  21207. * This method allocates a new Vector3 per call
  21208. * @param i defines the facet index
  21209. * @returns a new Vector3
  21210. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21211. */
  21212. AbstractMesh.prototype.getFacetNormal = function (i) {
  21213. var norm = BABYLON.Vector3.Zero();
  21214. this.getFacetNormalToRef(i, norm);
  21215. return norm;
  21216. };
  21217. /**
  21218. * Sets the reference Vector3 with the i-th facet normal in the world system
  21219. * @param i defines the facet index
  21220. * @param ref defines the target vector
  21221. * @returns the current mesh
  21222. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21223. */
  21224. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21225. var localNorm = (this.getFacetLocalNormals())[i];
  21226. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21227. return this;
  21228. };
  21229. /**
  21230. * 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)
  21231. * @param x defines x coordinate
  21232. * @param y defines y coordinate
  21233. * @param z defines z coordinate
  21234. * @returns the array of facet indexes
  21235. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21236. */
  21237. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21238. var bInfo = this.getBoundingInfo();
  21239. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21240. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21241. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21242. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21243. return null;
  21244. }
  21245. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21246. };
  21247. /**
  21248. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21249. * @param projected sets as the (x,y,z) world projection on the facet
  21250. * @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
  21251. * @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
  21252. * @param x defines x coordinate
  21253. * @param y defines y coordinate
  21254. * @param z defines z coordinate
  21255. * @returns the face index if found (or null instead)
  21256. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21257. */
  21258. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21259. if (checkFace === void 0) { checkFace = false; }
  21260. if (facing === void 0) { facing = true; }
  21261. var world = this.getWorldMatrix();
  21262. var invMat = BABYLON.Tmp.Matrix[5];
  21263. world.invertToRef(invMat);
  21264. var invVect = BABYLON.Tmp.Vector3[8];
  21265. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21266. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21267. if (projected) {
  21268. // tranform the local computed projected vector to world coordinates
  21269. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21270. }
  21271. return closest;
  21272. };
  21273. /**
  21274. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21275. * @param projected sets as the (x,y,z) local projection on the facet
  21276. * @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
  21277. * @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
  21278. * @param x defines x coordinate
  21279. * @param y defines y coordinate
  21280. * @param z defines z coordinate
  21281. * @returns the face index if found (or null instead)
  21282. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21283. */
  21284. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21285. if (checkFace === void 0) { checkFace = false; }
  21286. if (facing === void 0) { facing = true; }
  21287. var closest = null;
  21288. var tmpx = 0.0;
  21289. var tmpy = 0.0;
  21290. var tmpz = 0.0;
  21291. var d = 0.0; // tmp dot facet normal * facet position
  21292. var t0 = 0.0;
  21293. var projx = 0.0;
  21294. var projy = 0.0;
  21295. var projz = 0.0;
  21296. // Get all the facets in the same partitioning block than (x, y, z)
  21297. var facetPositions = this.getFacetLocalPositions();
  21298. var facetNormals = this.getFacetLocalNormals();
  21299. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21300. if (!facetsInBlock) {
  21301. return null;
  21302. }
  21303. // Get the closest facet to (x, y, z)
  21304. var shortest = Number.MAX_VALUE; // init distance vars
  21305. var tmpDistance = shortest;
  21306. var fib; // current facet in the block
  21307. var norm; // current facet normal
  21308. var p0; // current facet barycenter position
  21309. // loop on all the facets in the current partitioning block
  21310. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21311. fib = facetsInBlock[idx];
  21312. norm = facetNormals[fib];
  21313. p0 = facetPositions[fib];
  21314. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21315. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21316. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21317. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21318. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21319. projx = x + norm.x * t0;
  21320. projy = y + norm.y * t0;
  21321. projz = z + norm.z * t0;
  21322. tmpx = projx - x;
  21323. tmpy = projy - y;
  21324. tmpz = projz - z;
  21325. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21326. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21327. shortest = tmpDistance;
  21328. closest = fib;
  21329. if (projected) {
  21330. projected.x = projx;
  21331. projected.y = projy;
  21332. projected.z = projz;
  21333. }
  21334. }
  21335. }
  21336. }
  21337. return closest;
  21338. };
  21339. /**
  21340. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21341. * @returns the parameters
  21342. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21343. */
  21344. AbstractMesh.prototype.getFacetDataParameters = function () {
  21345. return this._facetParameters;
  21346. };
  21347. /**
  21348. * Disables the feature FacetData and frees the related memory
  21349. * @returns the current mesh
  21350. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21351. */
  21352. AbstractMesh.prototype.disableFacetData = function () {
  21353. if (this._facetDataEnabled) {
  21354. this._facetDataEnabled = false;
  21355. this._facetPositions = new Array();
  21356. this._facetNormals = new Array();
  21357. this._facetPartitioning = new Array();
  21358. this._facetParameters = null;
  21359. this._depthSortedIndices = new Uint32Array(0);
  21360. }
  21361. return this;
  21362. };
  21363. /**
  21364. * Updates the AbstractMesh indices array
  21365. * @param indices defines the data source
  21366. * @returns the current mesh
  21367. */
  21368. AbstractMesh.prototype.updateIndices = function (indices) {
  21369. return this;
  21370. };
  21371. /**
  21372. * Creates new normals data for the mesh
  21373. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21374. * @returns the current mesh
  21375. */
  21376. AbstractMesh.prototype.createNormals = function (updatable) {
  21377. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21378. var indices = this.getIndices();
  21379. var normals;
  21380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21381. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21382. }
  21383. else {
  21384. normals = [];
  21385. }
  21386. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21387. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21388. return this;
  21389. };
  21390. /**
  21391. * Align the mesh with a normal
  21392. * @param normal defines the normal to use
  21393. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21394. * @returns the current mesh
  21395. */
  21396. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21397. if (!upDirection) {
  21398. upDirection = BABYLON.Axis.Y;
  21399. }
  21400. var axisX = BABYLON.Tmp.Vector3[0];
  21401. var axisZ = BABYLON.Tmp.Vector3[1];
  21402. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21403. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21404. if (this.rotationQuaternion) {
  21405. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21406. }
  21407. else {
  21408. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21409. }
  21410. return this;
  21411. };
  21412. /** @hidden */
  21413. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21414. this._isOccluded = false;
  21415. };
  21416. /** No occlusion */
  21417. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21418. /** Occlusion set to optimisitic */
  21419. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21420. /** Occlusion set to strict */
  21421. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21422. /** Use an accurante occlusion algorithm */
  21423. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21424. /** Use a conservative occlusion algorithm */
  21425. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21426. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21427. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21428. /** Culling strategy with bounding sphere only and then frustum culling */
  21429. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21430. return AbstractMesh;
  21431. }(BABYLON.TransformNode));
  21432. BABYLON.AbstractMesh = AbstractMesh;
  21433. })(BABYLON || (BABYLON = {}));
  21434. //# sourceMappingURL=babylon.abstractMesh.js.map
  21435. var BABYLON;
  21436. (function (BABYLON) {
  21437. /**
  21438. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21439. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21440. * 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.
  21441. */
  21442. var Light = /** @class */ (function (_super) {
  21443. __extends(Light, _super);
  21444. /**
  21445. * Creates a Light object in the scene.
  21446. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21447. * @param name The firendly name of the light
  21448. * @param scene The scene the light belongs too
  21449. */
  21450. function Light(name, scene) {
  21451. var _this = _super.call(this, name, scene) || this;
  21452. /**
  21453. * Diffuse gives the basic color to an object.
  21454. */
  21455. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21456. /**
  21457. * Specular produces a highlight color on an object.
  21458. * Note: This is note affecting PBR materials.
  21459. */
  21460. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21461. /**
  21462. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21463. * falling off base on range or angle.
  21464. * This can be set to any values in Light.FALLOFF_x.
  21465. *
  21466. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21467. * other types of materials.
  21468. */
  21469. _this.falloffType = Light.FALLOFF_DEFAULT;
  21470. /**
  21471. * Strength of the light.
  21472. * Note: By default it is define in the framework own unit.
  21473. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21474. */
  21475. _this.intensity = 1.0;
  21476. _this._range = Number.MAX_VALUE;
  21477. _this._inverseSquaredRange = 0;
  21478. /**
  21479. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21480. * of light.
  21481. */
  21482. _this._photometricScale = 1.0;
  21483. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21484. _this._radius = 0.00001;
  21485. /**
  21486. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21487. * exceeding the number allowed of the materials.
  21488. */
  21489. _this.renderPriority = 0;
  21490. _this._shadowEnabled = true;
  21491. _this._excludeWithLayerMask = 0;
  21492. _this._includeOnlyWithLayerMask = 0;
  21493. _this._lightmapMode = 0;
  21494. /**
  21495. * @hidden Internal use only.
  21496. */
  21497. _this._excludedMeshesIds = new Array();
  21498. /**
  21499. * @hidden Internal use only.
  21500. */
  21501. _this._includedOnlyMeshesIds = new Array();
  21502. _this.getScene().addLight(_this);
  21503. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21504. _this._buildUniformLayout();
  21505. _this.includedOnlyMeshes = new Array();
  21506. _this.excludedMeshes = new Array();
  21507. _this._resyncMeshes();
  21508. return _this;
  21509. }
  21510. Object.defineProperty(Light.prototype, "range", {
  21511. /**
  21512. * Defines how far from the source the light is impacting in scene units.
  21513. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21514. */
  21515. get: function () {
  21516. return this._range;
  21517. },
  21518. /**
  21519. * Defines how far from the source the light is impacting in scene units.
  21520. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21521. */
  21522. set: function (value) {
  21523. this._range = value;
  21524. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21525. },
  21526. enumerable: true,
  21527. configurable: true
  21528. });
  21529. Object.defineProperty(Light.prototype, "intensityMode", {
  21530. /**
  21531. * Gets the photometric scale used to interpret the intensity.
  21532. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21533. */
  21534. get: function () {
  21535. return this._intensityMode;
  21536. },
  21537. /**
  21538. * Sets the photometric scale used to interpret the intensity.
  21539. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21540. */
  21541. set: function (value) {
  21542. this._intensityMode = value;
  21543. this._computePhotometricScale();
  21544. },
  21545. enumerable: true,
  21546. configurable: true
  21547. });
  21548. ;
  21549. ;
  21550. Object.defineProperty(Light.prototype, "radius", {
  21551. /**
  21552. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21553. */
  21554. get: function () {
  21555. return this._radius;
  21556. },
  21557. /**
  21558. * sets the light radius used by PBR Materials to simulate soft area lights.
  21559. */
  21560. set: function (value) {
  21561. this._radius = value;
  21562. this._computePhotometricScale();
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. ;
  21568. ;
  21569. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21570. /**
  21571. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21572. * the current shadow generator.
  21573. */
  21574. get: function () {
  21575. return this._shadowEnabled;
  21576. },
  21577. /**
  21578. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21579. * the current shadow generator.
  21580. */
  21581. set: function (value) {
  21582. if (this._shadowEnabled === value) {
  21583. return;
  21584. }
  21585. this._shadowEnabled = value;
  21586. this._markMeshesAsLightDirty();
  21587. },
  21588. enumerable: true,
  21589. configurable: true
  21590. });
  21591. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21592. /**
  21593. * Gets the only meshes impacted by this light.
  21594. */
  21595. get: function () {
  21596. return this._includedOnlyMeshes;
  21597. },
  21598. /**
  21599. * Sets the only meshes impacted by this light.
  21600. */
  21601. set: function (value) {
  21602. this._includedOnlyMeshes = value;
  21603. this._hookArrayForIncludedOnly(value);
  21604. },
  21605. enumerable: true,
  21606. configurable: true
  21607. });
  21608. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21609. /**
  21610. * Gets the meshes not impacted by this light.
  21611. */
  21612. get: function () {
  21613. return this._excludedMeshes;
  21614. },
  21615. /**
  21616. * Sets the meshes not impacted by this light.
  21617. */
  21618. set: function (value) {
  21619. this._excludedMeshes = value;
  21620. this._hookArrayForExcluded(value);
  21621. },
  21622. enumerable: true,
  21623. configurable: true
  21624. });
  21625. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21626. /**
  21627. * Gets the layer id use to find what meshes are not impacted by the light.
  21628. * Inactive if 0
  21629. */
  21630. get: function () {
  21631. return this._excludeWithLayerMask;
  21632. },
  21633. /**
  21634. * Sets the layer id use to find what meshes are not impacted by the light.
  21635. * Inactive if 0
  21636. */
  21637. set: function (value) {
  21638. this._excludeWithLayerMask = value;
  21639. this._resyncMeshes();
  21640. },
  21641. enumerable: true,
  21642. configurable: true
  21643. });
  21644. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21645. /**
  21646. * Gets the layer id use to find what meshes are impacted by the light.
  21647. * Inactive if 0
  21648. */
  21649. get: function () {
  21650. return this._includeOnlyWithLayerMask;
  21651. },
  21652. /**
  21653. * Sets the layer id use to find what meshes are impacted by the light.
  21654. * Inactive if 0
  21655. */
  21656. set: function (value) {
  21657. this._includeOnlyWithLayerMask = value;
  21658. this._resyncMeshes();
  21659. },
  21660. enumerable: true,
  21661. configurable: true
  21662. });
  21663. Object.defineProperty(Light.prototype, "lightmapMode", {
  21664. /**
  21665. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21666. */
  21667. get: function () {
  21668. return this._lightmapMode;
  21669. },
  21670. /**
  21671. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21672. */
  21673. set: function (value) {
  21674. if (this._lightmapMode === value) {
  21675. return;
  21676. }
  21677. this._lightmapMode = value;
  21678. this._markMeshesAsLightDirty();
  21679. },
  21680. enumerable: true,
  21681. configurable: true
  21682. });
  21683. /**
  21684. * Returns the string "Light".
  21685. * @returns the class name
  21686. */
  21687. Light.prototype.getClassName = function () {
  21688. return "Light";
  21689. };
  21690. /**
  21691. * Converts the light information to a readable string for debug purpose.
  21692. * @param fullDetails Supports for multiple levels of logging within scene loading
  21693. * @returns the human readable light info
  21694. */
  21695. Light.prototype.toString = function (fullDetails) {
  21696. var ret = "Name: " + this.name;
  21697. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21698. if (this.animations) {
  21699. for (var i = 0; i < this.animations.length; i++) {
  21700. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21701. }
  21702. }
  21703. if (fullDetails) {
  21704. }
  21705. return ret;
  21706. };
  21707. /**
  21708. * Set the enabled state of this node.
  21709. * @param value - the new enabled state
  21710. */
  21711. Light.prototype.setEnabled = function (value) {
  21712. _super.prototype.setEnabled.call(this, value);
  21713. this._resyncMeshes();
  21714. };
  21715. /**
  21716. * Returns the Light associated shadow generator if any.
  21717. * @return the associated shadow generator.
  21718. */
  21719. Light.prototype.getShadowGenerator = function () {
  21720. return this._shadowGenerator;
  21721. };
  21722. /**
  21723. * Returns a Vector3, the absolute light position in the World.
  21724. * @returns the world space position of the light
  21725. */
  21726. Light.prototype.getAbsolutePosition = function () {
  21727. return BABYLON.Vector3.Zero();
  21728. };
  21729. /**
  21730. * Specifies if the light will affect the passed mesh.
  21731. * @param mesh The mesh to test against the light
  21732. * @return true the mesh is affected otherwise, false.
  21733. */
  21734. Light.prototype.canAffectMesh = function (mesh) {
  21735. if (!mesh) {
  21736. return true;
  21737. }
  21738. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21739. return false;
  21740. }
  21741. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21742. return false;
  21743. }
  21744. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21745. return false;
  21746. }
  21747. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21748. return false;
  21749. }
  21750. return true;
  21751. };
  21752. /**
  21753. * Sort function to order lights for rendering.
  21754. * @param a First Light object to compare to second.
  21755. * @param b Second Light object to compare first.
  21756. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21757. */
  21758. Light.CompareLightsPriority = function (a, b) {
  21759. //shadow-casting lights have priority over non-shadow-casting lights
  21760. //the renderPrioirty is a secondary sort criterion
  21761. if (a.shadowEnabled !== b.shadowEnabled) {
  21762. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21763. }
  21764. return b.renderPriority - a.renderPriority;
  21765. };
  21766. /**
  21767. * Releases resources associated with this node.
  21768. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21769. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21770. */
  21771. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21772. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21773. if (this._shadowGenerator) {
  21774. this._shadowGenerator.dispose();
  21775. this._shadowGenerator = null;
  21776. }
  21777. // Animations
  21778. this.getScene().stopAnimation(this);
  21779. // Remove from meshes
  21780. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21781. var mesh = _a[_i];
  21782. mesh._removeLightSource(this);
  21783. }
  21784. this._uniformBuffer.dispose();
  21785. // Remove from scene
  21786. this.getScene().removeLight(this);
  21787. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21788. };
  21789. /**
  21790. * Returns the light type ID (integer).
  21791. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21792. */
  21793. Light.prototype.getTypeID = function () {
  21794. return 0;
  21795. };
  21796. /**
  21797. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21798. * @returns the scaled intensity in intensity mode unit
  21799. */
  21800. Light.prototype.getScaledIntensity = function () {
  21801. return this._photometricScale * this.intensity;
  21802. };
  21803. /**
  21804. * Returns a new Light object, named "name", from the current one.
  21805. * @param name The name of the cloned light
  21806. * @returns the new created light
  21807. */
  21808. Light.prototype.clone = function (name) {
  21809. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21810. if (!constructor) {
  21811. return null;
  21812. }
  21813. return BABYLON.SerializationHelper.Clone(constructor, this);
  21814. };
  21815. /**
  21816. * Serializes the current light into a Serialization object.
  21817. * @returns the serialized object.
  21818. */
  21819. Light.prototype.serialize = function () {
  21820. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21821. // Type
  21822. serializationObject.type = this.getTypeID();
  21823. // Parent
  21824. if (this.parent) {
  21825. serializationObject.parentId = this.parent.id;
  21826. }
  21827. // Inclusion / exclusions
  21828. if (this.excludedMeshes.length > 0) {
  21829. serializationObject.excludedMeshesIds = [];
  21830. this.excludedMeshes.forEach(function (mesh) {
  21831. serializationObject.excludedMeshesIds.push(mesh.id);
  21832. });
  21833. }
  21834. if (this.includedOnlyMeshes.length > 0) {
  21835. serializationObject.includedOnlyMeshesIds = [];
  21836. this.includedOnlyMeshes.forEach(function (mesh) {
  21837. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21838. });
  21839. }
  21840. // Animations
  21841. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21842. serializationObject.ranges = this.serializeAnimationRanges();
  21843. return serializationObject;
  21844. };
  21845. /**
  21846. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21847. * This new light is named "name" and added to the passed scene.
  21848. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21849. * @param name The friendly name of the light
  21850. * @param scene The scene the new light will belong to
  21851. * @returns the constructor function
  21852. */
  21853. Light.GetConstructorFromName = function (type, name, scene) {
  21854. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21855. if (constructorFunc) {
  21856. return constructorFunc;
  21857. }
  21858. // Default to no light for none present once.
  21859. return null;
  21860. };
  21861. /**
  21862. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21863. * @param parsedLight The JSON representation of the light
  21864. * @param scene The scene to create the parsed light in
  21865. * @returns the created light after parsing
  21866. */
  21867. Light.Parse = function (parsedLight, scene) {
  21868. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21869. if (!constructor) {
  21870. return null;
  21871. }
  21872. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21873. // Inclusion / exclusions
  21874. if (parsedLight.excludedMeshesIds) {
  21875. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21876. }
  21877. if (parsedLight.includedOnlyMeshesIds) {
  21878. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21879. }
  21880. // Parent
  21881. if (parsedLight.parentId) {
  21882. light._waitingParentId = parsedLight.parentId;
  21883. }
  21884. // Animations
  21885. if (parsedLight.animations) {
  21886. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21887. var parsedAnimation = parsedLight.animations[animationIndex];
  21888. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21889. }
  21890. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21891. }
  21892. if (parsedLight.autoAnimate) {
  21893. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21894. }
  21895. return light;
  21896. };
  21897. Light.prototype._hookArrayForExcluded = function (array) {
  21898. var _this = this;
  21899. var oldPush = array.push;
  21900. array.push = function () {
  21901. var items = [];
  21902. for (var _i = 0; _i < arguments.length; _i++) {
  21903. items[_i] = arguments[_i];
  21904. }
  21905. var result = oldPush.apply(array, items);
  21906. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21907. var item = items_1[_a];
  21908. item._resyncLighSource(_this);
  21909. }
  21910. return result;
  21911. };
  21912. var oldSplice = array.splice;
  21913. array.splice = function (index, deleteCount) {
  21914. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21915. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21916. var item = deleted_1[_i];
  21917. item._resyncLighSource(_this);
  21918. }
  21919. return deleted;
  21920. };
  21921. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21922. var item = array_1[_i];
  21923. item._resyncLighSource(this);
  21924. }
  21925. };
  21926. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21927. var _this = this;
  21928. var oldPush = array.push;
  21929. array.push = function () {
  21930. var items = [];
  21931. for (var _i = 0; _i < arguments.length; _i++) {
  21932. items[_i] = arguments[_i];
  21933. }
  21934. var result = oldPush.apply(array, items);
  21935. _this._resyncMeshes();
  21936. return result;
  21937. };
  21938. var oldSplice = array.splice;
  21939. array.splice = function (index, deleteCount) {
  21940. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21941. _this._resyncMeshes();
  21942. return deleted;
  21943. };
  21944. this._resyncMeshes();
  21945. };
  21946. Light.prototype._resyncMeshes = function () {
  21947. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21948. var mesh = _a[_i];
  21949. mesh._resyncLighSource(this);
  21950. }
  21951. };
  21952. /**
  21953. * Forces the meshes to update their light related information in their rendering used effects
  21954. * @hidden Internal Use Only
  21955. */
  21956. Light.prototype._markMeshesAsLightDirty = function () {
  21957. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21958. var mesh = _a[_i];
  21959. if (mesh._lightSources.indexOf(this) !== -1) {
  21960. mesh._markSubMeshesAsLightDirty();
  21961. }
  21962. }
  21963. };
  21964. /**
  21965. * Recomputes the cached photometric scale if needed.
  21966. */
  21967. Light.prototype._computePhotometricScale = function () {
  21968. this._photometricScale = this._getPhotometricScale();
  21969. this.getScene().resetCachedMaterial();
  21970. };
  21971. /**
  21972. * Returns the Photometric Scale according to the light type and intensity mode.
  21973. */
  21974. Light.prototype._getPhotometricScale = function () {
  21975. var photometricScale = 0.0;
  21976. var lightTypeID = this.getTypeID();
  21977. //get photometric mode
  21978. var photometricMode = this.intensityMode;
  21979. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21980. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21981. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21982. }
  21983. else {
  21984. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21985. }
  21986. }
  21987. //compute photometric scale
  21988. switch (lightTypeID) {
  21989. case Light.LIGHTTYPEID_POINTLIGHT:
  21990. case Light.LIGHTTYPEID_SPOTLIGHT:
  21991. switch (photometricMode) {
  21992. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21993. photometricScale = 1.0 / (4.0 * Math.PI);
  21994. break;
  21995. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21996. photometricScale = 1.0;
  21997. break;
  21998. case Light.INTENSITYMODE_LUMINANCE:
  21999. photometricScale = this.radius * this.radius;
  22000. break;
  22001. }
  22002. break;
  22003. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22004. switch (photometricMode) {
  22005. case Light.INTENSITYMODE_ILLUMINANCE:
  22006. photometricScale = 1.0;
  22007. break;
  22008. case Light.INTENSITYMODE_LUMINANCE:
  22009. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22010. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22011. var apexAngleRadians = this.radius;
  22012. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22013. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22014. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22015. photometricScale = solidAngle;
  22016. break;
  22017. }
  22018. break;
  22019. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22020. // No fall off in hemisperic light.
  22021. photometricScale = 1.0;
  22022. break;
  22023. }
  22024. return photometricScale;
  22025. };
  22026. /**
  22027. * Reorder the light in the scene according to their defined priority.
  22028. * @hidden Internal Use Only
  22029. */
  22030. Light.prototype._reorderLightsInScene = function () {
  22031. var scene = this.getScene();
  22032. if (this._renderPriority != 0) {
  22033. scene.requireLightSorting = true;
  22034. }
  22035. this.getScene().sortLightsByPriority();
  22036. };
  22037. /**
  22038. * Falloff Default: light is falling off following the material specification:
  22039. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22040. */
  22041. Light.FALLOFF_DEFAULT = 0;
  22042. /**
  22043. * Falloff Physical: light is falling off following the inverse squared distance law.
  22044. */
  22045. Light.FALLOFF_PHYSICAL = 1;
  22046. /**
  22047. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22048. * to enhance interoperability with other engines.
  22049. */
  22050. Light.FALLOFF_GLTF = 2;
  22051. /**
  22052. * Falloff Standard: light is falling off like in the standard material
  22053. * to enhance interoperability with other materials.
  22054. */
  22055. Light.FALLOFF_STANDARD = 3;
  22056. //lightmapMode Consts
  22057. /**
  22058. * If every light affecting the material is in this lightmapMode,
  22059. * material.lightmapTexture adds or multiplies
  22060. * (depends on material.useLightmapAsShadowmap)
  22061. * after every other light calculations.
  22062. */
  22063. Light.LIGHTMAP_DEFAULT = 0;
  22064. /**
  22065. * material.lightmapTexture as only diffuse lighting from this light
  22066. * adds only specular lighting from this light
  22067. * adds dynamic shadows
  22068. */
  22069. Light.LIGHTMAP_SPECULAR = 1;
  22070. /**
  22071. * material.lightmapTexture as only lighting
  22072. * no light calculation from this light
  22073. * only adds dynamic shadows from this light
  22074. */
  22075. Light.LIGHTMAP_SHADOWSONLY = 2;
  22076. // Intensity Mode Consts
  22077. /**
  22078. * Each light type uses the default quantity according to its type:
  22079. * point/spot lights use luminous intensity
  22080. * directional lights use illuminance
  22081. */
  22082. Light.INTENSITYMODE_AUTOMATIC = 0;
  22083. /**
  22084. * lumen (lm)
  22085. */
  22086. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22087. /**
  22088. * candela (lm/sr)
  22089. */
  22090. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22091. /**
  22092. * lux (lm/m^2)
  22093. */
  22094. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22095. /**
  22096. * nit (cd/m^2)
  22097. */
  22098. Light.INTENSITYMODE_LUMINANCE = 4;
  22099. // Light types ids const.
  22100. /**
  22101. * Light type const id of the point light.
  22102. */
  22103. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22104. /**
  22105. * Light type const id of the directional light.
  22106. */
  22107. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22108. /**
  22109. * Light type const id of the spot light.
  22110. */
  22111. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22112. /**
  22113. * Light type const id of the hemispheric light.
  22114. */
  22115. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22116. __decorate([
  22117. BABYLON.serializeAsColor3()
  22118. ], Light.prototype, "diffuse", void 0);
  22119. __decorate([
  22120. BABYLON.serializeAsColor3()
  22121. ], Light.prototype, "specular", void 0);
  22122. __decorate([
  22123. BABYLON.serialize()
  22124. ], Light.prototype, "falloffType", void 0);
  22125. __decorate([
  22126. BABYLON.serialize()
  22127. ], Light.prototype, "intensity", void 0);
  22128. __decorate([
  22129. BABYLON.serialize()
  22130. ], Light.prototype, "range", null);
  22131. __decorate([
  22132. BABYLON.serialize()
  22133. ], Light.prototype, "intensityMode", null);
  22134. __decorate([
  22135. BABYLON.serialize()
  22136. ], Light.prototype, "radius", null);
  22137. __decorate([
  22138. BABYLON.serialize()
  22139. ], Light.prototype, "_renderPriority", void 0);
  22140. __decorate([
  22141. BABYLON.expandToProperty("_reorderLightsInScene")
  22142. ], Light.prototype, "renderPriority", void 0);
  22143. __decorate([
  22144. BABYLON.serialize("shadowEnabled")
  22145. ], Light.prototype, "_shadowEnabled", void 0);
  22146. __decorate([
  22147. BABYLON.serialize("excludeWithLayerMask")
  22148. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22149. __decorate([
  22150. BABYLON.serialize("includeOnlyWithLayerMask")
  22151. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22152. __decorate([
  22153. BABYLON.serialize("lightmapMode")
  22154. ], Light.prototype, "_lightmapMode", void 0);
  22155. return Light;
  22156. }(BABYLON.Node));
  22157. BABYLON.Light = Light;
  22158. })(BABYLON || (BABYLON = {}));
  22159. //# sourceMappingURL=babylon.light.js.map
  22160. var BABYLON;
  22161. (function (BABYLON) {
  22162. var Camera = /** @class */ (function (_super) {
  22163. __extends(Camera, _super);
  22164. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22165. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22166. var _this = _super.call(this, name, scene) || this;
  22167. /**
  22168. * The vector the camera should consider as up.
  22169. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22170. */
  22171. _this.upVector = BABYLON.Vector3.Up();
  22172. _this.orthoLeft = null;
  22173. _this.orthoRight = null;
  22174. _this.orthoBottom = null;
  22175. _this.orthoTop = null;
  22176. /**
  22177. * FOV is set in Radians. (default is 0.8)
  22178. */
  22179. _this.fov = 0.8;
  22180. _this.minZ = 1;
  22181. _this.maxZ = 10000.0;
  22182. _this.inertia = 0.9;
  22183. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22184. _this.isIntermediate = false;
  22185. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22186. /**
  22187. * Restricts the camera to viewing objects with the same layerMask.
  22188. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22189. */
  22190. _this.layerMask = 0x0FFFFFFF;
  22191. /**
  22192. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22193. */
  22194. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22195. // Camera rig members
  22196. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22197. /** @hidden */
  22198. _this._rigCameras = new Array();
  22199. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22200. /** @hidden */
  22201. _this._skipRendering = false;
  22202. _this.customRenderTargets = new Array();
  22203. // Observables
  22204. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22205. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22206. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22207. _this.onRestoreStateObservable = new BABYLON.Observable();
  22208. // Cache
  22209. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22210. _this._projectionMatrix = new BABYLON.Matrix();
  22211. _this._doNotComputeProjectionMatrix = false;
  22212. _this._postProcesses = new Array();
  22213. _this._transformMatrix = BABYLON.Matrix.Zero();
  22214. _this._activeMeshes = new BABYLON.SmartArray(256);
  22215. _this._globalPosition = BABYLON.Vector3.Zero();
  22216. _this._refreshFrustumPlanes = true;
  22217. _this.getScene().addCamera(_this);
  22218. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22219. _this.getScene().activeCamera = _this;
  22220. }
  22221. _this.position = position;
  22222. return _this;
  22223. }
  22224. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22225. get: function () {
  22226. return Camera._PERSPECTIVE_CAMERA;
  22227. },
  22228. enumerable: true,
  22229. configurable: true
  22230. });
  22231. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22232. get: function () {
  22233. return Camera._ORTHOGRAPHIC_CAMERA;
  22234. },
  22235. enumerable: true,
  22236. configurable: true
  22237. });
  22238. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22239. /**
  22240. * This is the default FOV mode for perspective cameras.
  22241. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22242. *
  22243. */
  22244. get: function () {
  22245. return Camera._FOVMODE_VERTICAL_FIXED;
  22246. },
  22247. enumerable: true,
  22248. configurable: true
  22249. });
  22250. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22251. /**
  22252. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22253. *
  22254. */
  22255. get: function () {
  22256. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22257. },
  22258. enumerable: true,
  22259. configurable: true
  22260. });
  22261. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22262. get: function () {
  22263. return Camera._RIG_MODE_NONE;
  22264. },
  22265. enumerable: true,
  22266. configurable: true
  22267. });
  22268. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22269. get: function () {
  22270. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22271. },
  22272. enumerable: true,
  22273. configurable: true
  22274. });
  22275. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22276. get: function () {
  22277. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22278. },
  22279. enumerable: true,
  22280. configurable: true
  22281. });
  22282. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22283. get: function () {
  22284. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22285. },
  22286. enumerable: true,
  22287. configurable: true
  22288. });
  22289. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22290. get: function () {
  22291. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22297. get: function () {
  22298. return Camera._RIG_MODE_VR;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22304. get: function () {
  22305. return Camera._RIG_MODE_WEBVR;
  22306. },
  22307. enumerable: true,
  22308. configurable: true
  22309. });
  22310. /**
  22311. * Store current camera state (fov, position, etc..)
  22312. */
  22313. Camera.prototype.storeState = function () {
  22314. this._stateStored = true;
  22315. this._storedFov = this.fov;
  22316. return this;
  22317. };
  22318. /**
  22319. * Restores the camera state values if it has been stored. You must call storeState() first
  22320. */
  22321. Camera.prototype._restoreStateValues = function () {
  22322. if (!this._stateStored) {
  22323. return false;
  22324. }
  22325. this.fov = this._storedFov;
  22326. return true;
  22327. };
  22328. /**
  22329. * Restored camera state. You must call storeState() first
  22330. */
  22331. Camera.prototype.restoreState = function () {
  22332. if (this._restoreStateValues()) {
  22333. this.onRestoreStateObservable.notifyObservers(this);
  22334. return true;
  22335. }
  22336. return false;
  22337. };
  22338. Camera.prototype.getClassName = function () {
  22339. return "Camera";
  22340. };
  22341. /**
  22342. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22343. */
  22344. Camera.prototype.toString = function (fullDetails) {
  22345. var ret = "Name: " + this.name;
  22346. ret += ", type: " + this.getClassName();
  22347. if (this.animations) {
  22348. for (var i = 0; i < this.animations.length; i++) {
  22349. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22350. }
  22351. }
  22352. if (fullDetails) {
  22353. }
  22354. return ret;
  22355. };
  22356. Object.defineProperty(Camera.prototype, "globalPosition", {
  22357. get: function () {
  22358. return this._globalPosition;
  22359. },
  22360. enumerable: true,
  22361. configurable: true
  22362. });
  22363. Camera.prototype.getActiveMeshes = function () {
  22364. return this._activeMeshes;
  22365. };
  22366. Camera.prototype.isActiveMesh = function (mesh) {
  22367. return (this._activeMeshes.indexOf(mesh) !== -1);
  22368. };
  22369. /**
  22370. * Is this camera ready to be used/rendered
  22371. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22372. * @return true if the camera is ready
  22373. */
  22374. Camera.prototype.isReady = function (completeCheck) {
  22375. if (completeCheck === void 0) { completeCheck = false; }
  22376. if (completeCheck) {
  22377. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22378. var pp = _a[_i];
  22379. if (pp && !pp.isReady()) {
  22380. return false;
  22381. }
  22382. }
  22383. }
  22384. return _super.prototype.isReady.call(this, completeCheck);
  22385. };
  22386. //Cache
  22387. /** @hidden */
  22388. Camera.prototype._initCache = function () {
  22389. _super.prototype._initCache.call(this);
  22390. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22391. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22392. this._cache.mode = undefined;
  22393. this._cache.minZ = undefined;
  22394. this._cache.maxZ = undefined;
  22395. this._cache.fov = undefined;
  22396. this._cache.fovMode = undefined;
  22397. this._cache.aspectRatio = undefined;
  22398. this._cache.orthoLeft = undefined;
  22399. this._cache.orthoRight = undefined;
  22400. this._cache.orthoBottom = undefined;
  22401. this._cache.orthoTop = undefined;
  22402. this._cache.renderWidth = undefined;
  22403. this._cache.renderHeight = undefined;
  22404. };
  22405. /** @hidden */
  22406. Camera.prototype._updateCache = function (ignoreParentClass) {
  22407. if (!ignoreParentClass) {
  22408. _super.prototype._updateCache.call(this);
  22409. }
  22410. this._cache.position.copyFrom(this.position);
  22411. this._cache.upVector.copyFrom(this.upVector);
  22412. };
  22413. // Synchronized
  22414. /** @hidden */
  22415. Camera.prototype._isSynchronized = function () {
  22416. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22417. };
  22418. /** @hidden */
  22419. Camera.prototype._isSynchronizedViewMatrix = function () {
  22420. if (!_super.prototype._isSynchronized.call(this))
  22421. return false;
  22422. return this._cache.position.equals(this.position)
  22423. && this._cache.upVector.equals(this.upVector)
  22424. && this.isSynchronizedWithParent();
  22425. };
  22426. /** @hidden */
  22427. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22428. var check = this._cache.mode === this.mode
  22429. && this._cache.minZ === this.minZ
  22430. && this._cache.maxZ === this.maxZ;
  22431. if (!check) {
  22432. return false;
  22433. }
  22434. var engine = this.getEngine();
  22435. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22436. check = this._cache.fov === this.fov
  22437. && this._cache.fovMode === this.fovMode
  22438. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22439. }
  22440. else {
  22441. check = this._cache.orthoLeft === this.orthoLeft
  22442. && this._cache.orthoRight === this.orthoRight
  22443. && this._cache.orthoBottom === this.orthoBottom
  22444. && this._cache.orthoTop === this.orthoTop
  22445. && this._cache.renderWidth === engine.getRenderWidth()
  22446. && this._cache.renderHeight === engine.getRenderHeight();
  22447. }
  22448. return check;
  22449. };
  22450. // Controls
  22451. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22452. };
  22453. Camera.prototype.detachControl = function (element) {
  22454. };
  22455. Camera.prototype.update = function () {
  22456. this._checkInputs();
  22457. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22458. this._updateRigCameras();
  22459. }
  22460. };
  22461. /** @hidden */
  22462. Camera.prototype._checkInputs = function () {
  22463. this.onAfterCheckInputsObservable.notifyObservers(this);
  22464. };
  22465. Object.defineProperty(Camera.prototype, "rigCameras", {
  22466. get: function () {
  22467. return this._rigCameras;
  22468. },
  22469. enumerable: true,
  22470. configurable: true
  22471. });
  22472. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22473. get: function () {
  22474. return this._rigPostProcess;
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. /**
  22480. * Internal, gets the first post proces.
  22481. * @returns the first post process to be run on this camera.
  22482. */
  22483. Camera.prototype._getFirstPostProcess = function () {
  22484. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22485. if (this._postProcesses[ppIndex] !== null) {
  22486. return this._postProcesses[ppIndex];
  22487. }
  22488. }
  22489. return null;
  22490. };
  22491. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22492. // invalidate framebuffer
  22493. var firstPostProcess = this._getFirstPostProcess();
  22494. if (firstPostProcess) {
  22495. firstPostProcess.markTextureDirty();
  22496. }
  22497. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22498. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22499. var cam = this._rigCameras[i];
  22500. var rigPostProcess = cam._rigPostProcess;
  22501. // for VR rig, there does not have to be a post process
  22502. if (rigPostProcess) {
  22503. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22504. if (isPass) {
  22505. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22506. cam.isIntermediate = this._postProcesses.length === 0;
  22507. }
  22508. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22509. rigPostProcess.markTextureDirty();
  22510. }
  22511. else {
  22512. cam._postProcesses = this._postProcesses.slice(0);
  22513. }
  22514. }
  22515. };
  22516. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22517. if (insertAt === void 0) { insertAt = null; }
  22518. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22519. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22520. return 0;
  22521. }
  22522. if (insertAt == null || insertAt < 0) {
  22523. this._postProcesses.push(postProcess);
  22524. }
  22525. else if (this._postProcesses[insertAt] === null) {
  22526. this._postProcesses[insertAt] = postProcess;
  22527. }
  22528. else {
  22529. this._postProcesses.splice(insertAt, 0, postProcess);
  22530. }
  22531. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22532. return this._postProcesses.indexOf(postProcess);
  22533. };
  22534. Camera.prototype.detachPostProcess = function (postProcess) {
  22535. var idx = this._postProcesses.indexOf(postProcess);
  22536. if (idx !== -1) {
  22537. this._postProcesses[idx] = null;
  22538. }
  22539. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22540. };
  22541. Camera.prototype.getWorldMatrix = function () {
  22542. if (this._isSynchronizedViewMatrix()) {
  22543. return this._worldMatrix;
  22544. }
  22545. // Getting the the view matrix will also compute the world matrix.
  22546. this.getViewMatrix();
  22547. return this._worldMatrix;
  22548. };
  22549. /** @hidden */
  22550. Camera.prototype._getViewMatrix = function () {
  22551. return BABYLON.Matrix.Identity();
  22552. };
  22553. Camera.prototype.getViewMatrix = function (force) {
  22554. if (!force && this._isSynchronizedViewMatrix()) {
  22555. return this._computedViewMatrix;
  22556. }
  22557. this.updateCache();
  22558. this._computedViewMatrix = this._getViewMatrix();
  22559. this._currentRenderId = this.getScene().getRenderId();
  22560. this._childRenderId = this._currentRenderId;
  22561. this._refreshFrustumPlanes = true;
  22562. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22563. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22564. }
  22565. this.onViewMatrixChangedObservable.notifyObservers(this);
  22566. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22567. return this._computedViewMatrix;
  22568. };
  22569. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22570. this._doNotComputeProjectionMatrix = true;
  22571. if (projection !== undefined) {
  22572. this._projectionMatrix = projection;
  22573. }
  22574. };
  22575. ;
  22576. Camera.prototype.unfreezeProjectionMatrix = function () {
  22577. this._doNotComputeProjectionMatrix = false;
  22578. };
  22579. ;
  22580. Camera.prototype.getProjectionMatrix = function (force) {
  22581. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22582. return this._projectionMatrix;
  22583. }
  22584. // Cache
  22585. this._cache.mode = this.mode;
  22586. this._cache.minZ = this.minZ;
  22587. this._cache.maxZ = this.maxZ;
  22588. // Matrix
  22589. this._refreshFrustumPlanes = true;
  22590. var engine = this.getEngine();
  22591. var scene = this.getScene();
  22592. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22593. this._cache.fov = this.fov;
  22594. this._cache.fovMode = this.fovMode;
  22595. this._cache.aspectRatio = engine.getAspectRatio(this);
  22596. if (this.minZ <= 0) {
  22597. this.minZ = 0.1;
  22598. }
  22599. if (scene.useRightHandedSystem) {
  22600. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22601. }
  22602. else {
  22603. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22604. }
  22605. }
  22606. else {
  22607. var halfWidth = engine.getRenderWidth() / 2.0;
  22608. var halfHeight = engine.getRenderHeight() / 2.0;
  22609. if (scene.useRightHandedSystem) {
  22610. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22611. }
  22612. else {
  22613. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22614. }
  22615. this._cache.orthoLeft = this.orthoLeft;
  22616. this._cache.orthoRight = this.orthoRight;
  22617. this._cache.orthoBottom = this.orthoBottom;
  22618. this._cache.orthoTop = this.orthoTop;
  22619. this._cache.renderWidth = engine.getRenderWidth();
  22620. this._cache.renderHeight = engine.getRenderHeight();
  22621. }
  22622. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22623. return this._projectionMatrix;
  22624. };
  22625. /**
  22626. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22627. * @returns a Matrix
  22628. */
  22629. Camera.prototype.getTransformationMatrix = function () {
  22630. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22631. return this._transformMatrix;
  22632. };
  22633. Camera.prototype.updateFrustumPlanes = function () {
  22634. if (!this._refreshFrustumPlanes) {
  22635. return;
  22636. }
  22637. this.getTransformationMatrix();
  22638. if (!this._frustumPlanes) {
  22639. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22640. }
  22641. else {
  22642. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22643. }
  22644. this._refreshFrustumPlanes = false;
  22645. };
  22646. Camera.prototype.isInFrustum = function (target) {
  22647. this.updateFrustumPlanes();
  22648. return target.isInFrustum(this._frustumPlanes);
  22649. };
  22650. Camera.prototype.isCompletelyInFrustum = function (target) {
  22651. this.updateFrustumPlanes();
  22652. return target.isCompletelyInFrustum(this._frustumPlanes);
  22653. };
  22654. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22655. if (length === void 0) { length = 100; }
  22656. if (!transform) {
  22657. transform = this.getWorldMatrix();
  22658. }
  22659. if (!origin) {
  22660. origin = this.position;
  22661. }
  22662. var forward = new BABYLON.Vector3(0, 0, 1);
  22663. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22664. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22665. return new BABYLON.Ray(origin, direction, length);
  22666. };
  22667. /**
  22668. * Releases resources associated with this node.
  22669. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22670. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22671. */
  22672. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22673. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22674. // Observables
  22675. this.onViewMatrixChangedObservable.clear();
  22676. this.onProjectionMatrixChangedObservable.clear();
  22677. this.onAfterCheckInputsObservable.clear();
  22678. this.onRestoreStateObservable.clear();
  22679. // Inputs
  22680. if (this.inputs) {
  22681. this.inputs.clear();
  22682. }
  22683. // Animations
  22684. this.getScene().stopAnimation(this);
  22685. // Remove from scene
  22686. this.getScene().removeCamera(this);
  22687. while (this._rigCameras.length > 0) {
  22688. var camera = this._rigCameras.pop();
  22689. if (camera) {
  22690. camera.dispose();
  22691. }
  22692. }
  22693. // Postprocesses
  22694. if (this._rigPostProcess) {
  22695. this._rigPostProcess.dispose(this);
  22696. this._rigPostProcess = null;
  22697. this._postProcesses = [];
  22698. }
  22699. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22700. this._rigPostProcess = null;
  22701. this._postProcesses = [];
  22702. }
  22703. else {
  22704. var i = this._postProcesses.length;
  22705. while (--i >= 0) {
  22706. var postProcess = this._postProcesses[i];
  22707. if (postProcess) {
  22708. postProcess.dispose(this);
  22709. }
  22710. }
  22711. }
  22712. // Render targets
  22713. var i = this.customRenderTargets.length;
  22714. while (--i >= 0) {
  22715. this.customRenderTargets[i].dispose();
  22716. }
  22717. this.customRenderTargets = [];
  22718. // Active Meshes
  22719. this._activeMeshes.dispose();
  22720. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22721. };
  22722. Object.defineProperty(Camera.prototype, "leftCamera", {
  22723. // ---- Camera rigs section ----
  22724. get: function () {
  22725. if (this._rigCameras.length < 1) {
  22726. return null;
  22727. }
  22728. return this._rigCameras[0];
  22729. },
  22730. enumerable: true,
  22731. configurable: true
  22732. });
  22733. Object.defineProperty(Camera.prototype, "rightCamera", {
  22734. get: function () {
  22735. if (this._rigCameras.length < 2) {
  22736. return null;
  22737. }
  22738. return this._rigCameras[1];
  22739. },
  22740. enumerable: true,
  22741. configurable: true
  22742. });
  22743. Camera.prototype.getLeftTarget = function () {
  22744. if (this._rigCameras.length < 1) {
  22745. return null;
  22746. }
  22747. return this._rigCameras[0].getTarget();
  22748. };
  22749. Camera.prototype.getRightTarget = function () {
  22750. if (this._rigCameras.length < 2) {
  22751. return null;
  22752. }
  22753. return this._rigCameras[1].getTarget();
  22754. };
  22755. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22756. if (this.cameraRigMode === mode) {
  22757. return;
  22758. }
  22759. while (this._rigCameras.length > 0) {
  22760. var camera = this._rigCameras.pop();
  22761. if (camera) {
  22762. camera.dispose();
  22763. }
  22764. }
  22765. this.cameraRigMode = mode;
  22766. this._cameraRigParams = {};
  22767. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22768. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22769. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22770. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22771. // create the rig cameras, unless none
  22772. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22773. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22774. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22775. if (leftCamera && rightCamera) {
  22776. this._rigCameras.push(leftCamera);
  22777. this._rigCameras.push(rightCamera);
  22778. }
  22779. }
  22780. switch (this.cameraRigMode) {
  22781. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22782. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22783. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22784. break;
  22785. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22786. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22787. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22788. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22789. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22790. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22791. break;
  22792. case Camera.RIG_MODE_VR:
  22793. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22794. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22795. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22796. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22797. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22798. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22799. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22800. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22801. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22802. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22803. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22804. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22805. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22806. if (metrics.compensateDistortion) {
  22807. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22808. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22809. }
  22810. break;
  22811. case Camera.RIG_MODE_WEBVR:
  22812. if (rigParams.vrDisplay) {
  22813. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22814. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22815. //Left eye
  22816. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22817. this._rigCameras[0].setCameraRigParameter("left", true);
  22818. //leaving this for future reference
  22819. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22820. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22821. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22822. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22823. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22824. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22825. this._rigCameras[0].parent = this;
  22826. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22827. //Right eye
  22828. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22829. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22830. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22831. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22832. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22833. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22834. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22835. this._rigCameras[1].parent = this;
  22836. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22837. if (Camera.UseAlternateWebVRRendering) {
  22838. this._rigCameras[1]._skipRendering = true;
  22839. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22840. }
  22841. }
  22842. break;
  22843. }
  22844. this._cascadePostProcessesToRigCams();
  22845. this.update();
  22846. };
  22847. Camera.prototype._getVRProjectionMatrix = function () {
  22848. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22849. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22850. return this._projectionMatrix;
  22851. };
  22852. Camera.prototype._updateCameraRotationMatrix = function () {
  22853. //Here for WebVR
  22854. };
  22855. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22856. //Here for WebVR
  22857. };
  22858. /**
  22859. * This function MUST be overwritten by the different WebVR cameras available.
  22860. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22861. */
  22862. Camera.prototype._getWebVRProjectionMatrix = function () {
  22863. return BABYLON.Matrix.Identity();
  22864. };
  22865. /**
  22866. * This function MUST be overwritten by the different WebVR cameras available.
  22867. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22868. */
  22869. Camera.prototype._getWebVRViewMatrix = function () {
  22870. return BABYLON.Matrix.Identity();
  22871. };
  22872. Camera.prototype.setCameraRigParameter = function (name, value) {
  22873. if (!this._cameraRigParams) {
  22874. this._cameraRigParams = {};
  22875. }
  22876. this._cameraRigParams[name] = value;
  22877. //provisionnally:
  22878. if (name === "interaxialDistance") {
  22879. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22880. }
  22881. };
  22882. /**
  22883. * needs to be overridden by children so sub has required properties to be copied
  22884. */
  22885. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22886. return null;
  22887. };
  22888. /**
  22889. * May need to be overridden by children
  22890. * @hidden
  22891. */
  22892. Camera.prototype._updateRigCameras = function () {
  22893. for (var i = 0; i < this._rigCameras.length; i++) {
  22894. this._rigCameras[i].minZ = this.minZ;
  22895. this._rigCameras[i].maxZ = this.maxZ;
  22896. this._rigCameras[i].fov = this.fov;
  22897. }
  22898. // only update viewport when ANAGLYPH
  22899. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22900. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22901. }
  22902. };
  22903. /** @hidden */
  22904. Camera.prototype._setupInputs = function () {
  22905. };
  22906. Camera.prototype.serialize = function () {
  22907. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22908. // Type
  22909. serializationObject.type = this.getClassName();
  22910. // Parent
  22911. if (this.parent) {
  22912. serializationObject.parentId = this.parent.id;
  22913. }
  22914. if (this.inputs) {
  22915. this.inputs.serialize(serializationObject);
  22916. }
  22917. // Animations
  22918. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22919. serializationObject.ranges = this.serializeAnimationRanges();
  22920. return serializationObject;
  22921. };
  22922. Camera.prototype.clone = function (name) {
  22923. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22924. };
  22925. Camera.prototype.getDirection = function (localAxis) {
  22926. var result = BABYLON.Vector3.Zero();
  22927. this.getDirectionToRef(localAxis, result);
  22928. return result;
  22929. };
  22930. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22931. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22932. };
  22933. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22934. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22935. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22936. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22937. interaxial_distance: interaxial_distance,
  22938. isStereoscopicSideBySide: isStereoscopicSideBySide
  22939. });
  22940. if (constructorFunc) {
  22941. return constructorFunc;
  22942. }
  22943. // Default to universal camera
  22944. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22945. };
  22946. Camera.prototype.computeWorldMatrix = function () {
  22947. return this.getWorldMatrix();
  22948. };
  22949. Camera.Parse = function (parsedCamera, scene) {
  22950. var type = parsedCamera.type;
  22951. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22952. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22953. // Parent
  22954. if (parsedCamera.parentId) {
  22955. camera._waitingParentId = parsedCamera.parentId;
  22956. }
  22957. //If camera has an input manager, let it parse inputs settings
  22958. if (camera.inputs) {
  22959. camera.inputs.parse(parsedCamera);
  22960. camera._setupInputs();
  22961. }
  22962. if (camera.setPosition) { // need to force position
  22963. camera.position.copyFromFloats(0, 0, 0);
  22964. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22965. }
  22966. // Target
  22967. if (parsedCamera.target) {
  22968. if (camera.setTarget) {
  22969. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22970. }
  22971. }
  22972. // Apply 3d rig, when found
  22973. if (parsedCamera.cameraRigMode) {
  22974. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22975. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22976. }
  22977. // Animations
  22978. if (parsedCamera.animations) {
  22979. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22980. var parsedAnimation = parsedCamera.animations[animationIndex];
  22981. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22982. }
  22983. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22984. }
  22985. if (parsedCamera.autoAnimate) {
  22986. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22987. }
  22988. return camera;
  22989. };
  22990. // Statics
  22991. Camera._PERSPECTIVE_CAMERA = 0;
  22992. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22993. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22994. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22995. Camera._RIG_MODE_NONE = 0;
  22996. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22997. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22998. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22999. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23000. Camera._RIG_MODE_VR = 20;
  23001. Camera._RIG_MODE_WEBVR = 21;
  23002. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23003. Camera.UseAlternateWebVRRendering = false;
  23004. __decorate([
  23005. BABYLON.serializeAsVector3()
  23006. ], Camera.prototype, "position", void 0);
  23007. __decorate([
  23008. BABYLON.serializeAsVector3()
  23009. ], Camera.prototype, "upVector", void 0);
  23010. __decorate([
  23011. BABYLON.serialize()
  23012. ], Camera.prototype, "orthoLeft", void 0);
  23013. __decorate([
  23014. BABYLON.serialize()
  23015. ], Camera.prototype, "orthoRight", void 0);
  23016. __decorate([
  23017. BABYLON.serialize()
  23018. ], Camera.prototype, "orthoBottom", void 0);
  23019. __decorate([
  23020. BABYLON.serialize()
  23021. ], Camera.prototype, "orthoTop", void 0);
  23022. __decorate([
  23023. BABYLON.serialize()
  23024. ], Camera.prototype, "fov", void 0);
  23025. __decorate([
  23026. BABYLON.serialize()
  23027. ], Camera.prototype, "minZ", void 0);
  23028. __decorate([
  23029. BABYLON.serialize()
  23030. ], Camera.prototype, "maxZ", void 0);
  23031. __decorate([
  23032. BABYLON.serialize()
  23033. ], Camera.prototype, "inertia", void 0);
  23034. __decorate([
  23035. BABYLON.serialize()
  23036. ], Camera.prototype, "mode", void 0);
  23037. __decorate([
  23038. BABYLON.serialize()
  23039. ], Camera.prototype, "layerMask", void 0);
  23040. __decorate([
  23041. BABYLON.serialize()
  23042. ], Camera.prototype, "fovMode", void 0);
  23043. __decorate([
  23044. BABYLON.serialize()
  23045. ], Camera.prototype, "cameraRigMode", void 0);
  23046. __decorate([
  23047. BABYLON.serialize()
  23048. ], Camera.prototype, "interaxialDistance", void 0);
  23049. __decorate([
  23050. BABYLON.serialize()
  23051. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23052. return Camera;
  23053. }(BABYLON.Node));
  23054. BABYLON.Camera = Camera;
  23055. })(BABYLON || (BABYLON = {}));
  23056. //# sourceMappingURL=babylon.camera.js.map
  23057. var BABYLON;
  23058. (function (BABYLON) {
  23059. var RenderingManager = /** @class */ (function () {
  23060. function RenderingManager(scene) {
  23061. /**
  23062. * @hidden
  23063. */
  23064. this._useSceneAutoClearSetup = false;
  23065. this._renderingGroups = new Array();
  23066. this._autoClearDepthStencil = {};
  23067. this._customOpaqueSortCompareFn = {};
  23068. this._customAlphaTestSortCompareFn = {};
  23069. this._customTransparentSortCompareFn = {};
  23070. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23071. this._scene = scene;
  23072. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23073. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23074. }
  23075. }
  23076. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23077. if (depth === void 0) { depth = true; }
  23078. if (stencil === void 0) { stencil = true; }
  23079. if (this._depthStencilBufferAlreadyCleaned) {
  23080. return;
  23081. }
  23082. this._scene.getEngine().clear(null, false, depth, stencil);
  23083. this._depthStencilBufferAlreadyCleaned = true;
  23084. };
  23085. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23086. // Update the observable context (not null as it only goes away on dispose)
  23087. var info = this._renderingGroupInfo;
  23088. info.scene = this._scene;
  23089. info.camera = this._scene.activeCamera;
  23090. // Dispatch sprites
  23091. if (this._scene.spriteManagers && renderSprites) {
  23092. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23093. var manager = this._scene.spriteManagers[index];
  23094. this.dispatchSprites(manager);
  23095. }
  23096. }
  23097. // Render
  23098. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23099. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23100. var renderingGroup = this._renderingGroups[index];
  23101. if (!renderingGroup)
  23102. continue;
  23103. var renderingGroupMask = Math.pow(2, index);
  23104. info.renderingGroupId = index;
  23105. // Before Observable
  23106. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23107. // Clear depth/stencil if needed
  23108. if (RenderingManager.AUTOCLEAR) {
  23109. var autoClear = this._useSceneAutoClearSetup ?
  23110. this._scene.getAutoClearDepthStencilSetup(index) :
  23111. this._autoClearDepthStencil[index];
  23112. if (autoClear && autoClear.autoClear) {
  23113. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23114. }
  23115. }
  23116. // Render
  23117. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23118. var step = _a[_i];
  23119. step.action(index);
  23120. }
  23121. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23122. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23123. var step = _c[_b];
  23124. step.action(index);
  23125. }
  23126. // After Observable
  23127. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23128. }
  23129. };
  23130. RenderingManager.prototype.reset = function () {
  23131. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23132. var renderingGroup = this._renderingGroups[index];
  23133. if (renderingGroup) {
  23134. renderingGroup.prepare();
  23135. }
  23136. }
  23137. };
  23138. RenderingManager.prototype.dispose = function () {
  23139. this.freeRenderingGroups();
  23140. this._renderingGroups.length = 0;
  23141. this._renderingGroupInfo = null;
  23142. };
  23143. /**
  23144. * Clear the info related to rendering groups preventing retention points during dispose.
  23145. */
  23146. RenderingManager.prototype.freeRenderingGroups = function () {
  23147. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23148. var renderingGroup = this._renderingGroups[index];
  23149. if (renderingGroup) {
  23150. renderingGroup.dispose();
  23151. }
  23152. }
  23153. };
  23154. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23155. if (this._renderingGroups[renderingGroupId] === undefined) {
  23156. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23157. }
  23158. };
  23159. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23160. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23161. this._prepareRenderingGroup(renderingGroupId);
  23162. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23163. };
  23164. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23165. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23166. this._prepareRenderingGroup(renderingGroupId);
  23167. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23168. };
  23169. /**
  23170. * @param subMesh The submesh to dispatch
  23171. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23172. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23173. */
  23174. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23175. if (mesh === undefined) {
  23176. mesh = subMesh.getMesh();
  23177. }
  23178. var renderingGroupId = mesh.renderingGroupId || 0;
  23179. this._prepareRenderingGroup(renderingGroupId);
  23180. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23181. };
  23182. /**
  23183. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23184. * This allowed control for front to back rendering or reversly depending of the special needs.
  23185. *
  23186. * @param renderingGroupId The rendering group id corresponding to its index
  23187. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23188. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23189. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23190. */
  23191. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23192. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23193. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23194. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23195. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23196. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23197. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23198. if (this._renderingGroups[renderingGroupId]) {
  23199. var group = this._renderingGroups[renderingGroupId];
  23200. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23201. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23202. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23203. }
  23204. };
  23205. /**
  23206. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23207. *
  23208. * @param renderingGroupId The rendering group id corresponding to its index
  23209. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23210. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23211. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23212. */
  23213. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23214. if (depth === void 0) { depth = true; }
  23215. if (stencil === void 0) { stencil = true; }
  23216. this._autoClearDepthStencil[renderingGroupId] = {
  23217. autoClear: autoClearDepthStencil,
  23218. depth: depth,
  23219. stencil: stencil
  23220. };
  23221. };
  23222. /**
  23223. * Gets the current auto clear configuration for one rendering group of the rendering
  23224. * manager.
  23225. * @param index the rendering group index to get the information for
  23226. * @returns The auto clear setup for the requested rendering group
  23227. */
  23228. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23229. return this._autoClearDepthStencil[index];
  23230. };
  23231. /**
  23232. * The max id used for rendering groups (not included)
  23233. */
  23234. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23235. /**
  23236. * The min id used for rendering groups (included)
  23237. */
  23238. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23239. /**
  23240. * Used to globally prevent autoclearing scenes.
  23241. */
  23242. RenderingManager.AUTOCLEAR = true;
  23243. return RenderingManager;
  23244. }());
  23245. BABYLON.RenderingManager = RenderingManager;
  23246. })(BABYLON || (BABYLON = {}));
  23247. //# sourceMappingURL=babylon.renderingManager.js.map
  23248. var BABYLON;
  23249. (function (BABYLON) {
  23250. var RenderingGroup = /** @class */ (function () {
  23251. /**
  23252. * Creates a new rendering group.
  23253. * @param index The rendering group index
  23254. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23255. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23256. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23257. */
  23258. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23259. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23260. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23261. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23262. this.index = index;
  23263. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23264. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23265. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23266. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23267. this._particleSystems = new BABYLON.SmartArray(256);
  23268. this._spriteManagers = new BABYLON.SmartArray(256);
  23269. this._edgesRenderers = new BABYLON.SmartArray(16);
  23270. this._scene = scene;
  23271. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23272. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23273. this.transparentSortCompareFn = transparentSortCompareFn;
  23274. }
  23275. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23276. /**
  23277. * Set the opaque sort comparison function.
  23278. * If null the sub meshes will be render in the order they were created
  23279. */
  23280. set: function (value) {
  23281. this._opaqueSortCompareFn = value;
  23282. if (value) {
  23283. this._renderOpaque = this.renderOpaqueSorted;
  23284. }
  23285. else {
  23286. this._renderOpaque = RenderingGroup.renderUnsorted;
  23287. }
  23288. },
  23289. enumerable: true,
  23290. configurable: true
  23291. });
  23292. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23293. /**
  23294. * Set the alpha test sort comparison function.
  23295. * If null the sub meshes will be render in the order they were created
  23296. */
  23297. set: function (value) {
  23298. this._alphaTestSortCompareFn = value;
  23299. if (value) {
  23300. this._renderAlphaTest = this.renderAlphaTestSorted;
  23301. }
  23302. else {
  23303. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23304. }
  23305. },
  23306. enumerable: true,
  23307. configurable: true
  23308. });
  23309. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23310. /**
  23311. * Set the transparent sort comparison function.
  23312. * If null the sub meshes will be render in the order they were created
  23313. */
  23314. set: function (value) {
  23315. if (value) {
  23316. this._transparentSortCompareFn = value;
  23317. }
  23318. else {
  23319. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23320. }
  23321. this._renderTransparent = this.renderTransparentSorted;
  23322. },
  23323. enumerable: true,
  23324. configurable: true
  23325. });
  23326. /**
  23327. * Render all the sub meshes contained in the group.
  23328. * @param customRenderFunction Used to override the default render behaviour of the group.
  23329. * @returns true if rendered some submeshes.
  23330. */
  23331. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23332. if (customRenderFunction) {
  23333. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23334. return;
  23335. }
  23336. var engine = this._scene.getEngine();
  23337. // Depth only
  23338. if (this._depthOnlySubMeshes.length !== 0) {
  23339. engine.setColorWrite(false);
  23340. this._renderAlphaTest(this._depthOnlySubMeshes);
  23341. engine.setColorWrite(true);
  23342. }
  23343. // Opaque
  23344. if (this._opaqueSubMeshes.length !== 0) {
  23345. this._renderOpaque(this._opaqueSubMeshes);
  23346. }
  23347. // Alpha test
  23348. if (this._alphaTestSubMeshes.length !== 0) {
  23349. this._renderAlphaTest(this._alphaTestSubMeshes);
  23350. }
  23351. var stencilState = engine.getStencilBuffer();
  23352. engine.setStencilBuffer(false);
  23353. // Sprites
  23354. if (renderSprites) {
  23355. this._renderSprites();
  23356. }
  23357. // Particles
  23358. if (renderParticles) {
  23359. this._renderParticles(activeMeshes);
  23360. }
  23361. if (this.onBeforeTransparentRendering) {
  23362. this.onBeforeTransparentRendering();
  23363. }
  23364. // Transparent
  23365. if (this._transparentSubMeshes.length !== 0) {
  23366. this._renderTransparent(this._transparentSubMeshes);
  23367. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23368. }
  23369. // Set back stencil to false in case it changes before the edge renderer.
  23370. engine.setStencilBuffer(false);
  23371. // Edges
  23372. if (this._edgesRenderers.length) {
  23373. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23374. this._edgesRenderers.data[edgesRendererIndex].render();
  23375. }
  23376. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23377. }
  23378. // Restore Stencil state.
  23379. engine.setStencilBuffer(stencilState);
  23380. };
  23381. /**
  23382. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23383. * @param subMeshes The submeshes to render
  23384. */
  23385. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23386. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23387. };
  23388. /**
  23389. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23390. * @param subMeshes The submeshes to render
  23391. */
  23392. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23393. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23394. };
  23395. /**
  23396. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23397. * @param subMeshes The submeshes to render
  23398. */
  23399. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23400. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23401. };
  23402. /**
  23403. * Renders the submeshes in a specified order.
  23404. * @param subMeshes The submeshes to sort before render
  23405. * @param sortCompareFn The comparison function use to sort
  23406. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23407. * @param transparent Specifies to activate blending if true
  23408. */
  23409. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23410. var subIndex = 0;
  23411. var subMesh;
  23412. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23413. for (; subIndex < subMeshes.length; subIndex++) {
  23414. subMesh = subMeshes.data[subIndex];
  23415. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23416. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23417. }
  23418. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23419. if (sortCompareFn) {
  23420. sortedArray.sort(sortCompareFn);
  23421. }
  23422. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23423. subMesh = sortedArray[subIndex];
  23424. if (transparent) {
  23425. var material = subMesh.getMaterial();
  23426. if (material && material.needDepthPrePass) {
  23427. var engine = material.getScene().getEngine();
  23428. engine.setColorWrite(false);
  23429. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23430. subMesh.render(false);
  23431. engine.setColorWrite(true);
  23432. }
  23433. }
  23434. subMesh.render(transparent);
  23435. }
  23436. };
  23437. /**
  23438. * Renders the submeshes in the order they were dispatched (no sort applied).
  23439. * @param subMeshes The submeshes to render
  23440. */
  23441. RenderingGroup.renderUnsorted = function (subMeshes) {
  23442. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23443. var submesh = subMeshes.data[subIndex];
  23444. submesh.render(false);
  23445. }
  23446. };
  23447. /**
  23448. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23449. * are rendered back to front if in the same alpha index.
  23450. *
  23451. * @param a The first submesh
  23452. * @param b The second submesh
  23453. * @returns The result of the comparison
  23454. */
  23455. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23456. // Alpha index first
  23457. if (a._alphaIndex > b._alphaIndex) {
  23458. return 1;
  23459. }
  23460. if (a._alphaIndex < b._alphaIndex) {
  23461. return -1;
  23462. }
  23463. // Then distance to camera
  23464. return RenderingGroup.backToFrontSortCompare(a, b);
  23465. };
  23466. /**
  23467. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23468. * are rendered back to front.
  23469. *
  23470. * @param a The first submesh
  23471. * @param b The second submesh
  23472. * @returns The result of the comparison
  23473. */
  23474. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23475. // Then distance to camera
  23476. if (a._distanceToCamera < b._distanceToCamera) {
  23477. return 1;
  23478. }
  23479. if (a._distanceToCamera > b._distanceToCamera) {
  23480. return -1;
  23481. }
  23482. return 0;
  23483. };
  23484. /**
  23485. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23486. * are rendered front to back (prevent overdraw).
  23487. *
  23488. * @param a The first submesh
  23489. * @param b The second submesh
  23490. * @returns The result of the comparison
  23491. */
  23492. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23493. // Then distance to camera
  23494. if (a._distanceToCamera < b._distanceToCamera) {
  23495. return -1;
  23496. }
  23497. if (a._distanceToCamera > b._distanceToCamera) {
  23498. return 1;
  23499. }
  23500. return 0;
  23501. };
  23502. /**
  23503. * Resets the different lists of submeshes to prepare a new frame.
  23504. */
  23505. RenderingGroup.prototype.prepare = function () {
  23506. this._opaqueSubMeshes.reset();
  23507. this._transparentSubMeshes.reset();
  23508. this._alphaTestSubMeshes.reset();
  23509. this._depthOnlySubMeshes.reset();
  23510. this._particleSystems.reset();
  23511. this._spriteManagers.reset();
  23512. this._edgesRenderers.reset();
  23513. };
  23514. RenderingGroup.prototype.dispose = function () {
  23515. this._opaqueSubMeshes.dispose();
  23516. this._transparentSubMeshes.dispose();
  23517. this._alphaTestSubMeshes.dispose();
  23518. this._depthOnlySubMeshes.dispose();
  23519. this._particleSystems.dispose();
  23520. this._spriteManagers.dispose();
  23521. this._edgesRenderers.dispose();
  23522. };
  23523. /**
  23524. * Inserts the submesh in its correct queue depending on its material.
  23525. * @param subMesh The submesh to dispatch
  23526. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23527. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23528. */
  23529. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23530. // Get mesh and materials if not provided
  23531. if (mesh === undefined) {
  23532. mesh = subMesh.getMesh();
  23533. }
  23534. if (material === undefined) {
  23535. material = subMesh.getMaterial();
  23536. }
  23537. if (material === null || material === undefined) {
  23538. return;
  23539. }
  23540. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23541. this._transparentSubMeshes.push(subMesh);
  23542. }
  23543. else if (material.needAlphaTesting()) { // Alpha test
  23544. if (material.needDepthPrePass) {
  23545. this._depthOnlySubMeshes.push(subMesh);
  23546. }
  23547. this._alphaTestSubMeshes.push(subMesh);
  23548. }
  23549. else {
  23550. if (material.needDepthPrePass) {
  23551. this._depthOnlySubMeshes.push(subMesh);
  23552. }
  23553. this._opaqueSubMeshes.push(subMesh); // Opaque
  23554. }
  23555. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23556. this._edgesRenderers.push(mesh._edgesRenderer);
  23557. }
  23558. };
  23559. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23560. this._spriteManagers.push(spriteManager);
  23561. };
  23562. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23563. this._particleSystems.push(particleSystem);
  23564. };
  23565. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23566. if (this._particleSystems.length === 0) {
  23567. return;
  23568. }
  23569. // Particles
  23570. var activeCamera = this._scene.activeCamera;
  23571. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23572. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23573. var particleSystem = this._particleSystems.data[particleIndex];
  23574. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23575. continue;
  23576. }
  23577. var emitter = particleSystem.emitter;
  23578. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23579. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23580. }
  23581. }
  23582. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23583. };
  23584. RenderingGroup.prototype._renderSprites = function () {
  23585. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23586. return;
  23587. }
  23588. // Sprites
  23589. var activeCamera = this._scene.activeCamera;
  23590. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23591. for (var id = 0; id < this._spriteManagers.length; id++) {
  23592. var spriteManager = this._spriteManagers.data[id];
  23593. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23594. spriteManager.render();
  23595. }
  23596. }
  23597. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23598. };
  23599. return RenderingGroup;
  23600. }());
  23601. BABYLON.RenderingGroup = RenderingGroup;
  23602. })(BABYLON || (BABYLON = {}));
  23603. //# sourceMappingURL=babylon.renderingGroup.js.map
  23604. var BABYLON;
  23605. (function (BABYLON) {
  23606. /**
  23607. * Groups all the scene component constants in one place to ease maintenance.
  23608. * @hidden
  23609. */
  23610. var SceneComponentConstants = /** @class */ (function () {
  23611. function SceneComponentConstants() {
  23612. }
  23613. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23614. SceneComponentConstants.NAME_LAYER = "Layer";
  23615. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23616. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23617. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23618. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23619. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23620. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23621. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23622. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23623. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23624. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23625. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23626. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23627. SceneComponentConstants.NAME_OCTREE = "Octree";
  23628. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23629. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23630. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23631. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23632. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23633. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23634. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23635. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23636. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23637. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23638. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23639. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23640. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23641. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23642. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23643. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23644. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23645. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23646. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23647. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23648. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23649. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23650. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23651. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23652. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23653. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23654. return SceneComponentConstants;
  23655. }());
  23656. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23657. /**
  23658. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23659. * @hidden
  23660. */
  23661. var Stage = /** @class */ (function (_super) {
  23662. __extends(Stage, _super);
  23663. /**
  23664. * Hide ctor from the rest of the world.
  23665. * @param items The items to add.
  23666. */
  23667. function Stage(items) {
  23668. return _super.apply(this, items) || this;
  23669. }
  23670. /**
  23671. * Creates a new Stage.
  23672. * @returns A new instance of a Stage
  23673. */
  23674. Stage.Create = function () {
  23675. return Object.create(Stage.prototype);
  23676. };
  23677. /**
  23678. * Registers a step in an ordered way in the targeted stage.
  23679. * @param index Defines the position to register the step in
  23680. * @param component Defines the component attached to the step
  23681. * @param action Defines the action to launch during the step
  23682. */
  23683. Stage.prototype.registerStep = function (index, component, action) {
  23684. var i = 0;
  23685. var maxIndex = Number.MAX_VALUE;
  23686. for (; i < this.length && i < maxIndex; i++) {
  23687. var step = this[i];
  23688. maxIndex = step.index;
  23689. }
  23690. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23691. };
  23692. /**
  23693. * Clears all the steps from the stage.
  23694. */
  23695. Stage.prototype.clear = function () {
  23696. this.length = 0;
  23697. };
  23698. return Stage;
  23699. }(Array));
  23700. BABYLON.Stage = Stage;
  23701. })(BABYLON || (BABYLON = {}));
  23702. //# sourceMappingURL=babylon.sceneComponent.js.map
  23703. var BABYLON;
  23704. (function (BABYLON) {
  23705. /**
  23706. * Base class of the scene acting as a container for the different elements composing a scene.
  23707. * This class is dynamically extended by the different components of the scene increasing
  23708. * flexibility and reducing coupling
  23709. */
  23710. var AbstractScene = /** @class */ (function () {
  23711. function AbstractScene() {
  23712. /**
  23713. * Gets the list of root nodes (ie. nodes with no parent)
  23714. */
  23715. this.rootNodes = new Array();
  23716. /** All of the cameras added to this scene
  23717. * @see http://doc.babylonjs.com/babylon101/cameras
  23718. */
  23719. this.cameras = new Array();
  23720. /**
  23721. * All of the lights added to this scene
  23722. * @see http://doc.babylonjs.com/babylon101/lights
  23723. */
  23724. this.lights = new Array();
  23725. /**
  23726. * All of the (abstract) meshes added to this scene
  23727. */
  23728. this.meshes = new Array();
  23729. /**
  23730. * The list of skeletons added to the scene
  23731. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23732. */
  23733. this.skeletons = new Array();
  23734. /**
  23735. * All of the particle systems added to this scene
  23736. * @see http://doc.babylonjs.com/babylon101/particles
  23737. */
  23738. this.particleSystems = new Array();
  23739. /**
  23740. * Gets a list of Animations associated with the scene
  23741. */
  23742. this.animations = [];
  23743. /**
  23744. * All of the animation groups added to this scene
  23745. * @see http://doc.babylonjs.com/how_to/group
  23746. */
  23747. this.animationGroups = new Array();
  23748. /**
  23749. * All of the multi-materials added to this scene
  23750. * @see http://doc.babylonjs.com/how_to/multi_materials
  23751. */
  23752. this.multiMaterials = new Array();
  23753. /**
  23754. * All of the materials added to this scene
  23755. * @see http://doc.babylonjs.com/babylon101/materials
  23756. */
  23757. this.materials = new Array();
  23758. /**
  23759. * The list of morph target managers added to the scene
  23760. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23761. */
  23762. this.morphTargetManagers = new Array();
  23763. /**
  23764. * The list of geometries used in the scene.
  23765. */
  23766. this.geometries = new Array();
  23767. /**
  23768. * All of the tranform nodes added to this scene
  23769. * @see http://doc.babylonjs.com/how_to/transformnode
  23770. */
  23771. this.transformNodes = new Array();
  23772. /**
  23773. * ActionManagers available on the scene.
  23774. */
  23775. this.actionManagers = new Array();
  23776. /**
  23777. * Sounds to keep.
  23778. */
  23779. this.sounds = new Array();
  23780. /**
  23781. * Textures to keep.
  23782. */
  23783. this.textures = new Array();
  23784. }
  23785. /**
  23786. * Adds a parser in the list of available ones
  23787. * @param name Defines the name of the parser
  23788. * @param parser Defines the parser to add
  23789. */
  23790. AbstractScene.AddParser = function (name, parser) {
  23791. this._BabylonFileParsers[name] = parser;
  23792. };
  23793. /**
  23794. * Gets a general parser from the list of avaialble ones
  23795. * @param name Defines the name of the parser
  23796. * @returns the requested parser or null
  23797. */
  23798. AbstractScene.GetParser = function (name) {
  23799. if (this._BabylonFileParsers[name]) {
  23800. return this._BabylonFileParsers[name];
  23801. }
  23802. return null;
  23803. };
  23804. /**
  23805. * Adds n individual parser in the list of available ones
  23806. * @param name Defines the name of the parser
  23807. * @param parser Defines the parser to add
  23808. */
  23809. AbstractScene.AddIndividualParser = function (name, parser) {
  23810. this._IndividualBabylonFileParsers[name] = parser;
  23811. };
  23812. /**
  23813. * Gets an individual parser from the list of avaialble ones
  23814. * @param name Defines the name of the parser
  23815. * @returns the requested parser or null
  23816. */
  23817. AbstractScene.GetIndividualParser = function (name) {
  23818. if (this._IndividualBabylonFileParsers[name]) {
  23819. return this._IndividualBabylonFileParsers[name];
  23820. }
  23821. return null;
  23822. };
  23823. /**
  23824. * Parser json data and populate both a scene and its associated container object
  23825. * @param jsonData Defines the data to parse
  23826. * @param scene Defines the scene to parse the data for
  23827. * @param container Defines the container attached to the parsing sequence
  23828. * @param rootUrl Defines the root url of the data
  23829. */
  23830. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23831. for (var parserName in this._BabylonFileParsers) {
  23832. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23833. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23834. }
  23835. }
  23836. };
  23837. /**
  23838. * Stores the list of available parsers in the application.
  23839. */
  23840. AbstractScene._BabylonFileParsers = {};
  23841. /**
  23842. * Stores the list of available individual parsers in the application.
  23843. */
  23844. AbstractScene._IndividualBabylonFileParsers = {};
  23845. return AbstractScene;
  23846. }());
  23847. BABYLON.AbstractScene = AbstractScene;
  23848. })(BABYLON || (BABYLON = {}));
  23849. //# sourceMappingURL=babylon.abstractScene.js.map
  23850. var BABYLON;
  23851. (function (BABYLON) {
  23852. /** @hidden */
  23853. var ClickInfo = /** @class */ (function () {
  23854. function ClickInfo() {
  23855. this._singleClick = false;
  23856. this._doubleClick = false;
  23857. this._hasSwiped = false;
  23858. this._ignore = false;
  23859. }
  23860. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23861. get: function () {
  23862. return this._singleClick;
  23863. },
  23864. set: function (b) {
  23865. this._singleClick = b;
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23871. get: function () {
  23872. return this._doubleClick;
  23873. },
  23874. set: function (b) {
  23875. this._doubleClick = b;
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23881. get: function () {
  23882. return this._hasSwiped;
  23883. },
  23884. set: function (b) {
  23885. this._hasSwiped = b;
  23886. },
  23887. enumerable: true,
  23888. configurable: true
  23889. });
  23890. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23891. get: function () {
  23892. return this._ignore;
  23893. },
  23894. set: function (b) {
  23895. this._ignore = b;
  23896. },
  23897. enumerable: true,
  23898. configurable: true
  23899. });
  23900. return ClickInfo;
  23901. }());
  23902. /**
  23903. * This class is used by the onRenderingGroupObservable
  23904. */
  23905. var RenderingGroupInfo = /** @class */ (function () {
  23906. function RenderingGroupInfo() {
  23907. }
  23908. return RenderingGroupInfo;
  23909. }());
  23910. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23911. /**
  23912. * Represents a scene to be rendered by the engine.
  23913. * @see http://doc.babylonjs.com/features/scene
  23914. */
  23915. var Scene = /** @class */ (function (_super) {
  23916. __extends(Scene, _super);
  23917. /**
  23918. * Creates a new Scene
  23919. * @param engine defines the engine to use to render this scene
  23920. */
  23921. function Scene(engine) {
  23922. var _this = _super.call(this) || this;
  23923. // Members
  23924. /**
  23925. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23926. */
  23927. _this.autoClear = true;
  23928. /**
  23929. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23930. */
  23931. _this.autoClearDepthAndStencil = true;
  23932. /**
  23933. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23934. */
  23935. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23936. /**
  23937. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23938. */
  23939. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23940. _this._forceWireframe = false;
  23941. _this._forcePointsCloud = false;
  23942. /**
  23943. * Gets or sets a boolean indicating if animations are enabled
  23944. */
  23945. _this.animationsEnabled = true;
  23946. _this._animationPropertiesOverride = null;
  23947. /**
  23948. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23949. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23950. */
  23951. _this.useConstantAnimationDeltaTime = false;
  23952. /**
  23953. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23954. * Please note that it requires to run a ray cast through the scene on every frame
  23955. */
  23956. _this.constantlyUpdateMeshUnderPointer = false;
  23957. /**
  23958. * Defines the HTML cursor to use when hovering over interactive elements
  23959. */
  23960. _this.hoverCursor = "pointer";
  23961. /**
  23962. * Defines the HTML default cursor to use (empty by default)
  23963. */
  23964. _this.defaultCursor = "";
  23965. /**
  23966. * This is used to call preventDefault() on pointer down
  23967. * in order to block unwanted artifacts like system double clicks
  23968. */
  23969. _this.preventDefaultOnPointerDown = true;
  23970. // Metadata
  23971. /**
  23972. * Gets or sets user defined metadata
  23973. */
  23974. _this.metadata = null;
  23975. /**
  23976. * Use this array to add regular expressions used to disable offline support for specific urls
  23977. */
  23978. _this.disableOfflineSupportExceptionRules = new Array();
  23979. /**
  23980. * An event triggered when the scene is disposed.
  23981. */
  23982. _this.onDisposeObservable = new BABYLON.Observable();
  23983. _this._onDisposeObserver = null;
  23984. /**
  23985. * An event triggered before rendering the scene (right after animations and physics)
  23986. */
  23987. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23988. _this._onBeforeRenderObserver = null;
  23989. /**
  23990. * An event triggered after rendering the scene
  23991. */
  23992. _this.onAfterRenderObservable = new BABYLON.Observable();
  23993. _this._onAfterRenderObserver = null;
  23994. /**
  23995. * An event triggered before animating the scene
  23996. */
  23997. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23998. /**
  23999. * An event triggered after animations processing
  24000. */
  24001. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24002. /**
  24003. * An event triggered before draw calls are ready to be sent
  24004. */
  24005. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24006. /**
  24007. * An event triggered after draw calls have been sent
  24008. */
  24009. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24010. /**
  24011. * An event triggered when physic simulation is about to be run
  24012. */
  24013. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24014. /**
  24015. * An event triggered when physic simulation has been done
  24016. */
  24017. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered when the scene is ready
  24020. */
  24021. _this.onReadyObservable = new BABYLON.Observable();
  24022. /**
  24023. * An event triggered before rendering a camera
  24024. */
  24025. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24026. _this._onBeforeCameraRenderObserver = null;
  24027. /**
  24028. * An event triggered after rendering a camera
  24029. */
  24030. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24031. _this._onAfterCameraRenderObserver = null;
  24032. /**
  24033. * An event triggered when active meshes evaluation is about to start
  24034. */
  24035. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24036. /**
  24037. * An event triggered when active meshes evaluation is done
  24038. */
  24039. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24040. /**
  24041. * An event triggered when particles rendering is about to start
  24042. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24043. */
  24044. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered when particles rendering is done
  24047. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24048. */
  24049. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24050. /**
  24051. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24052. */
  24053. _this.onDataLoadedObservable = new BABYLON.Observable();
  24054. /**
  24055. * An event triggered when a camera is created
  24056. */
  24057. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24058. /**
  24059. * An event triggered when a camera is removed
  24060. */
  24061. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24062. /**
  24063. * An event triggered when a light is created
  24064. */
  24065. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24066. /**
  24067. * An event triggered when a light is removed
  24068. */
  24069. _this.onLightRemovedObservable = new BABYLON.Observable();
  24070. /**
  24071. * An event triggered when a geometry is created
  24072. */
  24073. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24074. /**
  24075. * An event triggered when a geometry is removed
  24076. */
  24077. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24078. /**
  24079. * An event triggered when a transform node is created
  24080. */
  24081. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24082. /**
  24083. * An event triggered when a transform node is removed
  24084. */
  24085. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24086. /**
  24087. * An event triggered when a mesh is created
  24088. */
  24089. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24090. /**
  24091. * An event triggered when a mesh is removed
  24092. */
  24093. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24094. /**
  24095. * An event triggered when render targets are about to be rendered
  24096. * Can happen multiple times per frame.
  24097. */
  24098. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24099. /**
  24100. * An event triggered when render targets were rendered.
  24101. * Can happen multiple times per frame.
  24102. */
  24103. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24104. /**
  24105. * An event triggered before calculating deterministic simulation step
  24106. */
  24107. _this.onBeforeStepObservable = new BABYLON.Observable();
  24108. /**
  24109. * An event triggered after calculating deterministic simulation step
  24110. */
  24111. _this.onAfterStepObservable = new BABYLON.Observable();
  24112. /**
  24113. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24114. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24115. * 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)
  24116. */
  24117. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24118. /**
  24119. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24120. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24121. * 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)
  24122. */
  24123. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24124. /**
  24125. * This Observable will when a mesh has been imported into the scene.
  24126. */
  24127. _this.onMeshImportedObservable = new BABYLON.Observable();
  24128. // Animations
  24129. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24130. /**
  24131. * 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).
  24132. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24133. */
  24134. _this.onPrePointerObservable = new BABYLON.Observable();
  24135. /**
  24136. * Observable event triggered each time an input event is received from the rendering canvas
  24137. */
  24138. _this.onPointerObservable = new BABYLON.Observable();
  24139. _this._meshPickProceed = false;
  24140. _this._currentPickResult = null;
  24141. _this._previousPickResult = null;
  24142. _this._totalPointersPressed = 0;
  24143. _this._doubleClickOccured = false;
  24144. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24145. _this.cameraToUseForPointers = null;
  24146. _this._pointerX = 0;
  24147. _this._pointerY = 0;
  24148. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24149. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24150. _this._startingPointerTime = 0;
  24151. _this._previousStartingPointerTime = 0;
  24152. _this._pointerCaptures = {};
  24153. // Deterministic lockstep
  24154. _this._timeAccumulator = 0;
  24155. _this._currentStepId = 0;
  24156. _this._currentInternalStep = 0;
  24157. // Keyboard
  24158. /**
  24159. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24160. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24161. */
  24162. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24163. /**
  24164. * Observable event triggered each time an keyboard event is received from the hosting window
  24165. */
  24166. _this.onKeyboardObservable = new BABYLON.Observable();
  24167. // Coordinates system
  24168. _this._useRightHandedSystem = false;
  24169. // Fog
  24170. _this._fogEnabled = true;
  24171. _this._fogMode = Scene.FOGMODE_NONE;
  24172. /**
  24173. * Gets or sets the fog color to use
  24174. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24175. */
  24176. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24177. /**
  24178. * Gets or sets the fog density to use
  24179. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24180. */
  24181. _this.fogDensity = 0.1;
  24182. /**
  24183. * Gets or sets the fog start distance to use
  24184. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24185. */
  24186. _this.fogStart = 0;
  24187. /**
  24188. * Gets or sets the fog end distance to use
  24189. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24190. */
  24191. _this.fogEnd = 1000.0;
  24192. // Lights
  24193. _this._shadowsEnabled = true;
  24194. _this._lightsEnabled = true;
  24195. /** All of the active cameras added to this scene. */
  24196. _this.activeCameras = new Array();
  24197. // Textures
  24198. _this._texturesEnabled = true;
  24199. // Particles
  24200. /**
  24201. * Gets or sets a boolean indicating if particles are enabled on this scene
  24202. */
  24203. _this.particlesEnabled = true;
  24204. // Sprites
  24205. /**
  24206. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24207. */
  24208. _this.spritesEnabled = true;
  24209. // Skeletons
  24210. _this._skeletonsEnabled = true;
  24211. // Lens flares
  24212. /**
  24213. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24214. */
  24215. _this.lensFlaresEnabled = true;
  24216. // Collisions
  24217. /**
  24218. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24219. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24220. */
  24221. _this.collisionsEnabled = true;
  24222. /**
  24223. * Defines the gravity applied to this scene (used only for collisions)
  24224. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24225. */
  24226. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24227. // Postprocesses
  24228. /**
  24229. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24230. */
  24231. _this.postProcessesEnabled = true;
  24232. /**
  24233. * The list of postprocesses added to the scene
  24234. */
  24235. _this.postProcesses = new Array();
  24236. // Customs render targets
  24237. /**
  24238. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24239. */
  24240. _this.renderTargetsEnabled = true;
  24241. /**
  24242. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24243. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24244. */
  24245. _this.dumpNextRenderTargets = false;
  24246. /**
  24247. * The list of user defined render targets added to the scene
  24248. */
  24249. _this.customRenderTargets = new Array();
  24250. /**
  24251. * Gets the list of meshes imported to the scene through SceneLoader
  24252. */
  24253. _this.importedMeshesFiles = new Array();
  24254. // Probes
  24255. /**
  24256. * Gets or sets a boolean indicating if probes are enabled on this scene
  24257. */
  24258. _this.probesEnabled = true;
  24259. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24260. // Procedural textures
  24261. /**
  24262. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24263. */
  24264. _this.proceduralTexturesEnabled = true;
  24265. /**
  24266. * The list of sound tracks added to the scene
  24267. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24268. */
  24269. _this.soundTracks = new Array();
  24270. _this._audioEnabled = true;
  24271. _this._headphone = false;
  24272. // Performance counters
  24273. _this._totalVertices = new BABYLON.PerfCounter();
  24274. /** @hidden */
  24275. _this._activeIndices = new BABYLON.PerfCounter();
  24276. /** @hidden */
  24277. _this._activeParticles = new BABYLON.PerfCounter();
  24278. /** @hidden */
  24279. _this._activeBones = new BABYLON.PerfCounter();
  24280. _this._animationTime = 0;
  24281. /**
  24282. * Gets or sets a general scale for animation speed
  24283. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24284. */
  24285. _this.animationTimeScale = 1;
  24286. _this._renderId = 0;
  24287. _this._frameId = 0;
  24288. _this._executeWhenReadyTimeoutId = -1;
  24289. _this._intermediateRendering = false;
  24290. _this._viewUpdateFlag = -1;
  24291. _this._projectionUpdateFlag = -1;
  24292. _this._alternateViewUpdateFlag = -1;
  24293. _this._alternateProjectionUpdateFlag = -1;
  24294. /** @hidden */
  24295. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24296. _this._activeRequests = new Array();
  24297. _this._pendingData = new Array();
  24298. _this._isDisposed = false;
  24299. /**
  24300. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24301. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24302. */
  24303. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24304. _this._activeMeshes = new BABYLON.SmartArray(256);
  24305. _this._processedMaterials = new BABYLON.SmartArray(256);
  24306. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24307. /** @hidden */
  24308. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24309. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24310. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24311. /** @hidden */
  24312. _this._activeAnimatables = new Array();
  24313. _this._transformMatrix = BABYLON.Matrix.Zero();
  24314. _this._useAlternateCameraConfiguration = false;
  24315. _this._alternateRendering = false;
  24316. /**
  24317. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24318. * This is useful if there are more lights that the maximum simulteanous authorized
  24319. */
  24320. _this.requireLightSorting = false;
  24321. /**
  24322. * @hidden
  24323. * Backing store of defined scene components.
  24324. */
  24325. _this._components = [];
  24326. /**
  24327. * @hidden
  24328. * Backing store of defined scene components.
  24329. */
  24330. _this._serializableComponents = [];
  24331. /**
  24332. * List of components to register on the next registration step.
  24333. */
  24334. _this._transientComponents = [];
  24335. /**
  24336. * @hidden
  24337. * Defines the actions happening before camera updates.
  24338. */
  24339. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24340. /**
  24341. * @hidden
  24342. * Defines the actions happening before clear the canvas.
  24343. */
  24344. _this._beforeClearStage = BABYLON.Stage.Create();
  24345. /**
  24346. * @hidden
  24347. * Defines the actions when collecting render targets for the frame.
  24348. */
  24349. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24350. /**
  24351. * @hidden
  24352. * Defines the actions happening for one camera in the frame.
  24353. */
  24354. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24355. /**
  24356. * @hidden
  24357. * Defines the actions happening during the per mesh ready checks.
  24358. */
  24359. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24360. /**
  24361. * @hidden
  24362. * Defines the actions happening before evaluate active mesh checks.
  24363. */
  24364. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24365. /**
  24366. * @hidden
  24367. * Defines the actions happening during the evaluate sub mesh checks.
  24368. */
  24369. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24370. /**
  24371. * @hidden
  24372. * Defines the actions happening during the active mesh stage.
  24373. */
  24374. _this._activeMeshStage = BABYLON.Stage.Create();
  24375. /**
  24376. * @hidden
  24377. * Defines the actions happening during the per camera render target step.
  24378. */
  24379. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24380. /**
  24381. * @hidden
  24382. * Defines the actions happening just before the active camera is drawing.
  24383. */
  24384. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24385. /**
  24386. * @hidden
  24387. * Defines the actions happening just before a rendering group is drawing.
  24388. */
  24389. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24390. /**
  24391. * @hidden
  24392. * Defines the actions happening just before a mesh is drawing.
  24393. */
  24394. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24395. /**
  24396. * @hidden
  24397. * Defines the actions happening just after a mesh has been drawn.
  24398. */
  24399. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24400. /**
  24401. * @hidden
  24402. * Defines the actions happening just after a rendering group has been drawn.
  24403. */
  24404. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24405. /**
  24406. * @hidden
  24407. * Defines the actions happening just after the active camera has been drawn.
  24408. */
  24409. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24410. /**
  24411. * @hidden
  24412. * Defines the actions happening when a pointer move event happens.
  24413. */
  24414. _this._pointerMoveStage = BABYLON.Stage.Create();
  24415. /**
  24416. * @hidden
  24417. * Defines the actions happening when a pointer down event happens.
  24418. */
  24419. _this._pointerDownStage = BABYLON.Stage.Create();
  24420. /**
  24421. * @hidden
  24422. * Defines the actions happening when a pointer up event happens.
  24423. */
  24424. _this._pointerUpStage = BABYLON.Stage.Create();
  24425. _this._defaultMeshCandidates = {
  24426. data: [],
  24427. length: 0
  24428. };
  24429. _this._defaultSubMeshCandidates = {
  24430. data: [],
  24431. length: 0
  24432. };
  24433. _this._activeMeshesFrozen = false;
  24434. /** @hidden */
  24435. _this._allowPostProcessClearColor = true;
  24436. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24437. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24438. _this.blockMaterialDirtyMechanism = false;
  24439. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24440. _this._engine.scenes.push(_this);
  24441. _this._uid = null;
  24442. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24443. if (BABYLON.PostProcessManager) {
  24444. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24445. }
  24446. if (BABYLON.Tools.IsWindowObjectExist()) {
  24447. _this.attachControl();
  24448. }
  24449. //collision coordinator initialization. For now legacy per default.
  24450. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24451. // Uniform Buffer
  24452. _this._createUbo();
  24453. // Default Image processing definition
  24454. if (BABYLON.ImageProcessingConfiguration) {
  24455. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24456. }
  24457. _this.setDefaultCandidateProviders();
  24458. return _this;
  24459. }
  24460. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24461. /**
  24462. * Texture used in all pbr material as the reflection texture.
  24463. * As in the majority of the scene they are the same (exception for multi room and so on),
  24464. * this is easier to reference from here than from all the materials.
  24465. */
  24466. get: function () {
  24467. return this._environmentTexture;
  24468. },
  24469. /**
  24470. * Texture used in all pbr material as the reflection texture.
  24471. * As in the majority of the scene they are the same (exception for multi room and so on),
  24472. * this is easier to set here than in all the materials.
  24473. */
  24474. set: function (value) {
  24475. if (this._environmentTexture === value) {
  24476. return;
  24477. }
  24478. this._environmentTexture = value;
  24479. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24485. /**
  24486. * Default image processing configuration used either in the rendering
  24487. * Forward main pass or through the imageProcessingPostProcess if present.
  24488. * As in the majority of the scene they are the same (exception for multi camera),
  24489. * this is easier to reference from here than from all the materials and post process.
  24490. *
  24491. * No setter as we it is a shared configuration, you can set the values instead.
  24492. */
  24493. get: function () {
  24494. return this._imageProcessingConfiguration;
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24500. get: function () {
  24501. return this._forceWireframe;
  24502. },
  24503. /**
  24504. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24505. */
  24506. set: function (value) {
  24507. if (this._forceWireframe === value) {
  24508. return;
  24509. }
  24510. this._forceWireframe = value;
  24511. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24517. get: function () {
  24518. return this._forcePointsCloud;
  24519. },
  24520. /**
  24521. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24522. */
  24523. set: function (value) {
  24524. if (this._forcePointsCloud === value) {
  24525. return;
  24526. }
  24527. this._forcePointsCloud = value;
  24528. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24529. },
  24530. enumerable: true,
  24531. configurable: true
  24532. });
  24533. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24534. /**
  24535. * Gets or sets the animation properties override
  24536. */
  24537. get: function () {
  24538. return this._animationPropertiesOverride;
  24539. },
  24540. set: function (value) {
  24541. this._animationPropertiesOverride = value;
  24542. },
  24543. enumerable: true,
  24544. configurable: true
  24545. });
  24546. Object.defineProperty(Scene.prototype, "onDispose", {
  24547. /** Sets a function to be executed when this scene is disposed. */
  24548. set: function (callback) {
  24549. if (this._onDisposeObserver) {
  24550. this.onDisposeObservable.remove(this._onDisposeObserver);
  24551. }
  24552. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24553. },
  24554. enumerable: true,
  24555. configurable: true
  24556. });
  24557. Object.defineProperty(Scene.prototype, "beforeRender", {
  24558. /** Sets a function to be executed before rendering this scene */
  24559. set: function (callback) {
  24560. if (this._onBeforeRenderObserver) {
  24561. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24562. }
  24563. if (callback) {
  24564. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24565. }
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. Object.defineProperty(Scene.prototype, "afterRender", {
  24571. /** Sets a function to be executed after rendering this scene */
  24572. set: function (callback) {
  24573. if (this._onAfterRenderObserver) {
  24574. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24575. }
  24576. if (callback) {
  24577. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24578. }
  24579. },
  24580. enumerable: true,
  24581. configurable: true
  24582. });
  24583. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24584. /** Sets a function to be executed before rendering a camera*/
  24585. set: function (callback) {
  24586. if (this._onBeforeCameraRenderObserver) {
  24587. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24588. }
  24589. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24595. /** Sets a function to be executed after rendering a camera*/
  24596. set: function (callback) {
  24597. if (this._onAfterCameraRenderObserver) {
  24598. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24599. }
  24600. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24601. },
  24602. enumerable: true,
  24603. configurable: true
  24604. });
  24605. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24606. /**
  24607. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24608. */
  24609. get: function () {
  24610. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24616. get: function () {
  24617. return this._useRightHandedSystem;
  24618. },
  24619. /**
  24620. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24621. */
  24622. set: function (value) {
  24623. if (this._useRightHandedSystem === value) {
  24624. return;
  24625. }
  24626. this._useRightHandedSystem = value;
  24627. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24628. },
  24629. enumerable: true,
  24630. configurable: true
  24631. });
  24632. /**
  24633. * Sets the step Id used by deterministic lock step
  24634. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24635. * @param newStepId defines the step Id
  24636. */
  24637. Scene.prototype.setStepId = function (newStepId) {
  24638. this._currentStepId = newStepId;
  24639. };
  24640. ;
  24641. /**
  24642. * Gets the step Id used by deterministic lock step
  24643. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24644. * @returns the step Id
  24645. */
  24646. Scene.prototype.getStepId = function () {
  24647. return this._currentStepId;
  24648. };
  24649. ;
  24650. /**
  24651. * Gets the internal step used by deterministic lock step
  24652. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24653. * @returns the internal step
  24654. */
  24655. Scene.prototype.getInternalStep = function () {
  24656. return this._currentInternalStep;
  24657. };
  24658. ;
  24659. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24660. get: function () {
  24661. return this._fogEnabled;
  24662. },
  24663. /**
  24664. * Gets or sets a boolean indicating if fog is enabled on this scene
  24665. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24666. */
  24667. set: function (value) {
  24668. if (this._fogEnabled === value) {
  24669. return;
  24670. }
  24671. this._fogEnabled = value;
  24672. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24673. },
  24674. enumerable: true,
  24675. configurable: true
  24676. });
  24677. Object.defineProperty(Scene.prototype, "fogMode", {
  24678. get: function () {
  24679. return this._fogMode;
  24680. },
  24681. /**
  24682. * Gets or sets the fog mode to use
  24683. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24684. */
  24685. set: function (value) {
  24686. if (this._fogMode === value) {
  24687. return;
  24688. }
  24689. this._fogMode = value;
  24690. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24691. },
  24692. enumerable: true,
  24693. configurable: true
  24694. });
  24695. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24696. get: function () {
  24697. return this._shadowsEnabled;
  24698. },
  24699. /**
  24700. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24701. */
  24702. set: function (value) {
  24703. if (this._shadowsEnabled === value) {
  24704. return;
  24705. }
  24706. this._shadowsEnabled = value;
  24707. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24708. },
  24709. enumerable: true,
  24710. configurable: true
  24711. });
  24712. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24713. get: function () {
  24714. return this._lightsEnabled;
  24715. },
  24716. /**
  24717. * Gets or sets a boolean indicating if lights are enabled on this scene
  24718. */
  24719. set: function (value) {
  24720. if (this._lightsEnabled === value) {
  24721. return;
  24722. }
  24723. this._lightsEnabled = value;
  24724. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24725. },
  24726. enumerable: true,
  24727. configurable: true
  24728. });
  24729. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24730. /** The default material used on meshes when no material is affected */
  24731. get: function () {
  24732. if (!this._defaultMaterial) {
  24733. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24734. }
  24735. return this._defaultMaterial;
  24736. },
  24737. /** The default material used on meshes when no material is affected */
  24738. set: function (value) {
  24739. this._defaultMaterial = value;
  24740. },
  24741. enumerable: true,
  24742. configurable: true
  24743. });
  24744. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24745. get: function () {
  24746. return this._texturesEnabled;
  24747. },
  24748. /**
  24749. * Gets or sets a boolean indicating if textures are enabled on this scene
  24750. */
  24751. set: function (value) {
  24752. if (this._texturesEnabled === value) {
  24753. return;
  24754. }
  24755. this._texturesEnabled = value;
  24756. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24757. },
  24758. enumerable: true,
  24759. configurable: true
  24760. });
  24761. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24762. get: function () {
  24763. return this._skeletonsEnabled;
  24764. },
  24765. /**
  24766. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24767. */
  24768. set: function (value) {
  24769. if (this._skeletonsEnabled === value) {
  24770. return;
  24771. }
  24772. this._skeletonsEnabled = value;
  24773. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24774. },
  24775. enumerable: true,
  24776. configurable: true
  24777. });
  24778. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24779. /**
  24780. * Gets the main soundtrack associated with the scene
  24781. */
  24782. get: function () {
  24783. if (!this._mainSoundTrack) {
  24784. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24785. }
  24786. return this._mainSoundTrack;
  24787. },
  24788. enumerable: true,
  24789. configurable: true
  24790. });
  24791. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24792. /** @hidden */
  24793. get: function () {
  24794. return this._alternateRendering;
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24800. /**
  24801. * Gets the list of frustum planes (built from the active camera)
  24802. */
  24803. get: function () {
  24804. return this._frustumPlanes;
  24805. },
  24806. enumerable: true,
  24807. configurable: true
  24808. });
  24809. /**
  24810. * Registers the transient components if needed.
  24811. */
  24812. Scene.prototype._registerTransientComponents = function () {
  24813. // Register components that have been associated lately to the scene.
  24814. if (this._transientComponents.length > 0) {
  24815. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24816. var component = _a[_i];
  24817. component.register();
  24818. }
  24819. this._transientComponents = [];
  24820. }
  24821. };
  24822. /**
  24823. * @hidden
  24824. * Add a component to the scene.
  24825. * Note that the ccomponent could be registered on th next frame if this is called after
  24826. * the register component stage.
  24827. * @param component Defines the component to add to the scene
  24828. */
  24829. Scene.prototype._addComponent = function (component) {
  24830. this._components.push(component);
  24831. this._transientComponents.push(component);
  24832. var serializableComponent = component;
  24833. if (serializableComponent.addFromContainer) {
  24834. this._serializableComponents.push(serializableComponent);
  24835. }
  24836. };
  24837. /**
  24838. * @hidden
  24839. * Gets a component from the scene.
  24840. * @param name defines the name of the component to retrieve
  24841. * @returns the component or null if not present
  24842. */
  24843. Scene.prototype._getComponent = function (name) {
  24844. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24845. var component = _a[_i];
  24846. if (component.name === name) {
  24847. return component;
  24848. }
  24849. }
  24850. return null;
  24851. };
  24852. /**
  24853. * @hidden
  24854. */
  24855. Scene.prototype._getDefaultMeshCandidates = function () {
  24856. this._defaultMeshCandidates.data = this.meshes;
  24857. this._defaultMeshCandidates.length = this.meshes.length;
  24858. return this._defaultMeshCandidates;
  24859. };
  24860. /**
  24861. * @hidden
  24862. */
  24863. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  24864. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  24865. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  24866. return this._defaultSubMeshCandidates;
  24867. };
  24868. /**
  24869. * Sets the default candidate providers for the scene.
  24870. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  24871. * and getCollidingSubMeshCandidates to their default function
  24872. */
  24873. Scene.prototype.setDefaultCandidateProviders = function () {
  24874. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  24875. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24876. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24877. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24878. };
  24879. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24880. /**
  24881. * Gets a boolean indicating if collisions are processed on a web worker
  24882. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24883. */
  24884. get: function () {
  24885. return this._workerCollisions;
  24886. },
  24887. set: function (enabled) {
  24888. if (!BABYLON.CollisionCoordinatorLegacy) {
  24889. return;
  24890. }
  24891. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24892. this._workerCollisions = enabled;
  24893. if (this.collisionCoordinator) {
  24894. this.collisionCoordinator.destroy();
  24895. }
  24896. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24897. this.collisionCoordinator.init(this);
  24898. },
  24899. enumerable: true,
  24900. configurable: true
  24901. });
  24902. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24903. /**
  24904. * Gets the mesh that is currently under the pointer
  24905. */
  24906. get: function () {
  24907. return this._pointerOverMesh;
  24908. },
  24909. enumerable: true,
  24910. configurable: true
  24911. });
  24912. Object.defineProperty(Scene.prototype, "pointerX", {
  24913. /**
  24914. * Gets the current on-screen X position of the pointer
  24915. */
  24916. get: function () {
  24917. return this._pointerX;
  24918. },
  24919. enumerable: true,
  24920. configurable: true
  24921. });
  24922. Object.defineProperty(Scene.prototype, "pointerY", {
  24923. /**
  24924. * Gets the current on-screen Y position of the pointer
  24925. */
  24926. get: function () {
  24927. return this._pointerY;
  24928. },
  24929. enumerable: true,
  24930. configurable: true
  24931. });
  24932. /**
  24933. * Gets the cached material (ie. the latest rendered one)
  24934. * @returns the cached material
  24935. */
  24936. Scene.prototype.getCachedMaterial = function () {
  24937. return this._cachedMaterial;
  24938. };
  24939. /**
  24940. * Gets the cached effect (ie. the latest rendered one)
  24941. * @returns the cached effect
  24942. */
  24943. Scene.prototype.getCachedEffect = function () {
  24944. return this._cachedEffect;
  24945. };
  24946. /**
  24947. * Gets the cached visibility state (ie. the latest rendered one)
  24948. * @returns the cached visibility state
  24949. */
  24950. Scene.prototype.getCachedVisibility = function () {
  24951. return this._cachedVisibility;
  24952. };
  24953. /**
  24954. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24955. * @param material defines the current material
  24956. * @param effect defines the current effect
  24957. * @param visibility defines the current visibility state
  24958. * @returns true if one parameter is not cached
  24959. */
  24960. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24961. if (visibility === void 0) { visibility = 1; }
  24962. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24963. };
  24964. /**
  24965. * Gets the engine associated with the scene
  24966. * @returns an Engine
  24967. */
  24968. Scene.prototype.getEngine = function () {
  24969. return this._engine;
  24970. };
  24971. /**
  24972. * Gets the total number of vertices rendered per frame
  24973. * @returns the total number of vertices rendered per frame
  24974. */
  24975. Scene.prototype.getTotalVertices = function () {
  24976. return this._totalVertices.current;
  24977. };
  24978. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24979. /**
  24980. * Gets the performance counter for total vertices
  24981. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24982. */
  24983. get: function () {
  24984. return this._totalVertices;
  24985. },
  24986. enumerable: true,
  24987. configurable: true
  24988. });
  24989. /**
  24990. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24991. * @returns the total number of active indices rendered per frame
  24992. */
  24993. Scene.prototype.getActiveIndices = function () {
  24994. return this._activeIndices.current;
  24995. };
  24996. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24997. /**
  24998. * Gets the performance counter for active indices
  24999. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25000. */
  25001. get: function () {
  25002. return this._activeIndices;
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. /**
  25008. * Gets the total number of active particles rendered per frame
  25009. * @returns the total number of active particles rendered per frame
  25010. */
  25011. Scene.prototype.getActiveParticles = function () {
  25012. return this._activeParticles.current;
  25013. };
  25014. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25015. /**
  25016. * Gets the performance counter for active particles
  25017. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25018. */
  25019. get: function () {
  25020. return this._activeParticles;
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. /**
  25026. * Gets the total number of active bones rendered per frame
  25027. * @returns the total number of active bones rendered per frame
  25028. */
  25029. Scene.prototype.getActiveBones = function () {
  25030. return this._activeBones.current;
  25031. };
  25032. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25033. /**
  25034. * Gets the performance counter for active bones
  25035. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25036. */
  25037. get: function () {
  25038. return this._activeBones;
  25039. },
  25040. enumerable: true,
  25041. configurable: true
  25042. });
  25043. /** @hidden */
  25044. Scene.prototype.getInterFramePerfCounter = function () {
  25045. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25046. return 0;
  25047. };
  25048. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25049. /** @hidden */
  25050. get: function () {
  25051. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25052. return null;
  25053. },
  25054. enumerable: true,
  25055. configurable: true
  25056. });
  25057. /** @hidden */
  25058. Scene.prototype.getLastFrameDuration = function () {
  25059. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25060. return 0;
  25061. };
  25062. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25063. /** @hidden */
  25064. get: function () {
  25065. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25066. return null;
  25067. },
  25068. enumerable: true,
  25069. configurable: true
  25070. });
  25071. /** @hidden */
  25072. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25073. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25074. return 0;
  25075. };
  25076. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25077. /** @hidden */
  25078. get: function () {
  25079. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25080. return null;
  25081. },
  25082. enumerable: true,
  25083. configurable: true
  25084. });
  25085. /**
  25086. * Gets the array of active meshes
  25087. * @returns an array of AbstractMesh
  25088. */
  25089. Scene.prototype.getActiveMeshes = function () {
  25090. return this._activeMeshes;
  25091. };
  25092. /** @hidden */
  25093. Scene.prototype.getRenderTargetsDuration = function () {
  25094. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25095. return 0;
  25096. };
  25097. /** @hidden */
  25098. Scene.prototype.getRenderDuration = function () {
  25099. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25100. return 0;
  25101. };
  25102. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25103. /** @hidden */
  25104. get: function () {
  25105. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25106. return null;
  25107. },
  25108. enumerable: true,
  25109. configurable: true
  25110. });
  25111. /** @hidden */
  25112. Scene.prototype.getParticlesDuration = function () {
  25113. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25114. return 0;
  25115. };
  25116. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25117. /** @hidden */
  25118. get: function () {
  25119. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25120. return null;
  25121. },
  25122. enumerable: true,
  25123. configurable: true
  25124. });
  25125. /** @hidden */
  25126. Scene.prototype.getSpritesDuration = function () {
  25127. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25128. return 0;
  25129. };
  25130. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25131. /** @hidden */
  25132. get: function () {
  25133. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25134. return null;
  25135. },
  25136. enumerable: true,
  25137. configurable: true
  25138. });
  25139. /**
  25140. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25141. * @returns a number
  25142. */
  25143. Scene.prototype.getAnimationRatio = function () {
  25144. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25145. };
  25146. /**
  25147. * Gets an unique Id for the current render phase
  25148. * @returns a number
  25149. */
  25150. Scene.prototype.getRenderId = function () {
  25151. return this._renderId;
  25152. };
  25153. /**
  25154. * Gets an unique Id for the current frame
  25155. * @returns a number
  25156. */
  25157. Scene.prototype.getFrameId = function () {
  25158. return this._frameId;
  25159. };
  25160. /** Call this function if you want to manually increment the render Id*/
  25161. Scene.prototype.incrementRenderId = function () {
  25162. this._renderId++;
  25163. };
  25164. Scene.prototype._updatePointerPosition = function (evt) {
  25165. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25166. if (!canvasRect) {
  25167. return;
  25168. }
  25169. this._pointerX = evt.clientX - canvasRect.left;
  25170. this._pointerY = evt.clientY - canvasRect.top;
  25171. this._unTranslatedPointerX = this._pointerX;
  25172. this._unTranslatedPointerY = this._pointerY;
  25173. };
  25174. Scene.prototype._createUbo = function () {
  25175. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25176. this._sceneUbo.addUniform("viewProjection", 16);
  25177. this._sceneUbo.addUniform("view", 16);
  25178. };
  25179. Scene.prototype._createAlternateUbo = function () {
  25180. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25181. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25182. this._alternateSceneUbo.addUniform("view", 16);
  25183. };
  25184. // Pointers handling
  25185. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25186. if (pointerInfo.pickInfo) {
  25187. if (!pointerInfo.pickInfo.ray) {
  25188. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25189. }
  25190. }
  25191. };
  25192. /**
  25193. * Use this method to simulate a pointer move on a mesh
  25194. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25195. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25196. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25197. * @returns the current scene
  25198. */
  25199. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25200. var evt = new PointerEvent("pointermove", pointerEventInit);
  25201. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25202. return this;
  25203. }
  25204. return this._processPointerMove(pickResult, evt);
  25205. };
  25206. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25207. var canvas = this._engine.getRenderingCanvas();
  25208. if (!canvas) {
  25209. return this;
  25210. }
  25211. // Restore pointer
  25212. canvas.style.cursor = this.defaultCursor;
  25213. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25214. if (isMeshPicked) {
  25215. this.setPointerOverMesh(pickResult.pickedMesh);
  25216. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25217. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25218. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25219. }
  25220. else {
  25221. canvas.style.cursor = this.hoverCursor;
  25222. }
  25223. }
  25224. }
  25225. else {
  25226. this.setPointerOverMesh(null);
  25227. }
  25228. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25229. var step = _a[_i];
  25230. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25231. }
  25232. if (pickResult) {
  25233. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25234. if (this.onPointerMove) {
  25235. this.onPointerMove(evt, pickResult, type);
  25236. }
  25237. if (this.onPointerObservable.hasObservers()) {
  25238. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25239. this._setRayOnPointerInfo(pi);
  25240. this.onPointerObservable.notifyObservers(pi, type);
  25241. }
  25242. }
  25243. return this;
  25244. };
  25245. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25246. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25247. if (pickResult) {
  25248. pi.ray = pickResult.ray;
  25249. }
  25250. this.onPrePointerObservable.notifyObservers(pi, type);
  25251. if (pi.skipOnPointerObservable) {
  25252. return true;
  25253. }
  25254. else {
  25255. return false;
  25256. }
  25257. };
  25258. /**
  25259. * Use this method to simulate a pointer down on a mesh
  25260. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25261. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25262. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25263. * @returns the current scene
  25264. */
  25265. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25266. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25267. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25268. return this;
  25269. }
  25270. return this._processPointerDown(pickResult, evt);
  25271. };
  25272. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25273. var _this = this;
  25274. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25275. this._pickedDownMesh = pickResult.pickedMesh;
  25276. var actionManager = pickResult.pickedMesh.actionManager;
  25277. if (actionManager) {
  25278. if (actionManager.hasPickTriggers) {
  25279. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25280. switch (evt.button) {
  25281. case 0:
  25282. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25283. break;
  25284. case 1:
  25285. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25286. break;
  25287. case 2:
  25288. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25289. break;
  25290. }
  25291. }
  25292. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25293. window.setTimeout(function () {
  25294. 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);
  25295. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25296. if (_this._totalPointersPressed !== 0 &&
  25297. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25298. !_this._isPointerSwiping()) {
  25299. _this._startingPointerTime = 0;
  25300. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25301. }
  25302. }
  25303. }, Scene.LongPressDelay);
  25304. }
  25305. }
  25306. }
  25307. else {
  25308. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25309. var step = _a[_i];
  25310. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25311. }
  25312. }
  25313. if (pickResult) {
  25314. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25315. if (this.onPointerDown) {
  25316. this.onPointerDown(evt, pickResult, type);
  25317. }
  25318. if (this.onPointerObservable.hasObservers()) {
  25319. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25320. this._setRayOnPointerInfo(pi);
  25321. this.onPointerObservable.notifyObservers(pi, type);
  25322. }
  25323. }
  25324. return this;
  25325. };
  25326. /**
  25327. * Use this method to simulate a pointer up on a mesh
  25328. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25329. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25330. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25331. * @returns the current scene
  25332. */
  25333. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25334. var evt = new PointerEvent("pointerup", pointerEventInit);
  25335. var clickInfo = new ClickInfo();
  25336. clickInfo.singleClick = true;
  25337. clickInfo.ignore = true;
  25338. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25339. return this;
  25340. }
  25341. return this._processPointerUp(pickResult, evt, clickInfo);
  25342. };
  25343. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25344. if (pickResult && pickResult && pickResult.pickedMesh) {
  25345. this._pickedUpMesh = pickResult.pickedMesh;
  25346. if (this._pickedDownMesh === this._pickedUpMesh) {
  25347. if (this.onPointerPick) {
  25348. this.onPointerPick(evt, pickResult);
  25349. }
  25350. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25351. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25352. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25353. this._setRayOnPointerInfo(pi);
  25354. this.onPointerObservable.notifyObservers(pi, type_1);
  25355. }
  25356. }
  25357. if (pickResult.pickedMesh.actionManager) {
  25358. if (clickInfo.ignore) {
  25359. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25360. }
  25361. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25362. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25363. }
  25364. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25365. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25366. }
  25367. }
  25368. }
  25369. else {
  25370. if (!clickInfo.ignore) {
  25371. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25372. var step = _a[_i];
  25373. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25374. }
  25375. }
  25376. }
  25377. if (this._pickedDownMesh &&
  25378. this._pickedDownMesh.actionManager &&
  25379. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25380. this._pickedDownMesh !== this._pickedUpMesh) {
  25381. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25382. }
  25383. var type = BABYLON.PointerEventTypes.POINTERUP;
  25384. if (this.onPointerObservable.hasObservers()) {
  25385. if (!clickInfo.ignore) {
  25386. if (!clickInfo.hasSwiped) {
  25387. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25388. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25389. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25390. this._setRayOnPointerInfo(pi);
  25391. this.onPointerObservable.notifyObservers(pi, type_2);
  25392. }
  25393. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25394. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25395. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25396. this._setRayOnPointerInfo(pi);
  25397. this.onPointerObservable.notifyObservers(pi, type_3);
  25398. }
  25399. }
  25400. }
  25401. else {
  25402. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25403. this._setRayOnPointerInfo(pi);
  25404. this.onPointerObservable.notifyObservers(pi, type);
  25405. }
  25406. }
  25407. if (this.onPointerUp) {
  25408. this.onPointerUp(evt, pickResult, type);
  25409. }
  25410. return this;
  25411. };
  25412. /**
  25413. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25414. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25415. * @returns true if the pointer was captured
  25416. */
  25417. Scene.prototype.isPointerCaptured = function (pointerId) {
  25418. if (pointerId === void 0) { pointerId = 0; }
  25419. return this._pointerCaptures[pointerId];
  25420. };
  25421. /** @hidden */
  25422. Scene.prototype._isPointerSwiping = function () {
  25423. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25424. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25425. };
  25426. /**
  25427. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25428. * @param attachUp defines if you want to attach events to pointerup
  25429. * @param attachDown defines if you want to attach events to pointerdown
  25430. * @param attachMove defines if you want to attach events to pointermove
  25431. */
  25432. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25433. var _this = this;
  25434. if (attachUp === void 0) { attachUp = true; }
  25435. if (attachDown === void 0) { attachDown = true; }
  25436. if (attachMove === void 0) { attachMove = true; }
  25437. this._initActionManager = function (act, clickInfo) {
  25438. if (!_this._meshPickProceed) {
  25439. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25440. _this._currentPickResult = pickResult;
  25441. if (pickResult) {
  25442. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25443. }
  25444. _this._meshPickProceed = true;
  25445. }
  25446. return act;
  25447. };
  25448. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25449. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25450. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25451. btn !== _this._previousButtonPressed) {
  25452. _this._doubleClickOccured = false;
  25453. clickInfo.singleClick = true;
  25454. clickInfo.ignore = false;
  25455. cb(clickInfo, _this._currentPickResult);
  25456. }
  25457. };
  25458. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25459. var clickInfo = new ClickInfo();
  25460. _this._currentPickResult = null;
  25461. var act = null;
  25462. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25463. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25464. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25465. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25466. act = _this._initActionManager(act, clickInfo);
  25467. if (act)
  25468. checkPicking = act.hasPickTriggers;
  25469. }
  25470. if (checkPicking) {
  25471. var btn = evt.button;
  25472. clickInfo.hasSwiped = _this._isPointerSwiping();
  25473. if (!clickInfo.hasSwiped) {
  25474. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25475. if (!checkSingleClickImmediately) {
  25476. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25477. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25478. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25479. act = _this._initActionManager(act, clickInfo);
  25480. if (act)
  25481. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25482. }
  25483. }
  25484. if (checkSingleClickImmediately) {
  25485. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25486. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25487. btn !== _this._previousButtonPressed) {
  25488. clickInfo.singleClick = true;
  25489. cb(clickInfo, _this._currentPickResult);
  25490. }
  25491. }
  25492. // at least one double click is required to be check and exclusive double click is enabled
  25493. else {
  25494. // wait that no double click has been raised during the double click delay
  25495. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25496. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25497. }
  25498. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25499. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25500. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25501. act = _this._initActionManager(act, clickInfo);
  25502. if (act)
  25503. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25504. }
  25505. if (checkDoubleClick) {
  25506. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25507. if (btn === _this._previousButtonPressed &&
  25508. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25509. !_this._doubleClickOccured) {
  25510. // pointer has not moved for 2 clicks, it's a double click
  25511. if (!clickInfo.hasSwiped &&
  25512. !_this._isPointerSwiping()) {
  25513. _this._previousStartingPointerTime = 0;
  25514. _this._doubleClickOccured = true;
  25515. clickInfo.doubleClick = true;
  25516. clickInfo.ignore = false;
  25517. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25518. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25519. }
  25520. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25521. cb(clickInfo, _this._currentPickResult);
  25522. }
  25523. // if the two successive clicks are too far, it's just two simple clicks
  25524. else {
  25525. _this._doubleClickOccured = false;
  25526. _this._previousStartingPointerTime = _this._startingPointerTime;
  25527. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25528. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25529. _this._previousButtonPressed = btn;
  25530. if (Scene.ExclusiveDoubleClickMode) {
  25531. if (_this._previousDelayedSimpleClickTimeout) {
  25532. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25533. }
  25534. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25535. cb(clickInfo, _this._previousPickResult);
  25536. }
  25537. else {
  25538. cb(clickInfo, _this._currentPickResult);
  25539. }
  25540. }
  25541. }
  25542. // just the first click of the double has been raised
  25543. else {
  25544. _this._doubleClickOccured = false;
  25545. _this._previousStartingPointerTime = _this._startingPointerTime;
  25546. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25547. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25548. _this._previousButtonPressed = btn;
  25549. }
  25550. }
  25551. }
  25552. }
  25553. clickInfo.ignore = true;
  25554. cb(clickInfo, _this._currentPickResult);
  25555. };
  25556. this._onPointerMove = function (evt) {
  25557. _this._updatePointerPosition(evt);
  25558. // PreObservable support
  25559. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25560. return;
  25561. }
  25562. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25563. return;
  25564. }
  25565. if (!_this.pointerMovePredicate) {
  25566. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25567. }
  25568. // Meshes
  25569. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25570. _this._processPointerMove(pickResult, evt);
  25571. };
  25572. this._onPointerDown = function (evt) {
  25573. _this._totalPointersPressed++;
  25574. _this._pickedDownMesh = null;
  25575. _this._meshPickProceed = false;
  25576. _this._updatePointerPosition(evt);
  25577. if (_this.preventDefaultOnPointerDown && canvas) {
  25578. evt.preventDefault();
  25579. canvas.focus();
  25580. }
  25581. // PreObservable support
  25582. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25583. return;
  25584. }
  25585. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25586. return;
  25587. }
  25588. _this._pointerCaptures[evt.pointerId] = true;
  25589. _this._startingPointerPosition.x = _this._pointerX;
  25590. _this._startingPointerPosition.y = _this._pointerY;
  25591. _this._startingPointerTime = Date.now();
  25592. if (!_this.pointerDownPredicate) {
  25593. _this.pointerDownPredicate = function (mesh) {
  25594. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25595. };
  25596. }
  25597. // Meshes
  25598. _this._pickedDownMesh = null;
  25599. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25600. _this._processPointerDown(pickResult, evt);
  25601. };
  25602. this._onPointerUp = function (evt) {
  25603. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25604. return; // So we need to test it the pointer down was pressed before.
  25605. }
  25606. _this._totalPointersPressed--;
  25607. _this._pickedUpMesh = null;
  25608. _this._meshPickProceed = false;
  25609. _this._updatePointerPosition(evt);
  25610. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25611. // PreObservable support
  25612. if (_this.onPrePointerObservable.hasObservers()) {
  25613. if (!clickInfo.ignore) {
  25614. if (!clickInfo.hasSwiped) {
  25615. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25616. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25617. return;
  25618. }
  25619. }
  25620. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25621. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25622. return;
  25623. }
  25624. }
  25625. }
  25626. }
  25627. else {
  25628. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25629. return;
  25630. }
  25631. }
  25632. }
  25633. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25634. return;
  25635. }
  25636. _this._pointerCaptures[evt.pointerId] = false;
  25637. if (!_this.pointerUpPredicate) {
  25638. _this.pointerUpPredicate = function (mesh) {
  25639. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25640. };
  25641. }
  25642. // Meshes
  25643. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25644. _this._initActionManager(null, clickInfo);
  25645. }
  25646. if (!pickResult) {
  25647. pickResult = _this._currentPickResult;
  25648. }
  25649. _this._processPointerUp(pickResult, evt, clickInfo);
  25650. _this._previousPickResult = _this._currentPickResult;
  25651. });
  25652. };
  25653. this._onKeyDown = function (evt) {
  25654. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25655. if (_this.onPreKeyboardObservable.hasObservers()) {
  25656. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25657. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25658. if (pi.skipOnPointerObservable) {
  25659. return;
  25660. }
  25661. }
  25662. if (_this.onKeyboardObservable.hasObservers()) {
  25663. var pi = new BABYLON.KeyboardInfo(type, evt);
  25664. _this.onKeyboardObservable.notifyObservers(pi, type);
  25665. }
  25666. if (_this.actionManager) {
  25667. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25668. }
  25669. };
  25670. this._onKeyUp = function (evt) {
  25671. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25672. if (_this.onPreKeyboardObservable.hasObservers()) {
  25673. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25674. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25675. if (pi.skipOnPointerObservable) {
  25676. return;
  25677. }
  25678. }
  25679. if (_this.onKeyboardObservable.hasObservers()) {
  25680. var pi = new BABYLON.KeyboardInfo(type, evt);
  25681. _this.onKeyboardObservable.notifyObservers(pi, type);
  25682. }
  25683. if (_this.actionManager) {
  25684. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25685. }
  25686. };
  25687. var engine = this.getEngine();
  25688. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25689. if (!canvas) {
  25690. return;
  25691. }
  25692. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25693. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25694. });
  25695. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25696. if (!canvas) {
  25697. return;
  25698. }
  25699. canvas.removeEventListener("keydown", _this._onKeyDown);
  25700. canvas.removeEventListener("keyup", _this._onKeyUp);
  25701. });
  25702. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25703. var canvas = this._engine.getRenderingCanvas();
  25704. if (!canvas) {
  25705. return;
  25706. }
  25707. if (attachMove) {
  25708. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25709. // Wheel
  25710. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25711. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25712. }
  25713. if (attachDown) {
  25714. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25715. }
  25716. if (attachUp) {
  25717. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25718. }
  25719. canvas.tabIndex = 1;
  25720. };
  25721. /** Detaches all event handlers*/
  25722. Scene.prototype.detachControl = function () {
  25723. var engine = this.getEngine();
  25724. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25725. var canvas = engine.getRenderingCanvas();
  25726. if (!canvas) {
  25727. return;
  25728. }
  25729. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25730. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25731. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25732. if (this._onCanvasBlurObserver) {
  25733. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25734. }
  25735. if (this._onCanvasFocusObserver) {
  25736. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25737. }
  25738. // Wheel
  25739. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25740. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25741. // Keyboard
  25742. canvas.removeEventListener("keydown", this._onKeyDown);
  25743. canvas.removeEventListener("keyup", this._onKeyUp);
  25744. // Observables
  25745. this.onKeyboardObservable.clear();
  25746. this.onPreKeyboardObservable.clear();
  25747. this.onPointerObservable.clear();
  25748. this.onPrePointerObservable.clear();
  25749. };
  25750. /**
  25751. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25752. * Delay loaded resources are not taking in account
  25753. * @return true if all required resources are ready
  25754. */
  25755. Scene.prototype.isReady = function () {
  25756. if (this._isDisposed) {
  25757. return false;
  25758. }
  25759. if (this._pendingData.length > 0) {
  25760. return false;
  25761. }
  25762. var index;
  25763. var engine = this.getEngine();
  25764. // Geometries
  25765. for (index = 0; index < this.geometries.length; index++) {
  25766. var geometry = this.geometries[index];
  25767. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25768. return false;
  25769. }
  25770. }
  25771. // Meshes
  25772. for (index = 0; index < this.meshes.length; index++) {
  25773. var mesh = this.meshes[index];
  25774. if (!mesh.isEnabled()) {
  25775. continue;
  25776. }
  25777. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25778. continue;
  25779. }
  25780. if (!mesh.isReady(true)) {
  25781. return false;
  25782. }
  25783. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25784. // Is Ready For Mesh
  25785. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25786. var step = _a[_i];
  25787. if (!step.action(mesh, hardwareInstancedRendering)) {
  25788. return false;
  25789. }
  25790. }
  25791. }
  25792. // Post-processes
  25793. if (this.activeCameras && this.activeCameras.length > 0) {
  25794. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25795. var camera = _c[_b];
  25796. if (!camera.isReady(true)) {
  25797. return false;
  25798. }
  25799. }
  25800. }
  25801. else if (this.activeCamera) {
  25802. if (!this.activeCamera.isReady(true)) {
  25803. return false;
  25804. }
  25805. }
  25806. // Particles
  25807. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25808. var particleSystem = _e[_d];
  25809. if (!particleSystem.isReady()) {
  25810. return false;
  25811. }
  25812. }
  25813. return true;
  25814. };
  25815. /** Resets all cached information relative to material (including effect and visibility) */
  25816. Scene.prototype.resetCachedMaterial = function () {
  25817. this._cachedMaterial = null;
  25818. this._cachedEffect = null;
  25819. this._cachedVisibility = null;
  25820. };
  25821. /**
  25822. * Registers a function to be called before every frame render
  25823. * @param func defines the function to register
  25824. */
  25825. Scene.prototype.registerBeforeRender = function (func) {
  25826. this.onBeforeRenderObservable.add(func);
  25827. };
  25828. /**
  25829. * Unregisters a function called before every frame render
  25830. * @param func defines the function to unregister
  25831. */
  25832. Scene.prototype.unregisterBeforeRender = function (func) {
  25833. this.onBeforeRenderObservable.removeCallback(func);
  25834. };
  25835. /**
  25836. * Registers a function to be called after every frame render
  25837. * @param func defines the function to register
  25838. */
  25839. Scene.prototype.registerAfterRender = function (func) {
  25840. this.onAfterRenderObservable.add(func);
  25841. };
  25842. /**
  25843. * Unregisters a function called after every frame render
  25844. * @param func defines the function to unregister
  25845. */
  25846. Scene.prototype.unregisterAfterRender = function (func) {
  25847. this.onAfterRenderObservable.removeCallback(func);
  25848. };
  25849. Scene.prototype._executeOnceBeforeRender = function (func) {
  25850. var _this = this;
  25851. var execFunc = function () {
  25852. func();
  25853. setTimeout(function () {
  25854. _this.unregisterBeforeRender(execFunc);
  25855. });
  25856. };
  25857. this.registerBeforeRender(execFunc);
  25858. };
  25859. /**
  25860. * The provided function will run before render once and will be disposed afterwards.
  25861. * A timeout delay can be provided so that the function will be executed in N ms.
  25862. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25863. * @param func The function to be executed.
  25864. * @param timeout optional delay in ms
  25865. */
  25866. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25867. var _this = this;
  25868. if (timeout !== undefined) {
  25869. setTimeout(function () {
  25870. _this._executeOnceBeforeRender(func);
  25871. }, timeout);
  25872. }
  25873. else {
  25874. this._executeOnceBeforeRender(func);
  25875. }
  25876. };
  25877. /** @hidden */
  25878. Scene.prototype._addPendingData = function (data) {
  25879. this._pendingData.push(data);
  25880. };
  25881. /** @hidden */
  25882. Scene.prototype._removePendingData = function (data) {
  25883. var wasLoading = this.isLoading;
  25884. var index = this._pendingData.indexOf(data);
  25885. if (index !== -1) {
  25886. this._pendingData.splice(index, 1);
  25887. }
  25888. if (wasLoading && !this.isLoading) {
  25889. this.onDataLoadedObservable.notifyObservers(this);
  25890. }
  25891. };
  25892. /**
  25893. * Returns the number of items waiting to be loaded
  25894. * @returns the number of items waiting to be loaded
  25895. */
  25896. Scene.prototype.getWaitingItemsCount = function () {
  25897. return this._pendingData.length;
  25898. };
  25899. Object.defineProperty(Scene.prototype, "isLoading", {
  25900. /**
  25901. * Returns a boolean indicating if the scene is still loading data
  25902. */
  25903. get: function () {
  25904. return this._pendingData.length > 0;
  25905. },
  25906. enumerable: true,
  25907. configurable: true
  25908. });
  25909. /**
  25910. * Registers a function to be executed when the scene is ready
  25911. * @param {Function} func - the function to be executed
  25912. */
  25913. Scene.prototype.executeWhenReady = function (func) {
  25914. var _this = this;
  25915. this.onReadyObservable.add(func);
  25916. if (this._executeWhenReadyTimeoutId !== -1) {
  25917. return;
  25918. }
  25919. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25920. _this._checkIsReady();
  25921. }, 150);
  25922. };
  25923. /**
  25924. * Returns a promise that resolves when the scene is ready
  25925. * @returns A promise that resolves when the scene is ready
  25926. */
  25927. Scene.prototype.whenReadyAsync = function () {
  25928. var _this = this;
  25929. return new Promise(function (resolve) {
  25930. _this.executeWhenReady(function () {
  25931. resolve();
  25932. });
  25933. });
  25934. };
  25935. /** @hidden */
  25936. Scene.prototype._checkIsReady = function () {
  25937. var _this = this;
  25938. this._registerTransientComponents();
  25939. if (this.isReady()) {
  25940. this.onReadyObservable.notifyObservers(this);
  25941. this.onReadyObservable.clear();
  25942. this._executeWhenReadyTimeoutId = -1;
  25943. return;
  25944. }
  25945. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25946. _this._checkIsReady();
  25947. }, 150);
  25948. };
  25949. // Animations
  25950. /**
  25951. * Will start the animation sequence of a given target
  25952. * @param target defines the target
  25953. * @param from defines from which frame should animation start
  25954. * @param to defines until which frame should animation run.
  25955. * @param weight defines the weight to apply to the animation (1.0 by default)
  25956. * @param loop defines if the animation loops
  25957. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25958. * @param onAnimationEnd defines the function to be executed when the animation ends
  25959. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25960. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25961. * @returns the animatable object created for this animation
  25962. */
  25963. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25964. if (weight === void 0) { weight = 1.0; }
  25965. if (speedRatio === void 0) { speedRatio = 1.0; }
  25966. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25967. returnedAnimatable.weight = weight;
  25968. return returnedAnimatable;
  25969. };
  25970. /**
  25971. * Will start the animation sequence of a given target
  25972. * @param target defines the target
  25973. * @param from defines from which frame should animation start
  25974. * @param to defines until which frame should animation run.
  25975. * @param loop defines if the animation loops
  25976. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25977. * @param onAnimationEnd defines the function to be executed when the animation ends
  25978. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25979. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25980. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25981. * @returns the animatable object created for this animation
  25982. */
  25983. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25984. if (speedRatio === void 0) { speedRatio = 1.0; }
  25985. if (stopCurrent === void 0) { stopCurrent = true; }
  25986. if (from > to && speedRatio > 0) {
  25987. speedRatio *= -1;
  25988. }
  25989. if (stopCurrent) {
  25990. this.stopAnimation(target, undefined, targetMask);
  25991. }
  25992. if (!animatable) {
  25993. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25994. }
  25995. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25996. // Local animations
  25997. if (target.animations && shouldRunTargetAnimations) {
  25998. animatable.appendAnimations(target, target.animations);
  25999. }
  26000. // Children animations
  26001. if (target.getAnimatables) {
  26002. var animatables = target.getAnimatables();
  26003. for (var index = 0; index < animatables.length; index++) {
  26004. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26005. }
  26006. }
  26007. animatable.reset();
  26008. return animatable;
  26009. };
  26010. /**
  26011. * Begin a new animation on a given node
  26012. * @param target defines the target where the animation will take place
  26013. * @param animations defines the list of animations to start
  26014. * @param from defines the initial value
  26015. * @param to defines the final value
  26016. * @param loop defines if you want animation to loop (off by default)
  26017. * @param speedRatio defines the speed ratio to apply to all animations
  26018. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26019. * @returns the list of created animatables
  26020. */
  26021. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26022. if (speedRatio === undefined) {
  26023. speedRatio = 1.0;
  26024. }
  26025. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26026. return animatable;
  26027. };
  26028. /**
  26029. * Begin a new animation on a given node and its hierarchy
  26030. * @param target defines the root node where the animation will take place
  26031. * @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.
  26032. * @param animations defines the list of animations to start
  26033. * @param from defines the initial value
  26034. * @param to defines the final value
  26035. * @param loop defines if you want animation to loop (off by default)
  26036. * @param speedRatio defines the speed ratio to apply to all animations
  26037. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26038. * @returns the list of animatables created for all nodes
  26039. */
  26040. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26041. var children = target.getDescendants(directDescendantsOnly);
  26042. var result = [];
  26043. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26044. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26045. var child = children_1[_i];
  26046. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26047. }
  26048. return result;
  26049. };
  26050. /**
  26051. * Gets the animatable associated with a specific target
  26052. * @param target defines the target of the animatable
  26053. * @returns the required animatable if found
  26054. */
  26055. Scene.prototype.getAnimatableByTarget = function (target) {
  26056. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26057. if (this._activeAnimatables[index].target === target) {
  26058. return this._activeAnimatables[index];
  26059. }
  26060. }
  26061. return null;
  26062. };
  26063. /**
  26064. * Gets all animatables associated with a given target
  26065. * @param target defines the target to look animatables for
  26066. * @returns an array of Animatables
  26067. */
  26068. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26069. var result = [];
  26070. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26071. if (this._activeAnimatables[index].target === target) {
  26072. result.push(this._activeAnimatables[index]);
  26073. }
  26074. }
  26075. return result;
  26076. };
  26077. Object.defineProperty(Scene.prototype, "animatables", {
  26078. /**
  26079. * Gets all animatable attached to the scene
  26080. */
  26081. get: function () {
  26082. return this._activeAnimatables;
  26083. },
  26084. enumerable: true,
  26085. configurable: true
  26086. });
  26087. /**
  26088. * Will stop the animation of the given target
  26089. * @param target - the target
  26090. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26091. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26092. */
  26093. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26094. var animatables = this.getAllAnimatablesByTarget(target);
  26095. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26096. var animatable = animatables_1[_i];
  26097. animatable.stop(animationName, targetMask);
  26098. }
  26099. };
  26100. /**
  26101. * Stops and removes all animations that have been applied to the scene
  26102. */
  26103. Scene.prototype.stopAllAnimations = function () {
  26104. if (this._activeAnimatables) {
  26105. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26106. this._activeAnimatables[i].stop();
  26107. }
  26108. this._activeAnimatables = [];
  26109. }
  26110. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26111. var group = _a[_i];
  26112. group.stop();
  26113. }
  26114. };
  26115. Scene.prototype._animate = function () {
  26116. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26117. return;
  26118. }
  26119. // Getting time
  26120. var now = BABYLON.Tools.Now;
  26121. if (!this._animationTimeLast) {
  26122. if (this._pendingData.length > 0) {
  26123. return;
  26124. }
  26125. this._animationTimeLast = now;
  26126. }
  26127. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26128. this._animationTime += deltaTime;
  26129. this._animationTimeLast = now;
  26130. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26131. this._activeAnimatables[index]._animate(this._animationTime);
  26132. }
  26133. // Late animation bindings
  26134. this._processLateAnimationBindings();
  26135. };
  26136. /** @hidden */
  26137. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26138. var target = runtimeAnimation.target;
  26139. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26140. if (!target._lateAnimationHolders) {
  26141. target._lateAnimationHolders = {};
  26142. }
  26143. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26144. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26145. totalWeight: 0,
  26146. animations: [],
  26147. originalValue: originalValue
  26148. };
  26149. }
  26150. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26151. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26152. };
  26153. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26154. var normalizer = 1.0;
  26155. var finalPosition = BABYLON.Tmp.Vector3[0];
  26156. var finalScaling = BABYLON.Tmp.Vector3[1];
  26157. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26158. var startIndex = 0;
  26159. var originalAnimation = holder.animations[0];
  26160. var originalValue = holder.originalValue;
  26161. var scale = 1;
  26162. if (holder.totalWeight < 1.0) {
  26163. // We need to mix the original value in
  26164. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26165. scale = 1.0 - holder.totalWeight;
  26166. }
  26167. else {
  26168. startIndex = 1;
  26169. // We need to normalize the weights
  26170. normalizer = holder.totalWeight;
  26171. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26172. scale = originalAnimation.weight / normalizer;
  26173. if (scale == 1) {
  26174. return originalAnimation.currentValue;
  26175. }
  26176. }
  26177. finalScaling.scaleInPlace(scale);
  26178. finalPosition.scaleInPlace(scale);
  26179. finalQuaternion.scaleInPlace(scale);
  26180. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26181. var runtimeAnimation = holder.animations[animIndex];
  26182. var scale = runtimeAnimation.weight / normalizer;
  26183. var currentPosition = BABYLON.Tmp.Vector3[2];
  26184. var currentScaling = BABYLON.Tmp.Vector3[3];
  26185. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26186. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26187. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26188. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26189. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26190. }
  26191. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26192. return originalAnimation._workValue;
  26193. };
  26194. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26195. var originalAnimation = holder.animations[0];
  26196. var originalValue = holder.originalValue;
  26197. if (holder.animations.length === 1) {
  26198. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26199. return refQuaternion;
  26200. }
  26201. var normalizer = 1.0;
  26202. var quaternions;
  26203. var weights;
  26204. if (holder.totalWeight < 1.0) {
  26205. var scale = 1.0 - holder.totalWeight;
  26206. quaternions = [];
  26207. weights = [];
  26208. quaternions.push(originalValue);
  26209. weights.push(scale);
  26210. }
  26211. else {
  26212. if (holder.animations.length === 2) { // Slerp as soon as we can
  26213. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26214. return refQuaternion;
  26215. }
  26216. quaternions = [];
  26217. weights = [];
  26218. normalizer = holder.totalWeight;
  26219. }
  26220. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26221. var runtimeAnimation = holder.animations[animIndex];
  26222. quaternions.push(runtimeAnimation.currentValue);
  26223. weights.push(runtimeAnimation.weight / normalizer);
  26224. }
  26225. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26226. var cumulativeAmount = 0;
  26227. var cumulativeQuaternion = null;
  26228. for (var index = 0; index < quaternions.length;) {
  26229. if (!cumulativeQuaternion) {
  26230. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26231. cumulativeQuaternion = refQuaternion;
  26232. cumulativeAmount = weights[index] + weights[index + 1];
  26233. index += 2;
  26234. continue;
  26235. }
  26236. cumulativeAmount += weights[index];
  26237. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26238. index++;
  26239. }
  26240. return cumulativeQuaternion;
  26241. };
  26242. Scene.prototype._processLateAnimationBindings = function () {
  26243. if (!this._registeredForLateAnimationBindings.length) {
  26244. return;
  26245. }
  26246. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26247. var target = this._registeredForLateAnimationBindings.data[index];
  26248. for (var path in target._lateAnimationHolders) {
  26249. var holder = target._lateAnimationHolders[path];
  26250. var originalAnimation = holder.animations[0];
  26251. var originalValue = holder.originalValue;
  26252. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26253. var finalValue = target[path];
  26254. if (matrixDecomposeMode) {
  26255. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26256. }
  26257. else {
  26258. var quaternionMode = originalValue.w !== undefined;
  26259. if (quaternionMode) {
  26260. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26261. }
  26262. else {
  26263. var startIndex = 0;
  26264. var normalizer = 1.0;
  26265. if (holder.totalWeight < 1.0) {
  26266. // We need to mix the original value in
  26267. if (originalValue.scale) {
  26268. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26269. }
  26270. else {
  26271. finalValue = originalValue * (1.0 - holder.totalWeight);
  26272. }
  26273. }
  26274. else {
  26275. // We need to normalize the weights
  26276. normalizer = holder.totalWeight;
  26277. var scale_1 = originalAnimation.weight / normalizer;
  26278. if (scale_1 !== 1) {
  26279. if (originalAnimation.currentValue.scale) {
  26280. finalValue = originalAnimation.currentValue.scale(scale_1);
  26281. }
  26282. else {
  26283. finalValue = originalAnimation.currentValue * scale_1;
  26284. }
  26285. }
  26286. else {
  26287. finalValue = originalAnimation.currentValue;
  26288. }
  26289. startIndex = 1;
  26290. }
  26291. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26292. var runtimeAnimation = holder.animations[animIndex];
  26293. var scale = runtimeAnimation.weight / normalizer;
  26294. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26295. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26296. }
  26297. else {
  26298. finalValue += runtimeAnimation.currentValue * scale;
  26299. }
  26300. }
  26301. }
  26302. }
  26303. target[path] = finalValue;
  26304. }
  26305. target._lateAnimationHolders = {};
  26306. }
  26307. this._registeredForLateAnimationBindings.reset();
  26308. };
  26309. // Matrix
  26310. /** @hidden */
  26311. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26312. this._useAlternateCameraConfiguration = active;
  26313. };
  26314. /**
  26315. * Gets the current view matrix
  26316. * @returns a Matrix
  26317. */
  26318. Scene.prototype.getViewMatrix = function () {
  26319. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26320. };
  26321. /**
  26322. * Gets the current projection matrix
  26323. * @returns a Matrix
  26324. */
  26325. Scene.prototype.getProjectionMatrix = function () {
  26326. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26327. };
  26328. /**
  26329. * Gets the current transform matrix
  26330. * @returns a Matrix made of View * Projection
  26331. */
  26332. Scene.prototype.getTransformMatrix = function () {
  26333. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26334. };
  26335. /**
  26336. * Sets the current transform matrix
  26337. * @param view defines the View matrix to use
  26338. * @param projection defines the Projection matrix to use
  26339. */
  26340. Scene.prototype.setTransformMatrix = function (view, projection) {
  26341. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26342. return;
  26343. }
  26344. this._viewUpdateFlag = view.updateFlag;
  26345. this._projectionUpdateFlag = projection.updateFlag;
  26346. this._viewMatrix = view;
  26347. this._projectionMatrix = projection;
  26348. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26349. // Update frustum
  26350. if (!this._frustumPlanes) {
  26351. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26352. }
  26353. else {
  26354. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26355. }
  26356. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26357. var otherCamera = this.activeCamera._alternateCamera;
  26358. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26359. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26360. }
  26361. if (this._sceneUbo.useUbo) {
  26362. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26363. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26364. this._sceneUbo.update();
  26365. }
  26366. };
  26367. /** @hidden */
  26368. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26369. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26370. return;
  26371. }
  26372. this._alternateViewUpdateFlag = view.updateFlag;
  26373. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26374. this._alternateViewMatrix = view;
  26375. this._alternateProjectionMatrix = projection;
  26376. if (!this._alternateTransformMatrix) {
  26377. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26378. }
  26379. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26380. if (!this._alternateSceneUbo) {
  26381. this._createAlternateUbo();
  26382. }
  26383. if (this._alternateSceneUbo.useUbo) {
  26384. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26385. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26386. this._alternateSceneUbo.update();
  26387. }
  26388. };
  26389. /**
  26390. * Gets the uniform buffer used to store scene data
  26391. * @returns a UniformBuffer
  26392. */
  26393. Scene.prototype.getSceneUniformBuffer = function () {
  26394. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26395. };
  26396. /**
  26397. * Gets an unique (relatively to the current scene) Id
  26398. * @returns an unique number for the scene
  26399. */
  26400. Scene.prototype.getUniqueId = function () {
  26401. var result = Scene._uniqueIdCounter;
  26402. Scene._uniqueIdCounter++;
  26403. return result;
  26404. };
  26405. /**
  26406. * Add a mesh to the list of scene's meshes
  26407. * @param newMesh defines the mesh to add
  26408. * @param recursive if all child meshes should also be added to the scene
  26409. */
  26410. Scene.prototype.addMesh = function (newMesh, recursive) {
  26411. var _this = this;
  26412. if (recursive === void 0) { recursive = false; }
  26413. this.meshes.push(newMesh);
  26414. //notify the collision coordinator
  26415. if (this.collisionCoordinator) {
  26416. this.collisionCoordinator.onMeshAdded(newMesh);
  26417. }
  26418. newMesh._resyncLightSources();
  26419. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26420. if (recursive) {
  26421. newMesh.getChildMeshes().forEach(function (m) {
  26422. _this.addMesh(m);
  26423. });
  26424. }
  26425. };
  26426. /**
  26427. * Remove a mesh for the list of scene's meshes
  26428. * @param toRemove defines the mesh to remove
  26429. * @param recursive if all child meshes should also be removed from the scene
  26430. * @returns the index where the mesh was in the mesh list
  26431. */
  26432. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26433. var _this = this;
  26434. if (recursive === void 0) { recursive = false; }
  26435. var index = this.meshes.indexOf(toRemove);
  26436. if (index !== -1) {
  26437. // Remove from the scene if mesh found
  26438. this.meshes.splice(index, 1);
  26439. }
  26440. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26441. if (recursive) {
  26442. toRemove.getChildMeshes().forEach(function (m) {
  26443. _this.removeMesh(m);
  26444. });
  26445. }
  26446. return index;
  26447. };
  26448. /**
  26449. * Add a transform node to the list of scene's transform nodes
  26450. * @param newTransformNode defines the transform node to add
  26451. */
  26452. Scene.prototype.addTransformNode = function (newTransformNode) {
  26453. this.transformNodes.push(newTransformNode);
  26454. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26455. };
  26456. /**
  26457. * Remove a transform node for the list of scene's transform nodes
  26458. * @param toRemove defines the transform node to remove
  26459. * @returns the index where the transform node was in the transform node list
  26460. */
  26461. Scene.prototype.removeTransformNode = function (toRemove) {
  26462. var index = this.transformNodes.indexOf(toRemove);
  26463. if (index !== -1) {
  26464. // Remove from the scene if found
  26465. this.transformNodes.splice(index, 1);
  26466. }
  26467. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26468. return index;
  26469. };
  26470. /**
  26471. * Remove a skeleton for the list of scene's skeletons
  26472. * @param toRemove defines the skeleton to remove
  26473. * @returns the index where the skeleton was in the skeleton list
  26474. */
  26475. Scene.prototype.removeSkeleton = function (toRemove) {
  26476. var index = this.skeletons.indexOf(toRemove);
  26477. if (index !== -1) {
  26478. // Remove from the scene if found
  26479. this.skeletons.splice(index, 1);
  26480. }
  26481. return index;
  26482. };
  26483. /**
  26484. * Remove a morph target for the list of scene's morph targets
  26485. * @param toRemove defines the morph target to remove
  26486. * @returns the index where the morph target was in the morph target list
  26487. */
  26488. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26489. var index = this.morphTargetManagers.indexOf(toRemove);
  26490. if (index !== -1) {
  26491. // Remove from the scene if found
  26492. this.morphTargetManagers.splice(index, 1);
  26493. }
  26494. return index;
  26495. };
  26496. /**
  26497. * Remove a light for the list of scene's lights
  26498. * @param toRemove defines the light to remove
  26499. * @returns the index where the light was in the light list
  26500. */
  26501. Scene.prototype.removeLight = function (toRemove) {
  26502. var index = this.lights.indexOf(toRemove);
  26503. if (index !== -1) {
  26504. // Remove from meshes
  26505. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26506. var mesh = _a[_i];
  26507. mesh._removeLightSource(toRemove);
  26508. }
  26509. // Remove from the scene if mesh found
  26510. this.lights.splice(index, 1);
  26511. this.sortLightsByPriority();
  26512. }
  26513. this.onLightRemovedObservable.notifyObservers(toRemove);
  26514. return index;
  26515. };
  26516. /**
  26517. * Remove a camera for the list of scene's cameras
  26518. * @param toRemove defines the camera to remove
  26519. * @returns the index where the camera was in the camera list
  26520. */
  26521. Scene.prototype.removeCamera = function (toRemove) {
  26522. var index = this.cameras.indexOf(toRemove);
  26523. if (index !== -1) {
  26524. // Remove from the scene if mesh found
  26525. this.cameras.splice(index, 1);
  26526. }
  26527. // Remove from activeCameras
  26528. var index2 = this.activeCameras.indexOf(toRemove);
  26529. if (index2 !== -1) {
  26530. // Remove from the scene if mesh found
  26531. this.activeCameras.splice(index2, 1);
  26532. }
  26533. // Reset the activeCamera
  26534. if (this.activeCamera === toRemove) {
  26535. if (this.cameras.length > 0) {
  26536. this.activeCamera = this.cameras[0];
  26537. }
  26538. else {
  26539. this.activeCamera = null;
  26540. }
  26541. }
  26542. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26543. return index;
  26544. };
  26545. /**
  26546. * Remove a particle system for the list of scene's particle systems
  26547. * @param toRemove defines the particle system to remove
  26548. * @returns the index where the particle system was in the particle system list
  26549. */
  26550. Scene.prototype.removeParticleSystem = function (toRemove) {
  26551. var index = this.particleSystems.indexOf(toRemove);
  26552. if (index !== -1) {
  26553. this.particleSystems.splice(index, 1);
  26554. }
  26555. return index;
  26556. };
  26557. /**
  26558. * Remove a animation for the list of scene's animations
  26559. * @param toRemove defines the animation to remove
  26560. * @returns the index where the animation was in the animation list
  26561. */
  26562. Scene.prototype.removeAnimation = function (toRemove) {
  26563. var index = this.animations.indexOf(toRemove);
  26564. if (index !== -1) {
  26565. this.animations.splice(index, 1);
  26566. }
  26567. return index;
  26568. };
  26569. /**
  26570. * Removes the given animation group from this scene.
  26571. * @param toRemove The animation group to remove
  26572. * @returns The index of the removed animation group
  26573. */
  26574. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26575. var index = this.animationGroups.indexOf(toRemove);
  26576. if (index !== -1) {
  26577. this.animationGroups.splice(index, 1);
  26578. }
  26579. return index;
  26580. };
  26581. /**
  26582. * Removes the given multi-material from this scene.
  26583. * @param toRemove The multi-material to remove
  26584. * @returns The index of the removed multi-material
  26585. */
  26586. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26587. var index = this.multiMaterials.indexOf(toRemove);
  26588. if (index !== -1) {
  26589. this.multiMaterials.splice(index, 1);
  26590. }
  26591. return index;
  26592. };
  26593. /**
  26594. * Removes the given material from this scene.
  26595. * @param toRemove The material to remove
  26596. * @returns The index of the removed material
  26597. */
  26598. Scene.prototype.removeMaterial = function (toRemove) {
  26599. var index = this.materials.indexOf(toRemove);
  26600. if (index !== -1) {
  26601. this.materials.splice(index, 1);
  26602. }
  26603. return index;
  26604. };
  26605. /**
  26606. * Removes the given action manager from this scene.
  26607. * @param toRemove The action manager to remove
  26608. * @returns The index of the removed action manager
  26609. */
  26610. Scene.prototype.removeActionManager = function (toRemove) {
  26611. var index = this.actionManagers.indexOf(toRemove);
  26612. if (index !== -1) {
  26613. this.actionManagers.splice(index, 1);
  26614. }
  26615. return index;
  26616. };
  26617. /**
  26618. * Removes the given texture from this scene.
  26619. * @param toRemove The texture to remove
  26620. * @returns The index of the removed texture
  26621. */
  26622. Scene.prototype.removeTexture = function (toRemove) {
  26623. var index = this.textures.indexOf(toRemove);
  26624. if (index !== -1) {
  26625. this.textures.splice(index, 1);
  26626. }
  26627. return index;
  26628. };
  26629. /**
  26630. * Adds the given light to this scene
  26631. * @param newLight The light to add
  26632. */
  26633. Scene.prototype.addLight = function (newLight) {
  26634. this.lights.push(newLight);
  26635. this.sortLightsByPriority();
  26636. // Add light to all meshes (To support if the light is removed and then readded)
  26637. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26638. var mesh = _a[_i];
  26639. if (mesh._lightSources.indexOf(newLight) === -1) {
  26640. mesh._lightSources.push(newLight);
  26641. mesh._resyncLightSources();
  26642. }
  26643. }
  26644. this.onNewLightAddedObservable.notifyObservers(newLight);
  26645. };
  26646. /**
  26647. * Sorts the list list based on light priorities
  26648. */
  26649. Scene.prototype.sortLightsByPriority = function () {
  26650. if (this.requireLightSorting) {
  26651. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26652. }
  26653. };
  26654. /**
  26655. * Adds the given camera to this scene
  26656. * @param newCamera The camera to add
  26657. */
  26658. Scene.prototype.addCamera = function (newCamera) {
  26659. this.cameras.push(newCamera);
  26660. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26661. };
  26662. /**
  26663. * Adds the given skeleton to this scene
  26664. * @param newSkeleton The skeleton to add
  26665. */
  26666. Scene.prototype.addSkeleton = function (newSkeleton) {
  26667. this.skeletons.push(newSkeleton);
  26668. };
  26669. /**
  26670. * Adds the given particle system to this scene
  26671. * @param newParticleSystem The particle system to add
  26672. */
  26673. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26674. this.particleSystems.push(newParticleSystem);
  26675. };
  26676. /**
  26677. * Adds the given animation to this scene
  26678. * @param newAnimation The animation to add
  26679. */
  26680. Scene.prototype.addAnimation = function (newAnimation) {
  26681. this.animations.push(newAnimation);
  26682. };
  26683. /**
  26684. * Adds the given animation group to this scene.
  26685. * @param newAnimationGroup The animation group to add
  26686. */
  26687. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26688. this.animationGroups.push(newAnimationGroup);
  26689. };
  26690. /**
  26691. * Adds the given multi-material to this scene
  26692. * @param newMultiMaterial The multi-material to add
  26693. */
  26694. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26695. this.multiMaterials.push(newMultiMaterial);
  26696. };
  26697. /**
  26698. * Adds the given material to this scene
  26699. * @param newMaterial The material to add
  26700. */
  26701. Scene.prototype.addMaterial = function (newMaterial) {
  26702. this.materials.push(newMaterial);
  26703. };
  26704. /**
  26705. * Adds the given morph target to this scene
  26706. * @param newMorphTargetManager The morph target to add
  26707. */
  26708. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26709. this.morphTargetManagers.push(newMorphTargetManager);
  26710. };
  26711. /**
  26712. * Adds the given geometry to this scene
  26713. * @param newGeometry The geometry to add
  26714. */
  26715. Scene.prototype.addGeometry = function (newGeometry) {
  26716. this.geometries.push(newGeometry);
  26717. };
  26718. /**
  26719. * Adds the given action manager to this scene
  26720. * @param newActionManager The action manager to add
  26721. */
  26722. Scene.prototype.addActionManager = function (newActionManager) {
  26723. this.actionManagers.push(newActionManager);
  26724. };
  26725. /**
  26726. * Adds the given texture to this scene.
  26727. * @param newTexture The texture to add
  26728. */
  26729. Scene.prototype.addTexture = function (newTexture) {
  26730. this.textures.push(newTexture);
  26731. };
  26732. /**
  26733. * Switch active camera
  26734. * @param newCamera defines the new active camera
  26735. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26736. */
  26737. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26738. if (attachControl === void 0) { attachControl = true; }
  26739. var canvas = this._engine.getRenderingCanvas();
  26740. if (!canvas) {
  26741. return;
  26742. }
  26743. if (this.activeCamera) {
  26744. this.activeCamera.detachControl(canvas);
  26745. }
  26746. this.activeCamera = newCamera;
  26747. if (attachControl) {
  26748. newCamera.attachControl(canvas);
  26749. }
  26750. };
  26751. /**
  26752. * sets the active camera of the scene using its ID
  26753. * @param id defines the camera's ID
  26754. * @return the new active camera or null if none found.
  26755. */
  26756. Scene.prototype.setActiveCameraByID = function (id) {
  26757. var camera = this.getCameraByID(id);
  26758. if (camera) {
  26759. this.activeCamera = camera;
  26760. return camera;
  26761. }
  26762. return null;
  26763. };
  26764. /**
  26765. * sets the active camera of the scene using its name
  26766. * @param name defines the camera's name
  26767. * @returns the new active camera or null if none found.
  26768. */
  26769. Scene.prototype.setActiveCameraByName = function (name) {
  26770. var camera = this.getCameraByName(name);
  26771. if (camera) {
  26772. this.activeCamera = camera;
  26773. return camera;
  26774. }
  26775. return null;
  26776. };
  26777. /**
  26778. * get an animation group using its name
  26779. * @param name defines the material's name
  26780. * @return the animation group or null if none found.
  26781. */
  26782. Scene.prototype.getAnimationGroupByName = function (name) {
  26783. for (var index = 0; index < this.animationGroups.length; index++) {
  26784. if (this.animationGroups[index].name === name) {
  26785. return this.animationGroups[index];
  26786. }
  26787. }
  26788. return null;
  26789. };
  26790. /**
  26791. * get a material using its id
  26792. * @param id defines the material's ID
  26793. * @return the material or null if none found.
  26794. */
  26795. Scene.prototype.getMaterialByID = function (id) {
  26796. for (var index = 0; index < this.materials.length; index++) {
  26797. if (this.materials[index].id === id) {
  26798. return this.materials[index];
  26799. }
  26800. }
  26801. return null;
  26802. };
  26803. /**
  26804. * Gets a material using its name
  26805. * @param name defines the material's name
  26806. * @return the material or null if none found.
  26807. */
  26808. Scene.prototype.getMaterialByName = function (name) {
  26809. for (var index = 0; index < this.materials.length; index++) {
  26810. if (this.materials[index].name === name) {
  26811. return this.materials[index];
  26812. }
  26813. }
  26814. return null;
  26815. };
  26816. /**
  26817. * Gets a camera using its id
  26818. * @param id defines the id to look for
  26819. * @returns the camera or null if not found
  26820. */
  26821. Scene.prototype.getCameraByID = function (id) {
  26822. for (var index = 0; index < this.cameras.length; index++) {
  26823. if (this.cameras[index].id === id) {
  26824. return this.cameras[index];
  26825. }
  26826. }
  26827. return null;
  26828. };
  26829. /**
  26830. * Gets a camera using its unique id
  26831. * @param uniqueId defines the unique id to look for
  26832. * @returns the camera or null if not found
  26833. */
  26834. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26835. for (var index = 0; index < this.cameras.length; index++) {
  26836. if (this.cameras[index].uniqueId === uniqueId) {
  26837. return this.cameras[index];
  26838. }
  26839. }
  26840. return null;
  26841. };
  26842. /**
  26843. * Gets a camera using its name
  26844. * @param name defines the camera's name
  26845. * @return the camera or null if none found.
  26846. */
  26847. Scene.prototype.getCameraByName = function (name) {
  26848. for (var index = 0; index < this.cameras.length; index++) {
  26849. if (this.cameras[index].name === name) {
  26850. return this.cameras[index];
  26851. }
  26852. }
  26853. return null;
  26854. };
  26855. /**
  26856. * Gets a bone using its id
  26857. * @param id defines the bone's id
  26858. * @return the bone or null if not found
  26859. */
  26860. Scene.prototype.getBoneByID = function (id) {
  26861. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26862. var skeleton = this.skeletons[skeletonIndex];
  26863. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26864. if (skeleton.bones[boneIndex].id === id) {
  26865. return skeleton.bones[boneIndex];
  26866. }
  26867. }
  26868. }
  26869. return null;
  26870. };
  26871. /**
  26872. * Gets a bone using its id
  26873. * @param name defines the bone's name
  26874. * @return the bone or null if not found
  26875. */
  26876. Scene.prototype.getBoneByName = function (name) {
  26877. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26878. var skeleton = this.skeletons[skeletonIndex];
  26879. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26880. if (skeleton.bones[boneIndex].name === name) {
  26881. return skeleton.bones[boneIndex];
  26882. }
  26883. }
  26884. }
  26885. return null;
  26886. };
  26887. /**
  26888. * Gets a light node using its name
  26889. * @param name defines the the light's name
  26890. * @return the light or null if none found.
  26891. */
  26892. Scene.prototype.getLightByName = function (name) {
  26893. for (var index = 0; index < this.lights.length; index++) {
  26894. if (this.lights[index].name === name) {
  26895. return this.lights[index];
  26896. }
  26897. }
  26898. return null;
  26899. };
  26900. /**
  26901. * Gets a light node using its id
  26902. * @param id defines the light's id
  26903. * @return the light or null if none found.
  26904. */
  26905. Scene.prototype.getLightByID = function (id) {
  26906. for (var index = 0; index < this.lights.length; index++) {
  26907. if (this.lights[index].id === id) {
  26908. return this.lights[index];
  26909. }
  26910. }
  26911. return null;
  26912. };
  26913. /**
  26914. * Gets a light node using its scene-generated unique ID
  26915. * @param uniqueId defines the light's unique id
  26916. * @return the light or null if none found.
  26917. */
  26918. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26919. for (var index = 0; index < this.lights.length; index++) {
  26920. if (this.lights[index].uniqueId === uniqueId) {
  26921. return this.lights[index];
  26922. }
  26923. }
  26924. return null;
  26925. };
  26926. /**
  26927. * Gets a particle system by id
  26928. * @param id defines the particle system id
  26929. * @return the corresponding system or null if none found
  26930. */
  26931. Scene.prototype.getParticleSystemByID = function (id) {
  26932. for (var index = 0; index < this.particleSystems.length; index++) {
  26933. if (this.particleSystems[index].id === id) {
  26934. return this.particleSystems[index];
  26935. }
  26936. }
  26937. return null;
  26938. };
  26939. /**
  26940. * Gets a geometry using its ID
  26941. * @param id defines the geometry's id
  26942. * @return the geometry or null if none found.
  26943. */
  26944. Scene.prototype.getGeometryByID = function (id) {
  26945. for (var index = 0; index < this.geometries.length; index++) {
  26946. if (this.geometries[index].id === id) {
  26947. return this.geometries[index];
  26948. }
  26949. }
  26950. return null;
  26951. };
  26952. /**
  26953. * Add a new geometry to this scene
  26954. * @param geometry defines the geometry to be added to the scene.
  26955. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26956. * @return a boolean defining if the geometry was added or not
  26957. */
  26958. Scene.prototype.pushGeometry = function (geometry, force) {
  26959. if (!force && this.getGeometryByID(geometry.id)) {
  26960. return false;
  26961. }
  26962. this.geometries.push(geometry);
  26963. //notify the collision coordinator
  26964. if (this.collisionCoordinator) {
  26965. this.collisionCoordinator.onGeometryAdded(geometry);
  26966. }
  26967. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26968. return true;
  26969. };
  26970. /**
  26971. * Removes an existing geometry
  26972. * @param geometry defines the geometry to be removed from the scene
  26973. * @return a boolean defining if the geometry was removed or not
  26974. */
  26975. Scene.prototype.removeGeometry = function (geometry) {
  26976. var index = this.geometries.indexOf(geometry);
  26977. if (index > -1) {
  26978. this.geometries.splice(index, 1);
  26979. //notify the collision coordinator
  26980. if (this.collisionCoordinator) {
  26981. this.collisionCoordinator.onGeometryDeleted(geometry);
  26982. }
  26983. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26984. return true;
  26985. }
  26986. return false;
  26987. };
  26988. /**
  26989. * Gets the list of geometries attached to the scene
  26990. * @returns an array of Geometry
  26991. */
  26992. Scene.prototype.getGeometries = function () {
  26993. return this.geometries;
  26994. };
  26995. /**
  26996. * Gets the first added mesh found of a given ID
  26997. * @param id defines the id to search for
  26998. * @return the mesh found or null if not found at all
  26999. */
  27000. Scene.prototype.getMeshByID = function (id) {
  27001. for (var index = 0; index < this.meshes.length; index++) {
  27002. if (this.meshes[index].id === id) {
  27003. return this.meshes[index];
  27004. }
  27005. }
  27006. return null;
  27007. };
  27008. /**
  27009. * Gets a list of meshes using their id
  27010. * @param id defines the id to search for
  27011. * @returns a list of meshes
  27012. */
  27013. Scene.prototype.getMeshesByID = function (id) {
  27014. return this.meshes.filter(function (m) {
  27015. return m.id === id;
  27016. });
  27017. };
  27018. /**
  27019. * Gets the first added transform node found of a given ID
  27020. * @param id defines the id to search for
  27021. * @return the found transform node or null if not found at all.
  27022. */
  27023. Scene.prototype.getTransformNodeByID = function (id) {
  27024. for (var index = 0; index < this.transformNodes.length; index++) {
  27025. if (this.transformNodes[index].id === id) {
  27026. return this.transformNodes[index];
  27027. }
  27028. }
  27029. return null;
  27030. };
  27031. /**
  27032. * Gets a list of transform nodes using their id
  27033. * @param id defines the id to search for
  27034. * @returns a list of transform nodes
  27035. */
  27036. Scene.prototype.getTransformNodesByID = function (id) {
  27037. return this.transformNodes.filter(function (m) {
  27038. return m.id === id;
  27039. });
  27040. };
  27041. /**
  27042. * Gets a mesh with its auto-generated unique id
  27043. * @param uniqueId defines the unique id to search for
  27044. * @return the found mesh or null if not found at all.
  27045. */
  27046. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27047. for (var index = 0; index < this.meshes.length; index++) {
  27048. if (this.meshes[index].uniqueId === uniqueId) {
  27049. return this.meshes[index];
  27050. }
  27051. }
  27052. return null;
  27053. };
  27054. /**
  27055. * Gets a the last added mesh using a given id
  27056. * @param id defines the id to search for
  27057. * @return the found mesh or null if not found at all.
  27058. */
  27059. Scene.prototype.getLastMeshByID = function (id) {
  27060. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27061. if (this.meshes[index].id === id) {
  27062. return this.meshes[index];
  27063. }
  27064. }
  27065. return null;
  27066. };
  27067. /**
  27068. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27069. * @param id defines the id to search for
  27070. * @return the found node or null if not found at all
  27071. */
  27072. Scene.prototype.getLastEntryByID = function (id) {
  27073. var index;
  27074. for (index = this.meshes.length - 1; index >= 0; index--) {
  27075. if (this.meshes[index].id === id) {
  27076. return this.meshes[index];
  27077. }
  27078. }
  27079. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27080. if (this.transformNodes[index].id === id) {
  27081. return this.transformNodes[index];
  27082. }
  27083. }
  27084. for (index = this.cameras.length - 1; index >= 0; index--) {
  27085. if (this.cameras[index].id === id) {
  27086. return this.cameras[index];
  27087. }
  27088. }
  27089. for (index = this.lights.length - 1; index >= 0; index--) {
  27090. if (this.lights[index].id === id) {
  27091. return this.lights[index];
  27092. }
  27093. }
  27094. return null;
  27095. };
  27096. /**
  27097. * Gets a node (Mesh, Camera, Light) using a given id
  27098. * @param id defines the id to search for
  27099. * @return the found node or null if not found at all
  27100. */
  27101. Scene.prototype.getNodeByID = function (id) {
  27102. var mesh = this.getMeshByID(id);
  27103. if (mesh) {
  27104. return mesh;
  27105. }
  27106. var light = this.getLightByID(id);
  27107. if (light) {
  27108. return light;
  27109. }
  27110. var camera = this.getCameraByID(id);
  27111. if (camera) {
  27112. return camera;
  27113. }
  27114. var bone = this.getBoneByID(id);
  27115. return bone;
  27116. };
  27117. /**
  27118. * Gets a node (Mesh, Camera, Light) using a given name
  27119. * @param name defines the name to search for
  27120. * @return the found node or null if not found at all.
  27121. */
  27122. Scene.prototype.getNodeByName = function (name) {
  27123. var mesh = this.getMeshByName(name);
  27124. if (mesh) {
  27125. return mesh;
  27126. }
  27127. var light = this.getLightByName(name);
  27128. if (light) {
  27129. return light;
  27130. }
  27131. var camera = this.getCameraByName(name);
  27132. if (camera) {
  27133. return camera;
  27134. }
  27135. var bone = this.getBoneByName(name);
  27136. return bone;
  27137. };
  27138. /**
  27139. * Gets a mesh using a given name
  27140. * @param name defines the name to search for
  27141. * @return the found mesh or null if not found at all.
  27142. */
  27143. Scene.prototype.getMeshByName = function (name) {
  27144. for (var index = 0; index < this.meshes.length; index++) {
  27145. if (this.meshes[index].name === name) {
  27146. return this.meshes[index];
  27147. }
  27148. }
  27149. return null;
  27150. };
  27151. /**
  27152. * Gets a transform node using a given name
  27153. * @param name defines the name to search for
  27154. * @return the found transform node or null if not found at all.
  27155. */
  27156. Scene.prototype.getTransformNodeByName = function (name) {
  27157. for (var index = 0; index < this.transformNodes.length; index++) {
  27158. if (this.transformNodes[index].name === name) {
  27159. return this.transformNodes[index];
  27160. }
  27161. }
  27162. return null;
  27163. };
  27164. /**
  27165. * Gets a sound using a given name
  27166. * @param name defines the name to search for
  27167. * @return the found sound or null if not found at all.
  27168. */
  27169. Scene.prototype.getSoundByName = function (name) {
  27170. var index;
  27171. if (BABYLON.AudioEngine) {
  27172. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27173. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27174. return this.mainSoundTrack.soundCollection[index];
  27175. }
  27176. }
  27177. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27178. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27179. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27180. return this.soundTracks[sdIndex].soundCollection[index];
  27181. }
  27182. }
  27183. }
  27184. }
  27185. return null;
  27186. };
  27187. /**
  27188. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27189. * @param id defines the id to search for
  27190. * @return the found skeleton or null if not found at all.
  27191. */
  27192. Scene.prototype.getLastSkeletonByID = function (id) {
  27193. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27194. if (this.skeletons[index].id === id) {
  27195. return this.skeletons[index];
  27196. }
  27197. }
  27198. return null;
  27199. };
  27200. /**
  27201. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27202. * @param id defines the id to search for
  27203. * @return the found skeleton or null if not found at all.
  27204. */
  27205. Scene.prototype.getSkeletonById = function (id) {
  27206. for (var index = 0; index < this.skeletons.length; index++) {
  27207. if (this.skeletons[index].id === id) {
  27208. return this.skeletons[index];
  27209. }
  27210. }
  27211. return null;
  27212. };
  27213. /**
  27214. * Gets a skeleton using a given name
  27215. * @param name defines the name to search for
  27216. * @return the found skeleton or null if not found at all.
  27217. */
  27218. Scene.prototype.getSkeletonByName = function (name) {
  27219. for (var index = 0; index < this.skeletons.length; index++) {
  27220. if (this.skeletons[index].name === name) {
  27221. return this.skeletons[index];
  27222. }
  27223. }
  27224. return null;
  27225. };
  27226. /**
  27227. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27228. * @param id defines the id to search for
  27229. * @return the found morph target manager or null if not found at all.
  27230. */
  27231. Scene.prototype.getMorphTargetManagerById = function (id) {
  27232. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27233. if (this.morphTargetManagers[index].uniqueId === id) {
  27234. return this.morphTargetManagers[index];
  27235. }
  27236. }
  27237. return null;
  27238. };
  27239. /**
  27240. * Gets a boolean indicating if the given mesh is active
  27241. * @param mesh defines the mesh to look for
  27242. * @returns true if the mesh is in the active list
  27243. */
  27244. Scene.prototype.isActiveMesh = function (mesh) {
  27245. return (this._activeMeshes.indexOf(mesh) !== -1);
  27246. };
  27247. Object.defineProperty(Scene.prototype, "uid", {
  27248. /**
  27249. * Return a unique id as a string which can serve as an identifier for the scene
  27250. */
  27251. get: function () {
  27252. if (!this._uid) {
  27253. this._uid = BABYLON.Tools.RandomId();
  27254. }
  27255. return this._uid;
  27256. },
  27257. enumerable: true,
  27258. configurable: true
  27259. });
  27260. /**
  27261. * Add an externaly attached data from its key.
  27262. * This method call will fail and return false, if such key already exists.
  27263. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27264. * @param key the unique key that identifies the data
  27265. * @param data the data object to associate to the key for this Engine instance
  27266. * @return true if no such key were already present and the data was added successfully, false otherwise
  27267. */
  27268. Scene.prototype.addExternalData = function (key, data) {
  27269. if (!this._externalData) {
  27270. this._externalData = new BABYLON.StringDictionary();
  27271. }
  27272. return this._externalData.add(key, data);
  27273. };
  27274. /**
  27275. * Get an externaly attached data from its key
  27276. * @param key the unique key that identifies the data
  27277. * @return the associated data, if present (can be null), or undefined if not present
  27278. */
  27279. Scene.prototype.getExternalData = function (key) {
  27280. if (!this._externalData) {
  27281. return null;
  27282. }
  27283. return this._externalData.get(key);
  27284. };
  27285. /**
  27286. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27287. * @param key the unique key that identifies the data
  27288. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27289. * @return the associated data, can be null if the factory returned null.
  27290. */
  27291. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27292. if (!this._externalData) {
  27293. this._externalData = new BABYLON.StringDictionary();
  27294. }
  27295. return this._externalData.getOrAddWithFactory(key, factory);
  27296. };
  27297. /**
  27298. * Remove an externaly attached data from the Engine instance
  27299. * @param key the unique key that identifies the data
  27300. * @return true if the data was successfully removed, false if it doesn't exist
  27301. */
  27302. Scene.prototype.removeExternalData = function (key) {
  27303. return this._externalData.remove(key);
  27304. };
  27305. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27306. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27307. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27308. var step = _a[_i];
  27309. step.action(mesh, subMesh);
  27310. }
  27311. var material = subMesh.getMaterial();
  27312. if (material !== null && material !== undefined) {
  27313. // Render targets
  27314. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27315. if (this._processedMaterials.indexOf(material) === -1) {
  27316. this._processedMaterials.push(material);
  27317. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27318. }
  27319. }
  27320. // Dispatch
  27321. this._activeIndices.addCount(subMesh.indexCount, false);
  27322. this._renderingManager.dispatch(subMesh, mesh, material);
  27323. }
  27324. }
  27325. };
  27326. /**
  27327. * Clear the processed materials smart array preventing retention point in material dispose.
  27328. */
  27329. Scene.prototype.freeProcessedMaterials = function () {
  27330. this._processedMaterials.dispose();
  27331. };
  27332. /**
  27333. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27334. */
  27335. Scene.prototype.freeActiveMeshes = function () {
  27336. this._activeMeshes.dispose();
  27337. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27338. this.activeCamera._activeMeshes.dispose();
  27339. }
  27340. if (this.activeCameras) {
  27341. for (var i = 0; i < this.activeCameras.length; i++) {
  27342. var activeCamera = this.activeCameras[i];
  27343. if (activeCamera && activeCamera._activeMeshes) {
  27344. activeCamera._activeMeshes.dispose();
  27345. }
  27346. }
  27347. }
  27348. };
  27349. /**
  27350. * Clear the info related to rendering groups preventing retention points during dispose.
  27351. */
  27352. Scene.prototype.freeRenderingGroups = function () {
  27353. if (this._renderingManager) {
  27354. this._renderingManager.freeRenderingGroups();
  27355. }
  27356. if (this.textures) {
  27357. for (var i = 0; i < this.textures.length; i++) {
  27358. var texture = this.textures[i];
  27359. if (texture && texture.renderList) {
  27360. texture.freeRenderingGroups();
  27361. }
  27362. }
  27363. }
  27364. };
  27365. /** @hidden */
  27366. Scene.prototype._isInIntermediateRendering = function () {
  27367. return this._intermediateRendering;
  27368. };
  27369. /**
  27370. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27371. * @returns the current scene
  27372. */
  27373. Scene.prototype.freezeActiveMeshes = function () {
  27374. if (!this.activeCamera) {
  27375. return this;
  27376. }
  27377. if (!this._frustumPlanes) {
  27378. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27379. }
  27380. this._evaluateActiveMeshes();
  27381. this._activeMeshesFrozen = true;
  27382. return this;
  27383. };
  27384. /**
  27385. * Use this function to restart evaluating active meshes on every frame
  27386. * @returns the current scene
  27387. */
  27388. Scene.prototype.unfreezeActiveMeshes = function () {
  27389. this._activeMeshesFrozen = false;
  27390. return this;
  27391. };
  27392. Scene.prototype._evaluateActiveMeshes = function () {
  27393. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27394. return;
  27395. }
  27396. if (!this.activeCamera) {
  27397. return;
  27398. }
  27399. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27400. this.activeCamera._activeMeshes.reset();
  27401. this._activeMeshes.reset();
  27402. this._renderingManager.reset();
  27403. this._processedMaterials.reset();
  27404. this._activeParticleSystems.reset();
  27405. this._activeSkeletons.reset();
  27406. this._softwareSkinnedMeshes.reset();
  27407. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27408. var step = _a[_i];
  27409. step.action();
  27410. }
  27411. // Determine mesh candidates
  27412. var meshes = this.getActiveMeshCandidates();
  27413. // Check each mesh
  27414. var len = meshes.length;
  27415. for (var i = 0; i < len; i++) {
  27416. var mesh = meshes.data[i];
  27417. if (mesh.isBlocked) {
  27418. continue;
  27419. }
  27420. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27421. if (!mesh.isReady() || !mesh.isEnabled()) {
  27422. continue;
  27423. }
  27424. mesh.computeWorldMatrix();
  27425. // Intersections
  27426. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27427. this._meshesForIntersections.pushNoDuplicate(mesh);
  27428. }
  27429. // Switch to current LOD
  27430. var meshLOD = mesh.getLOD(this.activeCamera);
  27431. if (meshLOD === undefined || meshLOD === null) {
  27432. continue;
  27433. }
  27434. mesh._preActivate();
  27435. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27436. this._activeMeshes.push(mesh);
  27437. this.activeCamera._activeMeshes.push(mesh);
  27438. mesh._activate(this._renderId);
  27439. if (meshLOD !== mesh) {
  27440. meshLOD._activate(this._renderId);
  27441. }
  27442. this._activeMesh(mesh, meshLOD);
  27443. }
  27444. }
  27445. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27446. // Particle systems
  27447. if (this.particlesEnabled) {
  27448. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27449. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27450. var particleSystem = this.particleSystems[particleIndex];
  27451. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27452. continue;
  27453. }
  27454. var emitter = particleSystem.emitter;
  27455. if (!emitter.position || emitter.isEnabled()) {
  27456. this._activeParticleSystems.push(particleSystem);
  27457. particleSystem.animate();
  27458. this._renderingManager.dispatchParticles(particleSystem);
  27459. }
  27460. }
  27461. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27462. }
  27463. };
  27464. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27465. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27466. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27467. mesh.skeleton.prepare();
  27468. }
  27469. if (!mesh.computeBonesUsingShaders) {
  27470. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27471. }
  27472. }
  27473. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27474. var step = _a[_i];
  27475. step.action(sourceMesh, mesh);
  27476. }
  27477. if (mesh !== undefined && mesh !== null
  27478. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27479. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27480. var len = subMeshes.length;
  27481. for (var i = 0; i < len; i++) {
  27482. var subMesh = subMeshes.data[i];
  27483. this._evaluateSubMesh(subMesh, mesh);
  27484. }
  27485. }
  27486. };
  27487. /**
  27488. * Update the transform matrix to update from the current active camera
  27489. * @param force defines a boolean used to force the update even if cache is up to date
  27490. */
  27491. Scene.prototype.updateTransformMatrix = function (force) {
  27492. if (!this.activeCamera) {
  27493. return;
  27494. }
  27495. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27496. };
  27497. /**
  27498. * 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)
  27499. * @param alternateCamera defines the camera to use
  27500. */
  27501. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27502. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27503. };
  27504. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27505. if (camera && camera._skipRendering) {
  27506. return;
  27507. }
  27508. var engine = this._engine;
  27509. this.activeCamera = camera;
  27510. if (!this.activeCamera)
  27511. throw new Error("Active camera not set");
  27512. // Viewport
  27513. engine.setViewport(this.activeCamera.viewport);
  27514. // Camera
  27515. this.resetCachedMaterial();
  27516. this._renderId++;
  27517. this.updateTransformMatrix();
  27518. if (camera._alternateCamera) {
  27519. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27520. this._alternateRendering = true;
  27521. }
  27522. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27523. // Meshes
  27524. this._evaluateActiveMeshes();
  27525. // Software skinning
  27526. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27527. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27528. mesh.applySkeleton(mesh.skeleton);
  27529. }
  27530. // Render targets
  27531. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27532. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27533. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27534. }
  27535. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27536. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27537. }
  27538. // Collects render targets from external components.
  27539. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27540. var step = _a[_i];
  27541. step.action(this._renderTargets);
  27542. }
  27543. if (this.renderTargetsEnabled) {
  27544. this._intermediateRendering = true;
  27545. if (this._renderTargets.length > 0) {
  27546. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27547. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27548. var renderTarget = this._renderTargets.data[renderIndex];
  27549. if (renderTarget._shouldRender()) {
  27550. this._renderId++;
  27551. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27552. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27553. }
  27554. }
  27555. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27556. this._renderId++;
  27557. }
  27558. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27559. var step = _c[_b];
  27560. step.action(this.activeCamera);
  27561. }
  27562. this._intermediateRendering = false;
  27563. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27564. }
  27565. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27566. // Prepare Frame
  27567. if (this.postProcessManager) {
  27568. this.postProcessManager._prepareFrame();
  27569. }
  27570. // Before Camera Draw
  27571. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27572. var step = _e[_d];
  27573. step.action(this.activeCamera);
  27574. }
  27575. // Render
  27576. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27577. this._renderingManager.render(null, null, true, true);
  27578. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27579. // After Camera Draw
  27580. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27581. var step = _g[_f];
  27582. step.action(this.activeCamera);
  27583. }
  27584. // Finalize frame
  27585. if (this.postProcessManager) {
  27586. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27587. }
  27588. // Reset some special arrays
  27589. this._renderTargets.reset();
  27590. this._alternateRendering = false;
  27591. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27592. };
  27593. Scene.prototype._processSubCameras = function (camera) {
  27594. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27595. this._renderForCamera(camera);
  27596. return;
  27597. }
  27598. // rig cameras
  27599. for (var index = 0; index < camera._rigCameras.length; index++) {
  27600. this._renderForCamera(camera._rigCameras[index], camera);
  27601. }
  27602. this.activeCamera = camera;
  27603. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27604. };
  27605. Scene.prototype._checkIntersections = function () {
  27606. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27607. var sourceMesh = this._meshesForIntersections.data[index];
  27608. if (!sourceMesh.actionManager) {
  27609. continue;
  27610. }
  27611. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27612. var action = sourceMesh.actionManager.actions[actionIndex];
  27613. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27614. var parameters = action.getTriggerParameter();
  27615. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27616. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27617. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27618. if (areIntersecting && currentIntersectionInProgress === -1) {
  27619. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27620. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27621. sourceMesh._intersectionsInProgress.push(otherMesh);
  27622. }
  27623. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27624. sourceMesh._intersectionsInProgress.push(otherMesh);
  27625. }
  27626. }
  27627. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27628. //They intersected, and now they don't.
  27629. //is this trigger an exit trigger? execute an event.
  27630. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27631. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27632. }
  27633. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27634. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27635. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27636. return otherMesh === parameterMesh;
  27637. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27638. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27639. }
  27640. }
  27641. }
  27642. }
  27643. }
  27644. };
  27645. /**
  27646. * Render the scene
  27647. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27648. */
  27649. Scene.prototype.render = function (updateCameras) {
  27650. if (updateCameras === void 0) { updateCameras = true; }
  27651. if (this.isDisposed) {
  27652. return;
  27653. }
  27654. this._frameId++;
  27655. // Register components that have been associated lately to the scene.
  27656. this._registerTransientComponents();
  27657. this._activeParticles.fetchNewFrame();
  27658. this._totalVertices.fetchNewFrame();
  27659. this._activeIndices.fetchNewFrame();
  27660. this._activeBones.fetchNewFrame();
  27661. this._meshesForIntersections.reset();
  27662. this.resetCachedMaterial();
  27663. this.onBeforeAnimationsObservable.notifyObservers(this);
  27664. // Actions
  27665. if (this.actionManager) {
  27666. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27667. }
  27668. if (this._engine.isDeterministicLockStep()) {
  27669. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27670. var defaultFPS = (60.0 / 1000.0);
  27671. var defaultFrameTime = 1000 / 60; // frame time in MS
  27672. if (this._physicsEngine) {
  27673. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27674. }
  27675. var stepsTaken = 0;
  27676. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27677. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27678. internalSteps = Math.min(internalSteps, maxSubSteps);
  27679. do {
  27680. this.onBeforeStepObservable.notifyObservers(this);
  27681. // Animations
  27682. this._animationRatio = defaultFrameTime * defaultFPS;
  27683. this._animate();
  27684. this.onAfterAnimationsObservable.notifyObservers(this);
  27685. // Physics
  27686. if (this._physicsEngine) {
  27687. this.onBeforePhysicsObservable.notifyObservers(this);
  27688. this._physicsEngine._step(defaultFrameTime / 1000);
  27689. this.onAfterPhysicsObservable.notifyObservers(this);
  27690. }
  27691. this.onAfterStepObservable.notifyObservers(this);
  27692. this._currentStepId++;
  27693. stepsTaken++;
  27694. deltaTime -= defaultFrameTime;
  27695. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27696. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27697. }
  27698. else {
  27699. // Animations
  27700. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27701. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27702. this._animate();
  27703. this.onAfterAnimationsObservable.notifyObservers(this);
  27704. // Physics
  27705. if (this._physicsEngine) {
  27706. this.onBeforePhysicsObservable.notifyObservers(this);
  27707. this._physicsEngine._step(deltaTime / 1000.0);
  27708. this.onAfterPhysicsObservable.notifyObservers(this);
  27709. }
  27710. }
  27711. // Before camera update steps
  27712. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27713. var step = _a[_i];
  27714. step.action();
  27715. }
  27716. // Update Cameras
  27717. if (updateCameras) {
  27718. if (this.activeCameras.length > 0) {
  27719. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27720. var camera = this.activeCameras[cameraIndex];
  27721. camera.update();
  27722. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27723. // rig cameras
  27724. for (var index = 0; index < camera._rigCameras.length; index++) {
  27725. camera._rigCameras[index].update();
  27726. }
  27727. }
  27728. }
  27729. }
  27730. else if (this.activeCamera) {
  27731. this.activeCamera.update();
  27732. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27733. // rig cameras
  27734. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27735. this.activeCamera._rigCameras[index].update();
  27736. }
  27737. }
  27738. }
  27739. }
  27740. // Before render
  27741. this.onBeforeRenderObservable.notifyObservers(this);
  27742. // Customs render targets
  27743. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27744. var engine = this.getEngine();
  27745. var currentActiveCamera = this.activeCamera;
  27746. if (this.renderTargetsEnabled) {
  27747. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27748. this._intermediateRendering = true;
  27749. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27750. var renderTarget = this.customRenderTargets[customIndex];
  27751. if (renderTarget._shouldRender()) {
  27752. this._renderId++;
  27753. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27754. if (!this.activeCamera)
  27755. throw new Error("Active camera not set");
  27756. // Viewport
  27757. engine.setViewport(this.activeCamera.viewport);
  27758. // Camera
  27759. this.updateTransformMatrix();
  27760. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27761. }
  27762. }
  27763. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27764. this._intermediateRendering = false;
  27765. this._renderId++;
  27766. }
  27767. // Restore back buffer
  27768. if (this.customRenderTargets.length > 0) {
  27769. engine.restoreDefaultFramebuffer();
  27770. }
  27771. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27772. this.activeCamera = currentActiveCamera;
  27773. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27774. var step = _c[_b];
  27775. step.action();
  27776. }
  27777. // Clear
  27778. if (this.autoClearDepthAndStencil || this.autoClear) {
  27779. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27780. }
  27781. // Collects render targets from external components.
  27782. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27783. var step = _e[_d];
  27784. step.action(this._renderTargets);
  27785. }
  27786. // Multi-cameras?
  27787. if (this.activeCameras.length > 0) {
  27788. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27789. if (cameraIndex > 0) {
  27790. this._engine.clear(null, false, true, true);
  27791. }
  27792. this._processSubCameras(this.activeCameras[cameraIndex]);
  27793. }
  27794. }
  27795. else {
  27796. if (!this.activeCamera) {
  27797. throw new Error("No camera defined");
  27798. }
  27799. this._processSubCameras(this.activeCamera);
  27800. }
  27801. // Intersection checks
  27802. this._checkIntersections();
  27803. // Update the audio listener attached to the camera
  27804. if (BABYLON.AudioEngine) {
  27805. this._updateAudioParameters();
  27806. }
  27807. // After render
  27808. if (this.afterRender) {
  27809. this.afterRender();
  27810. }
  27811. this.onAfterRenderObservable.notifyObservers(this);
  27812. // Cleaning
  27813. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27814. var data = this._toBeDisposed.data[index];
  27815. if (data) {
  27816. data.dispose();
  27817. }
  27818. }
  27819. this._toBeDisposed.reset();
  27820. if (this.dumpNextRenderTargets) {
  27821. this.dumpNextRenderTargets = false;
  27822. }
  27823. this._activeBones.addCount(0, true);
  27824. this._activeIndices.addCount(0, true);
  27825. this._activeParticles.addCount(0, true);
  27826. };
  27827. Scene.prototype._updateAudioParameters = function () {
  27828. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27829. return;
  27830. }
  27831. var listeningCamera;
  27832. var audioEngine = BABYLON.Engine.audioEngine;
  27833. if (this.activeCameras.length > 0) {
  27834. listeningCamera = this.activeCameras[0];
  27835. }
  27836. else {
  27837. listeningCamera = this.activeCamera;
  27838. }
  27839. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27840. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27841. // for VR cameras
  27842. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27843. listeningCamera = listeningCamera.rigCameras[0];
  27844. }
  27845. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27846. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27847. cameraDirection.normalize();
  27848. // To avoid some errors on GearVR
  27849. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27850. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27851. }
  27852. var i;
  27853. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27854. var sound = this.mainSoundTrack.soundCollection[i];
  27855. if (sound.useCustomAttenuation) {
  27856. sound.updateDistanceFromListener();
  27857. }
  27858. }
  27859. for (i = 0; i < this.soundTracks.length; i++) {
  27860. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27861. sound = this.soundTracks[i].soundCollection[j];
  27862. if (sound.useCustomAttenuation) {
  27863. sound.updateDistanceFromListener();
  27864. }
  27865. }
  27866. }
  27867. }
  27868. };
  27869. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27870. // Audio
  27871. /**
  27872. * Gets or sets if audio support is enabled
  27873. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27874. */
  27875. get: function () {
  27876. return this._audioEnabled;
  27877. },
  27878. set: function (value) {
  27879. this._audioEnabled = value;
  27880. if (BABYLON.AudioEngine) {
  27881. if (this._audioEnabled) {
  27882. this._enableAudio();
  27883. }
  27884. else {
  27885. this._disableAudio();
  27886. }
  27887. }
  27888. },
  27889. enumerable: true,
  27890. configurable: true
  27891. });
  27892. Scene.prototype._disableAudio = function () {
  27893. var i;
  27894. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27895. this.mainSoundTrack.soundCollection[i].pause();
  27896. }
  27897. for (i = 0; i < this.soundTracks.length; i++) {
  27898. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27899. this.soundTracks[i].soundCollection[j].pause();
  27900. }
  27901. }
  27902. };
  27903. Scene.prototype._enableAudio = function () {
  27904. var i;
  27905. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27906. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27907. this.mainSoundTrack.soundCollection[i].play();
  27908. }
  27909. }
  27910. for (i = 0; i < this.soundTracks.length; i++) {
  27911. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27912. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27913. this.soundTracks[i].soundCollection[j].play();
  27914. }
  27915. }
  27916. }
  27917. };
  27918. Object.defineProperty(Scene.prototype, "headphone", {
  27919. /**
  27920. * Gets or sets if audio will be output to headphones
  27921. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27922. */
  27923. get: function () {
  27924. return this._headphone;
  27925. },
  27926. set: function (value) {
  27927. this._headphone = value;
  27928. if (BABYLON.AudioEngine) {
  27929. if (this._headphone) {
  27930. this._switchAudioModeForHeadphones();
  27931. }
  27932. else {
  27933. this._switchAudioModeForNormalSpeakers();
  27934. }
  27935. }
  27936. },
  27937. enumerable: true,
  27938. configurable: true
  27939. });
  27940. Scene.prototype._switchAudioModeForHeadphones = function () {
  27941. this.mainSoundTrack.switchPanningModelToHRTF();
  27942. for (var i = 0; i < this.soundTracks.length; i++) {
  27943. this.soundTracks[i].switchPanningModelToHRTF();
  27944. }
  27945. };
  27946. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27947. this.mainSoundTrack.switchPanningModelToEqualPower();
  27948. for (var i = 0; i < this.soundTracks.length; i++) {
  27949. this.soundTracks[i].switchPanningModelToEqualPower();
  27950. }
  27951. };
  27952. /**
  27953. * Freeze all materials
  27954. * A frozen material will not be updatable but should be faster to render
  27955. */
  27956. Scene.prototype.freezeMaterials = function () {
  27957. for (var i = 0; i < this.materials.length; i++) {
  27958. this.materials[i].freeze();
  27959. }
  27960. };
  27961. /**
  27962. * Unfreeze all materials
  27963. * A frozen material will not be updatable but should be faster to render
  27964. */
  27965. Scene.prototype.unfreezeMaterials = function () {
  27966. for (var i = 0; i < this.materials.length; i++) {
  27967. this.materials[i].unfreeze();
  27968. }
  27969. };
  27970. /**
  27971. * Releases all held ressources
  27972. */
  27973. Scene.prototype.dispose = function () {
  27974. this.beforeRender = null;
  27975. this.afterRender = null;
  27976. this.skeletons = [];
  27977. this.morphTargetManagers = [];
  27978. this._transientComponents = [];
  27979. this._isReadyForMeshStage.clear();
  27980. this._beforeEvaluateActiveMeshStage.clear();
  27981. this._evaluateSubMeshStage.clear();
  27982. this._activeMeshStage.clear();
  27983. this._cameraDrawRenderTargetStage.clear();
  27984. this._beforeCameraDrawStage.clear();
  27985. this._beforeRenderingGroupDrawStage.clear();
  27986. this._beforeRenderingMeshStage.clear();
  27987. this._afterRenderingMeshStage.clear();
  27988. this._afterRenderingGroupDrawStage.clear();
  27989. this._afterCameraDrawStage.clear();
  27990. this._beforeCameraUpdateStage.clear();
  27991. this._beforeClearStage.clear();
  27992. this._gatherRenderTargetsStage.clear();
  27993. this._gatherActiveCameraRenderTargetsStage.clear();
  27994. this._pointerMoveStage.clear();
  27995. this._pointerDownStage.clear();
  27996. this._pointerUpStage.clear();
  27997. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27998. var component = _a[_i];
  27999. component.dispose();
  28000. }
  28001. this.importedMeshesFiles = new Array();
  28002. this.stopAllAnimations();
  28003. this.resetCachedMaterial();
  28004. // Smart arrays
  28005. if (this.activeCamera) {
  28006. this.activeCamera._activeMeshes.dispose();
  28007. this.activeCamera = null;
  28008. }
  28009. this._activeMeshes.dispose();
  28010. this._renderingManager.dispose();
  28011. this._processedMaterials.dispose();
  28012. this._activeParticleSystems.dispose();
  28013. this._activeSkeletons.dispose();
  28014. this._softwareSkinnedMeshes.dispose();
  28015. this._renderTargets.dispose();
  28016. this._registeredForLateAnimationBindings.dispose();
  28017. this._meshesForIntersections.dispose();
  28018. this._toBeDisposed.dispose();
  28019. // Abort active requests
  28020. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28021. var request = _c[_b];
  28022. request.abort();
  28023. }
  28024. // Events
  28025. this.onDisposeObservable.notifyObservers(this);
  28026. this.onDisposeObservable.clear();
  28027. this.onBeforeRenderObservable.clear();
  28028. this.onAfterRenderObservable.clear();
  28029. this.onBeforeRenderTargetsRenderObservable.clear();
  28030. this.onAfterRenderTargetsRenderObservable.clear();
  28031. this.onAfterStepObservable.clear();
  28032. this.onBeforeStepObservable.clear();
  28033. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28034. this.onAfterActiveMeshesEvaluationObservable.clear();
  28035. this.onBeforeParticlesRenderingObservable.clear();
  28036. this.onAfterParticlesRenderingObservable.clear();
  28037. this.onBeforeDrawPhaseObservable.clear();
  28038. this.onAfterDrawPhaseObservable.clear();
  28039. this.onBeforePhysicsObservable.clear();
  28040. this.onAfterPhysicsObservable.clear();
  28041. this.onBeforeAnimationsObservable.clear();
  28042. this.onAfterAnimationsObservable.clear();
  28043. this.onDataLoadedObservable.clear();
  28044. this.onBeforeRenderingGroupObservable.clear();
  28045. this.onAfterRenderingGroupObservable.clear();
  28046. this.onMeshImportedObservable.clear();
  28047. this.detachControl();
  28048. // Release sounds & sounds tracks
  28049. if (BABYLON.AudioEngine) {
  28050. this.disposeSounds();
  28051. }
  28052. // Detach cameras
  28053. var canvas = this._engine.getRenderingCanvas();
  28054. if (canvas) {
  28055. var index;
  28056. for (index = 0; index < this.cameras.length; index++) {
  28057. this.cameras[index].detachControl(canvas);
  28058. }
  28059. }
  28060. // Release animation groups
  28061. while (this.animationGroups.length) {
  28062. this.animationGroups[0].dispose();
  28063. }
  28064. // Release lights
  28065. while (this.lights.length) {
  28066. this.lights[0].dispose();
  28067. }
  28068. // Release meshes
  28069. while (this.meshes.length) {
  28070. this.meshes[0].dispose(true);
  28071. }
  28072. while (this.transformNodes.length) {
  28073. this.removeTransformNode(this.transformNodes[0]);
  28074. }
  28075. // Release cameras
  28076. while (this.cameras.length) {
  28077. this.cameras[0].dispose();
  28078. }
  28079. // Release materials
  28080. if (this.defaultMaterial) {
  28081. this.defaultMaterial.dispose();
  28082. }
  28083. while (this.multiMaterials.length) {
  28084. this.multiMaterials[0].dispose();
  28085. }
  28086. while (this.materials.length) {
  28087. this.materials[0].dispose();
  28088. }
  28089. // Release particles
  28090. while (this.particleSystems.length) {
  28091. this.particleSystems[0].dispose();
  28092. }
  28093. // Release postProcesses
  28094. while (this.postProcesses.length) {
  28095. this.postProcesses[0].dispose();
  28096. }
  28097. // Release textures
  28098. while (this.textures.length) {
  28099. this.textures[0].dispose();
  28100. }
  28101. // Release UBO
  28102. this._sceneUbo.dispose();
  28103. if (this._alternateSceneUbo) {
  28104. this._alternateSceneUbo.dispose();
  28105. }
  28106. // Post-processes
  28107. this.postProcessManager.dispose();
  28108. // Physics
  28109. if (this._physicsEngine) {
  28110. this.disablePhysicsEngine();
  28111. }
  28112. // Remove from engine
  28113. index = this._engine.scenes.indexOf(this);
  28114. if (index > -1) {
  28115. this._engine.scenes.splice(index, 1);
  28116. }
  28117. this._engine.wipeCaches(true);
  28118. this._isDisposed = true;
  28119. };
  28120. Object.defineProperty(Scene.prototype, "isDisposed", {
  28121. /**
  28122. * Gets if the scene is already disposed
  28123. */
  28124. get: function () {
  28125. return this._isDisposed;
  28126. },
  28127. enumerable: true,
  28128. configurable: true
  28129. });
  28130. /**
  28131. * Releases sounds & soundtracks
  28132. */
  28133. Scene.prototype.disposeSounds = function () {
  28134. if (!this._mainSoundTrack) {
  28135. return;
  28136. }
  28137. this.mainSoundTrack.dispose();
  28138. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28139. this.soundTracks[scIndex].dispose();
  28140. }
  28141. };
  28142. /**
  28143. * Call this function to reduce memory footprint of the scene.
  28144. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28145. */
  28146. Scene.prototype.clearCachedVertexData = function () {
  28147. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28148. var mesh = this.meshes[meshIndex];
  28149. var geometry = mesh.geometry;
  28150. if (geometry) {
  28151. geometry._indices = [];
  28152. for (var vbName in geometry._vertexBuffers) {
  28153. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28154. continue;
  28155. }
  28156. geometry._vertexBuffers[vbName]._buffer._data = null;
  28157. }
  28158. }
  28159. }
  28160. };
  28161. /**
  28162. * This function will remove the local cached buffer data from texture.
  28163. * It will save memory but will prevent the texture from being rebuilt
  28164. */
  28165. Scene.prototype.cleanCachedTextureBuffer = function () {
  28166. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28167. var baseTexture = _a[_i];
  28168. var buffer = baseTexture._buffer;
  28169. if (buffer) {
  28170. baseTexture._buffer = null;
  28171. }
  28172. }
  28173. };
  28174. /**
  28175. * Get the world extend vectors with an optional filter
  28176. *
  28177. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28178. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28179. */
  28180. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28181. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28182. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28183. filterPredicate = filterPredicate || (function () { return true; });
  28184. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28185. mesh.computeWorldMatrix(true);
  28186. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28187. return;
  28188. }
  28189. var boundingInfo = mesh.getBoundingInfo();
  28190. var minBox = boundingInfo.boundingBox.minimumWorld;
  28191. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28192. BABYLON.Tools.CheckExtends(minBox, min, max);
  28193. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28194. });
  28195. return {
  28196. min: min,
  28197. max: max
  28198. };
  28199. };
  28200. // Picking
  28201. /**
  28202. * Creates a ray that can be used to pick in the scene
  28203. * @param x defines the x coordinate of the origin (on-screen)
  28204. * @param y defines the y coordinate of the origin (on-screen)
  28205. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28206. * @param camera defines the camera to use for the picking
  28207. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28208. * @returns a Ray
  28209. */
  28210. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28211. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28212. var result = BABYLON.Ray.Zero();
  28213. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28214. return result;
  28215. };
  28216. /**
  28217. * Creates a ray that can be used to pick in the scene
  28218. * @param x defines the x coordinate of the origin (on-screen)
  28219. * @param y defines the y coordinate of the origin (on-screen)
  28220. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28221. * @param result defines the ray where to store the picking ray
  28222. * @param camera defines the camera to use for the picking
  28223. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28224. * @returns the current scene
  28225. */
  28226. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28227. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28228. var engine = this._engine;
  28229. if (!camera) {
  28230. if (!this.activeCamera)
  28231. throw new Error("Active camera not set");
  28232. camera = this.activeCamera;
  28233. }
  28234. var cameraViewport = camera.viewport;
  28235. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28236. // Moving coordinates to local viewport world
  28237. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28238. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28239. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28240. return this;
  28241. };
  28242. /**
  28243. * Creates a ray that can be used to pick in the scene
  28244. * @param x defines the x coordinate of the origin (on-screen)
  28245. * @param y defines the y coordinate of the origin (on-screen)
  28246. * @param camera defines the camera to use for the picking
  28247. * @returns a Ray
  28248. */
  28249. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28250. var result = BABYLON.Ray.Zero();
  28251. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28252. return result;
  28253. };
  28254. /**
  28255. * Creates a ray that can be used to pick in the scene
  28256. * @param x defines the x coordinate of the origin (on-screen)
  28257. * @param y defines the y coordinate of the origin (on-screen)
  28258. * @param result defines the ray where to store the picking ray
  28259. * @param camera defines the camera to use for the picking
  28260. * @returns the current scene
  28261. */
  28262. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28263. if (!BABYLON.PickingInfo) {
  28264. return this;
  28265. }
  28266. var engine = this._engine;
  28267. if (!camera) {
  28268. if (!this.activeCamera)
  28269. throw new Error("Active camera not set");
  28270. camera = this.activeCamera;
  28271. }
  28272. var cameraViewport = camera.viewport;
  28273. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28274. var identity = BABYLON.Matrix.Identity();
  28275. // Moving coordinates to local viewport world
  28276. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28277. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28278. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28279. return this;
  28280. };
  28281. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28282. if (!BABYLON.PickingInfo) {
  28283. return null;
  28284. }
  28285. var pickingInfo = null;
  28286. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28287. var mesh = this.meshes[meshIndex];
  28288. if (predicate) {
  28289. if (!predicate(mesh)) {
  28290. continue;
  28291. }
  28292. }
  28293. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28294. continue;
  28295. }
  28296. var world = mesh.getWorldMatrix();
  28297. var ray = rayFunction(world);
  28298. var result = mesh.intersects(ray, fastCheck);
  28299. if (!result || !result.hit)
  28300. continue;
  28301. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28302. continue;
  28303. pickingInfo = result;
  28304. if (fastCheck) {
  28305. break;
  28306. }
  28307. }
  28308. return pickingInfo || new BABYLON.PickingInfo();
  28309. };
  28310. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28311. if (!BABYLON.PickingInfo) {
  28312. return null;
  28313. }
  28314. var pickingInfos = new Array();
  28315. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28316. var mesh = this.meshes[meshIndex];
  28317. if (predicate) {
  28318. if (!predicate(mesh)) {
  28319. continue;
  28320. }
  28321. }
  28322. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28323. continue;
  28324. }
  28325. var world = mesh.getWorldMatrix();
  28326. var ray = rayFunction(world);
  28327. var result = mesh.intersects(ray, false);
  28328. if (!result || !result.hit)
  28329. continue;
  28330. pickingInfos.push(result);
  28331. }
  28332. return pickingInfos;
  28333. };
  28334. /** Launch a ray to try to pick a mesh in the scene
  28335. * @param x position on screen
  28336. * @param y position on screen
  28337. * @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
  28338. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28339. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28340. * @returns a PickingInfo
  28341. */
  28342. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28343. var _this = this;
  28344. if (!BABYLON.PickingInfo) {
  28345. return null;
  28346. }
  28347. var result = this._internalPick(function (world) {
  28348. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28349. return _this._tempPickingRay;
  28350. }, predicate, fastCheck);
  28351. if (result) {
  28352. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28353. }
  28354. return result;
  28355. };
  28356. /** Use the given ray to pick a mesh in the scene
  28357. * @param ray The ray to use to pick meshes
  28358. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  28359. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28360. * @returns a PickingInfo
  28361. */
  28362. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28363. var _this = this;
  28364. var result = this._internalPick(function (world) {
  28365. if (!_this._pickWithRayInverseMatrix) {
  28366. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28367. }
  28368. world.invertToRef(_this._pickWithRayInverseMatrix);
  28369. if (!_this._cachedRayForTransform) {
  28370. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28371. }
  28372. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28373. return _this._cachedRayForTransform;
  28374. }, predicate, fastCheck);
  28375. if (result) {
  28376. result.ray = ray;
  28377. }
  28378. return result;
  28379. };
  28380. /**
  28381. * Launch a ray to try to pick a mesh in the scene
  28382. * @param x X position on screen
  28383. * @param y Y position on screen
  28384. * @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
  28385. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28386. * @returns an array of PickingInfo
  28387. */
  28388. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28389. var _this = this;
  28390. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28391. };
  28392. /**
  28393. * Launch a ray to try to pick a mesh in the scene
  28394. * @param ray Ray to use
  28395. * @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
  28396. * @returns an array of PickingInfo
  28397. */
  28398. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28399. var _this = this;
  28400. return this._internalMultiPick(function (world) {
  28401. if (!_this._pickWithRayInverseMatrix) {
  28402. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28403. }
  28404. world.invertToRef(_this._pickWithRayInverseMatrix);
  28405. if (!_this._cachedRayForTransform) {
  28406. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28407. }
  28408. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28409. return _this._cachedRayForTransform;
  28410. }, predicate);
  28411. };
  28412. /**
  28413. * Force the value of meshUnderPointer
  28414. * @param mesh defines the mesh to use
  28415. */
  28416. Scene.prototype.setPointerOverMesh = function (mesh) {
  28417. if (this._pointerOverMesh === mesh) {
  28418. return;
  28419. }
  28420. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28421. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28422. }
  28423. this._pointerOverMesh = mesh;
  28424. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28425. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28426. }
  28427. };
  28428. /**
  28429. * Gets the mesh under the pointer
  28430. * @returns a Mesh or null if no mesh is under the pointer
  28431. */
  28432. Scene.prototype.getPointerOverMesh = function () {
  28433. return this._pointerOverMesh;
  28434. };
  28435. // Physics
  28436. /**
  28437. * Gets the current physics engine
  28438. * @returns a PhysicsEngine or null if none attached
  28439. */
  28440. Scene.prototype.getPhysicsEngine = function () {
  28441. return this._physicsEngine;
  28442. };
  28443. /**
  28444. * Enables physics to the current scene
  28445. * @param gravity defines the scene's gravity for the physics engine
  28446. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28447. * @return a boolean indicating if the physics engine was initialized
  28448. */
  28449. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28450. if (gravity === void 0) { gravity = null; }
  28451. if (this._physicsEngine) {
  28452. return true;
  28453. }
  28454. try {
  28455. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28456. return true;
  28457. }
  28458. catch (e) {
  28459. BABYLON.Tools.Error(e.message);
  28460. return false;
  28461. }
  28462. };
  28463. /**
  28464. * Disables and disposes the physics engine associated with the scene
  28465. */
  28466. Scene.prototype.disablePhysicsEngine = function () {
  28467. if (!this._physicsEngine) {
  28468. return;
  28469. }
  28470. this._physicsEngine.dispose();
  28471. this._physicsEngine = null;
  28472. };
  28473. /**
  28474. * Gets a boolean indicating if there is an active physics engine
  28475. * @returns a boolean indicating if there is an active physics engine
  28476. */
  28477. Scene.prototype.isPhysicsEnabled = function () {
  28478. return this._physicsEngine !== undefined;
  28479. };
  28480. /**
  28481. * Deletes a physics compound impostor
  28482. * @param compound defines the compound to delete
  28483. */
  28484. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28485. var mesh = compound.parts[0].mesh;
  28486. if (mesh.physicsImpostor) {
  28487. mesh.physicsImpostor.dispose( /*true*/);
  28488. mesh.physicsImpostor = null;
  28489. }
  28490. };
  28491. // Misc.
  28492. /** @hidden */
  28493. Scene.prototype._rebuildGeometries = function () {
  28494. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28495. var geometry = _a[_i];
  28496. geometry._rebuild();
  28497. }
  28498. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28499. var mesh = _c[_b];
  28500. mesh._rebuild();
  28501. }
  28502. if (this.postProcessManager) {
  28503. this.postProcessManager._rebuild();
  28504. }
  28505. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28506. var component = _e[_d];
  28507. component.rebuild();
  28508. }
  28509. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28510. var system = _g[_f];
  28511. system.rebuild();
  28512. }
  28513. };
  28514. /** @hidden */
  28515. Scene.prototype._rebuildTextures = function () {
  28516. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28517. var texture = _a[_i];
  28518. texture._rebuild();
  28519. }
  28520. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28521. };
  28522. // Tags
  28523. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28524. if (tagsQuery === undefined) {
  28525. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28526. return list;
  28527. }
  28528. var listByTags = [];
  28529. forEach = forEach || (function (item) { return; });
  28530. for (var i in list) {
  28531. var item = list[i];
  28532. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28533. listByTags.push(item);
  28534. forEach(item);
  28535. }
  28536. }
  28537. return listByTags;
  28538. };
  28539. /**
  28540. * Get a list of meshes by tags
  28541. * @param tagsQuery defines the tags query to use
  28542. * @param forEach defines a predicate used to filter results
  28543. * @returns an array of Mesh
  28544. */
  28545. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28546. return this._getByTags(this.meshes, tagsQuery, forEach);
  28547. };
  28548. /**
  28549. * Get a list of cameras by tags
  28550. * @param tagsQuery defines the tags query to use
  28551. * @param forEach defines a predicate used to filter results
  28552. * @returns an array of Camera
  28553. */
  28554. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28555. return this._getByTags(this.cameras, tagsQuery, forEach);
  28556. };
  28557. /**
  28558. * Get a list of lights by tags
  28559. * @param tagsQuery defines the tags query to use
  28560. * @param forEach defines a predicate used to filter results
  28561. * @returns an array of Light
  28562. */
  28563. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28564. return this._getByTags(this.lights, tagsQuery, forEach);
  28565. };
  28566. /**
  28567. * Get a list of materials by tags
  28568. * @param tagsQuery defines the tags query to use
  28569. * @param forEach defines a predicate used to filter results
  28570. * @returns an array of Material
  28571. */
  28572. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28573. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28574. };
  28575. /**
  28576. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28577. * This allowed control for front to back rendering or reversly depending of the special needs.
  28578. *
  28579. * @param renderingGroupId The rendering group id corresponding to its index
  28580. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28581. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28582. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28583. */
  28584. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28585. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28586. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28587. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28588. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28589. };
  28590. /**
  28591. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28592. *
  28593. * @param renderingGroupId The rendering group id corresponding to its index
  28594. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28595. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28596. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28597. */
  28598. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28599. if (depth === void 0) { depth = true; }
  28600. if (stencil === void 0) { stencil = true; }
  28601. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28602. };
  28603. /**
  28604. * Gets the current auto clear configuration for one rendering group of the rendering
  28605. * manager.
  28606. * @param index the rendering group index to get the information for
  28607. * @returns The auto clear setup for the requested rendering group
  28608. */
  28609. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28610. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28611. };
  28612. /**
  28613. * Will flag all materials as dirty to trigger new shader compilation
  28614. * @param flag defines the flag used to specify which material part must be marked as dirty
  28615. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28616. */
  28617. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28618. if (this.blockMaterialDirtyMechanism) {
  28619. return;
  28620. }
  28621. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28622. var material = _a[_i];
  28623. if (predicate && !predicate(material)) {
  28624. continue;
  28625. }
  28626. material.markAsDirty(flag);
  28627. }
  28628. };
  28629. /** @hidden */
  28630. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28631. var _this = this;
  28632. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28633. this._activeRequests.push(request);
  28634. request.onCompleteObservable.add(function (request) {
  28635. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28636. });
  28637. return request;
  28638. };
  28639. /** @hidden */
  28640. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28641. var _this = this;
  28642. return new Promise(function (resolve, reject) {
  28643. _this._loadFile(url, function (data) {
  28644. resolve(data);
  28645. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28646. reject(exception);
  28647. });
  28648. });
  28649. };
  28650. // Statics
  28651. Scene._uniqueIdCounter = 0;
  28652. /** The fog is deactivated */
  28653. Scene.FOGMODE_NONE = 0;
  28654. /** The fog density is following an exponential function */
  28655. Scene.FOGMODE_EXP = 1;
  28656. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28657. Scene.FOGMODE_EXP2 = 2;
  28658. /** The fog density is following a linear function. */
  28659. Scene.FOGMODE_LINEAR = 3;
  28660. /**
  28661. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28662. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28663. */
  28664. Scene.MinDeltaTime = 1.0;
  28665. /**
  28666. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28667. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28668. */
  28669. Scene.MaxDeltaTime = 1000.0;
  28670. /** The distance in pixel that you have to move to prevent some events */
  28671. Scene.DragMovementThreshold = 10; // in pixels
  28672. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28673. Scene.LongPressDelay = 500; // in milliseconds
  28674. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28675. Scene.DoubleClickDelay = 300; // in milliseconds
  28676. /** If you need to check double click without raising a single click at first click, enable this flag */
  28677. Scene.ExclusiveDoubleClickMode = false;
  28678. return Scene;
  28679. }(BABYLON.AbstractScene));
  28680. BABYLON.Scene = Scene;
  28681. })(BABYLON || (BABYLON = {}));
  28682. //# sourceMappingURL=babylon.scene.js.map
  28683. var BABYLON;
  28684. (function (BABYLON) {
  28685. /**
  28686. * Set of assets to keep when moving a scene into an asset container.
  28687. */
  28688. var KeepAssets = /** @class */ (function (_super) {
  28689. __extends(KeepAssets, _super);
  28690. function KeepAssets() {
  28691. return _super !== null && _super.apply(this, arguments) || this;
  28692. }
  28693. return KeepAssets;
  28694. }(BABYLON.AbstractScene));
  28695. BABYLON.KeepAssets = KeepAssets;
  28696. /**
  28697. * Container with a set of assets that can be added or removed from a scene.
  28698. */
  28699. var AssetContainer = /** @class */ (function (_super) {
  28700. __extends(AssetContainer, _super);
  28701. /**
  28702. * Instantiates an AssetContainer.
  28703. * @param scene The scene the AssetContainer belongs to.
  28704. */
  28705. function AssetContainer(scene) {
  28706. var _this = _super.call(this) || this;
  28707. _this.scene = scene;
  28708. return _this;
  28709. }
  28710. /**
  28711. * Adds all the assets from the container to the scene.
  28712. */
  28713. AssetContainer.prototype.addAllToScene = function () {
  28714. var _this = this;
  28715. this.cameras.forEach(function (o) {
  28716. _this.scene.addCamera(o);
  28717. });
  28718. this.lights.forEach(function (o) {
  28719. _this.scene.addLight(o);
  28720. });
  28721. this.meshes.forEach(function (o) {
  28722. _this.scene.addMesh(o);
  28723. });
  28724. this.skeletons.forEach(function (o) {
  28725. _this.scene.addSkeleton(o);
  28726. });
  28727. this.animations.forEach(function (o) {
  28728. _this.scene.addAnimation(o);
  28729. });
  28730. this.animationGroups.forEach(function (o) {
  28731. _this.scene.addAnimationGroup(o);
  28732. });
  28733. this.multiMaterials.forEach(function (o) {
  28734. _this.scene.addMultiMaterial(o);
  28735. });
  28736. this.materials.forEach(function (o) {
  28737. _this.scene.addMaterial(o);
  28738. });
  28739. this.morphTargetManagers.forEach(function (o) {
  28740. _this.scene.addMorphTargetManager(o);
  28741. });
  28742. this.geometries.forEach(function (o) {
  28743. _this.scene.addGeometry(o);
  28744. });
  28745. this.transformNodes.forEach(function (o) {
  28746. _this.scene.addTransformNode(o);
  28747. });
  28748. this.actionManagers.forEach(function (o) {
  28749. _this.scene.addActionManager(o);
  28750. });
  28751. this.sounds.forEach(function (o) {
  28752. o.play();
  28753. o.autoplay = true;
  28754. _this.scene.mainSoundTrack.AddSound(o);
  28755. });
  28756. this.textures.forEach(function (o) {
  28757. _this.scene.addTexture(o);
  28758. });
  28759. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28760. var component = _a[_i];
  28761. component.addFromContainer(this.scene);
  28762. }
  28763. };
  28764. /**
  28765. * Removes all the assets in the container from the scene
  28766. */
  28767. AssetContainer.prototype.removeAllFromScene = function () {
  28768. var _this = this;
  28769. this.cameras.forEach(function (o) {
  28770. _this.scene.removeCamera(o);
  28771. });
  28772. this.lights.forEach(function (o) {
  28773. _this.scene.removeLight(o);
  28774. });
  28775. this.meshes.forEach(function (o) {
  28776. _this.scene.removeMesh(o);
  28777. });
  28778. this.skeletons.forEach(function (o) {
  28779. _this.scene.removeSkeleton(o);
  28780. });
  28781. this.animations.forEach(function (o) {
  28782. _this.scene.removeAnimation(o);
  28783. });
  28784. this.animationGroups.forEach(function (o) {
  28785. _this.scene.removeAnimationGroup(o);
  28786. });
  28787. this.multiMaterials.forEach(function (o) {
  28788. _this.scene.removeMultiMaterial(o);
  28789. });
  28790. this.materials.forEach(function (o) {
  28791. _this.scene.removeMaterial(o);
  28792. });
  28793. this.morphTargetManagers.forEach(function (o) {
  28794. _this.scene.removeMorphTargetManager(o);
  28795. });
  28796. this.geometries.forEach(function (o) {
  28797. _this.scene.removeGeometry(o);
  28798. });
  28799. this.transformNodes.forEach(function (o) {
  28800. _this.scene.removeTransformNode(o);
  28801. });
  28802. this.actionManagers.forEach(function (o) {
  28803. _this.scene.removeActionManager(o);
  28804. });
  28805. this.sounds.forEach(function (o) {
  28806. o.stop();
  28807. o.autoplay = false;
  28808. _this.scene.mainSoundTrack.RemoveSound(o);
  28809. });
  28810. this.textures.forEach(function (o) {
  28811. _this.scene.removeTexture(o);
  28812. });
  28813. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28814. var component = _a[_i];
  28815. component.removeFromContainer(this.scene);
  28816. }
  28817. };
  28818. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28819. if (!sourceAssets) {
  28820. return;
  28821. }
  28822. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28823. var asset = sourceAssets_1[_i];
  28824. var move = true;
  28825. if (keepAssets) {
  28826. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28827. var keepAsset = keepAssets_1[_a];
  28828. if (asset === keepAsset) {
  28829. move = false;
  28830. break;
  28831. }
  28832. }
  28833. }
  28834. if (move) {
  28835. targetAssets.push(asset);
  28836. }
  28837. }
  28838. };
  28839. /**
  28840. * Removes all the assets contained in the scene and adds them to the container.
  28841. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28842. */
  28843. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28844. if (keepAssets === undefined) {
  28845. keepAssets = new KeepAssets();
  28846. }
  28847. for (var key in this) {
  28848. if (this.hasOwnProperty(key)) {
  28849. this[key] = this[key] || [];
  28850. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28851. }
  28852. }
  28853. this.removeAllFromScene();
  28854. };
  28855. /**
  28856. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  28857. * @returns the root mesh
  28858. */
  28859. AssetContainer.prototype.createRootMesh = function () {
  28860. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28861. this.meshes.forEach(function (m) {
  28862. if (!m.parent) {
  28863. rootMesh.addChild(m);
  28864. }
  28865. });
  28866. this.meshes.unshift(rootMesh);
  28867. return rootMesh;
  28868. };
  28869. return AssetContainer;
  28870. }(BABYLON.AbstractScene));
  28871. BABYLON.AssetContainer = AssetContainer;
  28872. })(BABYLON || (BABYLON = {}));
  28873. //# sourceMappingURL=babylon.assetContainer.js.map
  28874. var BABYLON;
  28875. (function (BABYLON) {
  28876. var Buffer = /** @class */ (function () {
  28877. /**
  28878. * Constructor
  28879. * @param engine the engine
  28880. * @param data the data to use for this buffer
  28881. * @param updatable whether the data is updatable
  28882. * @param stride the stride (optional)
  28883. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28884. * @param instanced whether the buffer is instanced (optional)
  28885. * @param useBytes set to true if the stride in in bytes (optional)
  28886. */
  28887. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28888. if (stride === void 0) { stride = 0; }
  28889. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28890. if (instanced === void 0) { instanced = false; }
  28891. if (useBytes === void 0) { useBytes = false; }
  28892. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28893. this._engine = engine.getScene().getEngine();
  28894. }
  28895. else {
  28896. this._engine = engine;
  28897. }
  28898. this._updatable = updatable;
  28899. this._instanced = instanced;
  28900. this._data = data;
  28901. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28902. if (!postponeInternalCreation) { // by default
  28903. this.create();
  28904. }
  28905. }
  28906. /**
  28907. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28908. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28909. * @param offset defines offset in the buffer (0 by default)
  28910. * @param size defines the size in floats of attributes (position is 3 for instance)
  28911. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28912. * @param instanced defines if the vertex buffer contains indexed data
  28913. * @param useBytes defines if the offset and stride are in bytes
  28914. * @returns the new vertex buffer
  28915. */
  28916. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28917. if (useBytes === void 0) { useBytes = false; }
  28918. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28919. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28920. // a lot of these parameters are ignored as they are overriden by the buffer
  28921. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28922. };
  28923. // Properties
  28924. Buffer.prototype.isUpdatable = function () {
  28925. return this._updatable;
  28926. };
  28927. Buffer.prototype.getData = function () {
  28928. return this._data;
  28929. };
  28930. Buffer.prototype.getBuffer = function () {
  28931. return this._buffer;
  28932. };
  28933. /**
  28934. * Gets the stride in float32 units (i.e. byte stride / 4).
  28935. * May not be an integer if the byte stride is not divisible by 4.
  28936. * DEPRECATED. Use byteStride instead.
  28937. * @returns the stride in float32 units
  28938. */
  28939. Buffer.prototype.getStrideSize = function () {
  28940. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28941. };
  28942. // Methods
  28943. Buffer.prototype.create = function (data) {
  28944. if (data === void 0) { data = null; }
  28945. if (!data && this._buffer) {
  28946. return; // nothing to do
  28947. }
  28948. data = data || this._data;
  28949. if (!data) {
  28950. return;
  28951. }
  28952. if (!this._buffer) { // create buffer
  28953. if (this._updatable) {
  28954. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28955. this._data = data;
  28956. }
  28957. else {
  28958. this._buffer = this._engine.createVertexBuffer(data);
  28959. }
  28960. }
  28961. else if (this._updatable) { // update buffer
  28962. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28963. this._data = data;
  28964. }
  28965. };
  28966. /** @hidden */
  28967. Buffer.prototype._rebuild = function () {
  28968. this._buffer = null;
  28969. this.create(this._data);
  28970. };
  28971. Buffer.prototype.update = function (data) {
  28972. this.create(data);
  28973. };
  28974. /**
  28975. * Updates the data directly.
  28976. * @param data the new data
  28977. * @param offset the new offset
  28978. * @param vertexCount the vertex count (optional)
  28979. * @param useBytes set to true if the offset is in bytes
  28980. */
  28981. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28982. if (useBytes === void 0) { useBytes = false; }
  28983. if (!this._buffer) {
  28984. return;
  28985. }
  28986. if (this._updatable) { // update buffer
  28987. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28988. this._data = null;
  28989. }
  28990. };
  28991. Buffer.prototype.dispose = function () {
  28992. if (!this._buffer) {
  28993. return;
  28994. }
  28995. if (this._engine._releaseBuffer(this._buffer)) {
  28996. this._buffer = null;
  28997. }
  28998. };
  28999. return Buffer;
  29000. }());
  29001. BABYLON.Buffer = Buffer;
  29002. })(BABYLON || (BABYLON = {}));
  29003. //# sourceMappingURL=babylon.buffer.js.map
  29004. var BABYLON;
  29005. (function (BABYLON) {
  29006. var VertexBuffer = /** @class */ (function () {
  29007. /**
  29008. * Constructor
  29009. * @param engine the engine
  29010. * @param data the data to use for this vertex buffer
  29011. * @param kind the vertex buffer kind
  29012. * @param updatable whether the data is updatable
  29013. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29014. * @param stride the stride (optional)
  29015. * @param instanced whether the buffer is instanced (optional)
  29016. * @param offset the offset of the data (optional)
  29017. * @param size the number of components (optional)
  29018. * @param type the type of the component (optional)
  29019. * @param normalized whether the data contains normalized data (optional)
  29020. * @param useBytes set to true if stride and offset are in bytes (optional)
  29021. */
  29022. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29023. if (normalized === void 0) { normalized = false; }
  29024. if (useBytes === void 0) { useBytes = false; }
  29025. if (data instanceof BABYLON.Buffer) {
  29026. this._buffer = data;
  29027. this._ownsBuffer = false;
  29028. }
  29029. else {
  29030. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29031. this._ownsBuffer = true;
  29032. }
  29033. this._kind = kind;
  29034. if (type == undefined) {
  29035. var data_1 = this.getData();
  29036. this.type = VertexBuffer.FLOAT;
  29037. if (data_1 instanceof Int8Array)
  29038. this.type = VertexBuffer.BYTE;
  29039. else if (data_1 instanceof Uint8Array)
  29040. this.type = VertexBuffer.UNSIGNED_BYTE;
  29041. else if (data_1 instanceof Int16Array)
  29042. this.type = VertexBuffer.SHORT;
  29043. else if (data_1 instanceof Uint16Array)
  29044. this.type = VertexBuffer.UNSIGNED_SHORT;
  29045. else if (data_1 instanceof Int32Array)
  29046. this.type = VertexBuffer.INT;
  29047. else if (data_1 instanceof Uint32Array)
  29048. this.type = VertexBuffer.UNSIGNED_INT;
  29049. }
  29050. else {
  29051. this.type = type;
  29052. }
  29053. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29054. if (useBytes) {
  29055. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29056. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29057. this.byteOffset = offset || 0;
  29058. }
  29059. else {
  29060. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29061. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29062. this.byteOffset = (offset || 0) * typeByteLength;
  29063. }
  29064. this.normalized = normalized;
  29065. this._instanced = instanced !== undefined ? instanced : false;
  29066. this._instanceDivisor = instanced ? 1 : 0;
  29067. }
  29068. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29069. /**
  29070. * Gets or sets the instance divisor when in instanced mode
  29071. */
  29072. get: function () {
  29073. return this._instanceDivisor;
  29074. },
  29075. set: function (value) {
  29076. this._instanceDivisor = value;
  29077. if (value == 0) {
  29078. this._instanced = false;
  29079. }
  29080. else {
  29081. this._instanced = true;
  29082. }
  29083. },
  29084. enumerable: true,
  29085. configurable: true
  29086. });
  29087. /** @hidden */
  29088. VertexBuffer.prototype._rebuild = function () {
  29089. if (!this._buffer) {
  29090. return;
  29091. }
  29092. this._buffer._rebuild();
  29093. };
  29094. /**
  29095. * Returns the kind of the VertexBuffer (string).
  29096. */
  29097. VertexBuffer.prototype.getKind = function () {
  29098. return this._kind;
  29099. };
  29100. // Properties
  29101. /**
  29102. * Boolean : is the VertexBuffer updatable ?
  29103. */
  29104. VertexBuffer.prototype.isUpdatable = function () {
  29105. return this._buffer.isUpdatable();
  29106. };
  29107. /**
  29108. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29109. */
  29110. VertexBuffer.prototype.getData = function () {
  29111. return this._buffer.getData();
  29112. };
  29113. /**
  29114. * Returns the WebGLBuffer associated to the VertexBuffer.
  29115. */
  29116. VertexBuffer.prototype.getBuffer = function () {
  29117. return this._buffer.getBuffer();
  29118. };
  29119. /**
  29120. * Returns the stride as a multiple of the type byte length.
  29121. * DEPRECATED. Use byteStride instead.
  29122. */
  29123. VertexBuffer.prototype.getStrideSize = function () {
  29124. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29125. };
  29126. /**
  29127. * Returns the offset as a multiple of the type byte length.
  29128. * DEPRECATED. Use byteOffset instead.
  29129. */
  29130. VertexBuffer.prototype.getOffset = function () {
  29131. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29132. };
  29133. /**
  29134. * Returns the number of components per vertex attribute (integer).
  29135. */
  29136. VertexBuffer.prototype.getSize = function () {
  29137. return this._size;
  29138. };
  29139. /**
  29140. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29141. */
  29142. VertexBuffer.prototype.getIsInstanced = function () {
  29143. return this._instanced;
  29144. };
  29145. /**
  29146. * Returns the instancing divisor, zero for non-instanced (integer).
  29147. */
  29148. VertexBuffer.prototype.getInstanceDivisor = function () {
  29149. return this._instanceDivisor;
  29150. };
  29151. // Methods
  29152. /**
  29153. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29154. * Returns the created WebGLBuffer.
  29155. */
  29156. VertexBuffer.prototype.create = function (data) {
  29157. return this._buffer.create(data);
  29158. };
  29159. /**
  29160. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29161. * This function will create a new buffer if the current one is not updatable
  29162. * Returns the updated WebGLBuffer.
  29163. */
  29164. VertexBuffer.prototype.update = function (data) {
  29165. return this._buffer.update(data);
  29166. };
  29167. /**
  29168. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29169. * Returns the directly updated WebGLBuffer.
  29170. * @param data the new data
  29171. * @param offset the new offset
  29172. * @param useBytes set to true if the offset is in bytes
  29173. */
  29174. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29175. if (useBytes === void 0) { useBytes = false; }
  29176. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29177. };
  29178. /**
  29179. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29180. */
  29181. VertexBuffer.prototype.dispose = function () {
  29182. if (this._ownsBuffer) {
  29183. this._buffer.dispose();
  29184. }
  29185. };
  29186. /**
  29187. * Enumerates each value of this vertex buffer as numbers.
  29188. * @param count the number of values to enumerate
  29189. * @param callback the callback function called for each value
  29190. */
  29191. VertexBuffer.prototype.forEach = function (count, callback) {
  29192. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29193. };
  29194. Object.defineProperty(VertexBuffer, "PositionKind", {
  29195. get: function () {
  29196. return VertexBuffer._PositionKind;
  29197. },
  29198. enumerable: true,
  29199. configurable: true
  29200. });
  29201. Object.defineProperty(VertexBuffer, "NormalKind", {
  29202. get: function () {
  29203. return VertexBuffer._NormalKind;
  29204. },
  29205. enumerable: true,
  29206. configurable: true
  29207. });
  29208. Object.defineProperty(VertexBuffer, "TangentKind", {
  29209. get: function () {
  29210. return VertexBuffer._TangentKind;
  29211. },
  29212. enumerable: true,
  29213. configurable: true
  29214. });
  29215. Object.defineProperty(VertexBuffer, "UVKind", {
  29216. get: function () {
  29217. return VertexBuffer._UVKind;
  29218. },
  29219. enumerable: true,
  29220. configurable: true
  29221. });
  29222. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29223. get: function () {
  29224. return VertexBuffer._UV2Kind;
  29225. },
  29226. enumerable: true,
  29227. configurable: true
  29228. });
  29229. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29230. get: function () {
  29231. return VertexBuffer._UV3Kind;
  29232. },
  29233. enumerable: true,
  29234. configurable: true
  29235. });
  29236. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29237. get: function () {
  29238. return VertexBuffer._UV4Kind;
  29239. },
  29240. enumerable: true,
  29241. configurable: true
  29242. });
  29243. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29244. get: function () {
  29245. return VertexBuffer._UV5Kind;
  29246. },
  29247. enumerable: true,
  29248. configurable: true
  29249. });
  29250. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29251. get: function () {
  29252. return VertexBuffer._UV6Kind;
  29253. },
  29254. enumerable: true,
  29255. configurable: true
  29256. });
  29257. Object.defineProperty(VertexBuffer, "ColorKind", {
  29258. get: function () {
  29259. return VertexBuffer._ColorKind;
  29260. },
  29261. enumerable: true,
  29262. configurable: true
  29263. });
  29264. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29265. get: function () {
  29266. return VertexBuffer._MatricesIndicesKind;
  29267. },
  29268. enumerable: true,
  29269. configurable: true
  29270. });
  29271. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29272. get: function () {
  29273. return VertexBuffer._MatricesWeightsKind;
  29274. },
  29275. enumerable: true,
  29276. configurable: true
  29277. });
  29278. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29279. get: function () {
  29280. return VertexBuffer._MatricesIndicesExtraKind;
  29281. },
  29282. enumerable: true,
  29283. configurable: true
  29284. });
  29285. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29286. get: function () {
  29287. return VertexBuffer._MatricesWeightsExtraKind;
  29288. },
  29289. enumerable: true,
  29290. configurable: true
  29291. });
  29292. /**
  29293. * Deduces the stride given a kind.
  29294. * @param kind The kind string to deduce
  29295. * @returns The deduced stride
  29296. */
  29297. VertexBuffer.DeduceStride = function (kind) {
  29298. switch (kind) {
  29299. case VertexBuffer.UVKind:
  29300. case VertexBuffer.UV2Kind:
  29301. case VertexBuffer.UV3Kind:
  29302. case VertexBuffer.UV4Kind:
  29303. case VertexBuffer.UV5Kind:
  29304. case VertexBuffer.UV6Kind:
  29305. return 2;
  29306. case VertexBuffer.NormalKind:
  29307. case VertexBuffer.PositionKind:
  29308. return 3;
  29309. case VertexBuffer.ColorKind:
  29310. case VertexBuffer.MatricesIndicesKind:
  29311. case VertexBuffer.MatricesIndicesExtraKind:
  29312. case VertexBuffer.MatricesWeightsKind:
  29313. case VertexBuffer.MatricesWeightsExtraKind:
  29314. case VertexBuffer.TangentKind:
  29315. return 4;
  29316. default:
  29317. throw new Error("Invalid kind '" + kind + "'");
  29318. }
  29319. };
  29320. /**
  29321. * Gets the byte length of the given type.
  29322. * @param type the type
  29323. * @returns the number of bytes
  29324. */
  29325. VertexBuffer.GetTypeByteLength = function (type) {
  29326. switch (type) {
  29327. case VertexBuffer.BYTE:
  29328. case VertexBuffer.UNSIGNED_BYTE:
  29329. return 1;
  29330. case VertexBuffer.SHORT:
  29331. case VertexBuffer.UNSIGNED_SHORT:
  29332. return 2;
  29333. case VertexBuffer.INT:
  29334. case VertexBuffer.FLOAT:
  29335. return 4;
  29336. default:
  29337. throw new Error("Invalid type '" + type + "'");
  29338. }
  29339. };
  29340. /**
  29341. * Enumerates each value of the given parameters as numbers.
  29342. * @param data the data to enumerate
  29343. * @param byteOffset the byte offset of the data
  29344. * @param byteStride the byte stride of the data
  29345. * @param componentCount the number of components per element
  29346. * @param componentType the type of the component
  29347. * @param count the total number of components
  29348. * @param normalized whether the data is normalized
  29349. * @param callback the callback function called for each value
  29350. */
  29351. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29352. if (data instanceof Array) {
  29353. var offset = byteOffset / 4;
  29354. var stride = byteStride / 4;
  29355. for (var index = 0; index < count; index += componentCount) {
  29356. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29357. callback(data[offset + componentIndex], index + componentIndex);
  29358. }
  29359. offset += stride;
  29360. }
  29361. }
  29362. else {
  29363. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29364. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29365. for (var index = 0; index < count; index += componentCount) {
  29366. var componentByteOffset = byteOffset;
  29367. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29368. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29369. callback(value, index + componentIndex);
  29370. componentByteOffset += componentByteLength;
  29371. }
  29372. byteOffset += byteStride;
  29373. }
  29374. }
  29375. };
  29376. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29377. switch (type) {
  29378. case VertexBuffer.BYTE: {
  29379. var value = dataView.getInt8(byteOffset);
  29380. if (normalized) {
  29381. value = Math.max(value / 127, -1);
  29382. }
  29383. return value;
  29384. }
  29385. case VertexBuffer.UNSIGNED_BYTE: {
  29386. var value = dataView.getUint8(byteOffset);
  29387. if (normalized) {
  29388. value = value / 255;
  29389. }
  29390. return value;
  29391. }
  29392. case VertexBuffer.SHORT: {
  29393. var value = dataView.getInt16(byteOffset, true);
  29394. if (normalized) {
  29395. value = Math.max(value / 16383, -1);
  29396. }
  29397. return value;
  29398. }
  29399. case VertexBuffer.UNSIGNED_SHORT: {
  29400. var value = dataView.getUint16(byteOffset, true);
  29401. if (normalized) {
  29402. value = value / 65535;
  29403. }
  29404. return value;
  29405. }
  29406. case VertexBuffer.FLOAT: {
  29407. return dataView.getFloat32(byteOffset, true);
  29408. }
  29409. default: {
  29410. throw new Error("Invalid component type " + type);
  29411. }
  29412. }
  29413. };
  29414. /**
  29415. * The byte type.
  29416. */
  29417. VertexBuffer.BYTE = 5120;
  29418. /**
  29419. * The unsigned byte type.
  29420. */
  29421. VertexBuffer.UNSIGNED_BYTE = 5121;
  29422. /**
  29423. * The short type.
  29424. */
  29425. VertexBuffer.SHORT = 5122;
  29426. /**
  29427. * The unsigned short type.
  29428. */
  29429. VertexBuffer.UNSIGNED_SHORT = 5123;
  29430. /**
  29431. * The integer type.
  29432. */
  29433. VertexBuffer.INT = 5124;
  29434. /**
  29435. * The unsigned integer type.
  29436. */
  29437. VertexBuffer.UNSIGNED_INT = 5125;
  29438. /**
  29439. * The float type.
  29440. */
  29441. VertexBuffer.FLOAT = 5126;
  29442. // Enums
  29443. VertexBuffer._PositionKind = "position";
  29444. VertexBuffer._NormalKind = "normal";
  29445. VertexBuffer._TangentKind = "tangent";
  29446. VertexBuffer._UVKind = "uv";
  29447. VertexBuffer._UV2Kind = "uv2";
  29448. VertexBuffer._UV3Kind = "uv3";
  29449. VertexBuffer._UV4Kind = "uv4";
  29450. VertexBuffer._UV5Kind = "uv5";
  29451. VertexBuffer._UV6Kind = "uv6";
  29452. VertexBuffer._ColorKind = "color";
  29453. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29454. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29455. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29456. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29457. return VertexBuffer;
  29458. }());
  29459. BABYLON.VertexBuffer = VertexBuffer;
  29460. })(BABYLON || (BABYLON = {}));
  29461. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29462. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29463. var BABYLON;
  29464. (function (BABYLON) {
  29465. /**
  29466. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29467. */
  29468. var DummyInternalTextureTracker = /** @class */ (function () {
  29469. function DummyInternalTextureTracker() {
  29470. /**
  29471. * Gets or set the previous tracker in the list
  29472. */
  29473. this.previous = null;
  29474. /**
  29475. * Gets or set the next tracker in the list
  29476. */
  29477. this.next = null;
  29478. }
  29479. return DummyInternalTextureTracker;
  29480. }());
  29481. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29482. })(BABYLON || (BABYLON = {}));
  29483. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29484. var BABYLON;
  29485. (function (BABYLON) {
  29486. /**
  29487. * Class used to store data associated with WebGL texture data for the engine
  29488. * This class should not be used directly
  29489. */
  29490. var InternalTexture = /** @class */ (function () {
  29491. /**
  29492. * Creates a new InternalTexture
  29493. * @param engine defines the engine to use
  29494. * @param dataSource defines the type of data that will be used
  29495. */
  29496. function InternalTexture(engine, dataSource) {
  29497. /**
  29498. * Observable called when the texture is loaded
  29499. */
  29500. this.onLoadedObservable = new BABYLON.Observable();
  29501. /**
  29502. * Gets or set the previous tracker in the list
  29503. */
  29504. this.previous = null;
  29505. /**
  29506. * Gets or set the next tracker in the list
  29507. */
  29508. this.next = null;
  29509. // Private
  29510. /** @hidden */
  29511. this._initialSlot = -1;
  29512. /** @hidden */
  29513. this._designatedSlot = -1;
  29514. /** @hidden */
  29515. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29516. /** @hidden */
  29517. this._comparisonFunction = 0;
  29518. /** @hidden */
  29519. this._sphericalPolynomial = null;
  29520. /** @hidden */
  29521. this._lodGenerationScale = 0;
  29522. /** @hidden */
  29523. this._lodGenerationOffset = 0;
  29524. /** @hidden */
  29525. this._isRGBD = false;
  29526. /** @hidden */
  29527. this._references = 1;
  29528. this._engine = engine;
  29529. this._dataSource = dataSource;
  29530. this._webGLTexture = engine._createTexture();
  29531. }
  29532. /**
  29533. * Gets the Engine the texture belongs to.
  29534. * @returns The babylon engine
  29535. */
  29536. InternalTexture.prototype.getEngine = function () {
  29537. return this._engine;
  29538. };
  29539. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29540. /**
  29541. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29542. */
  29543. get: function () {
  29544. return this._dataSource;
  29545. },
  29546. enumerable: true,
  29547. configurable: true
  29548. });
  29549. /**
  29550. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29551. */
  29552. InternalTexture.prototype.incrementReferences = function () {
  29553. this._references++;
  29554. };
  29555. /**
  29556. * Change the size of the texture (not the size of the content)
  29557. * @param width defines the new width
  29558. * @param height defines the new height
  29559. * @param depth defines the new depth (1 by default)
  29560. */
  29561. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29562. if (depth === void 0) { depth = 1; }
  29563. this.width = width;
  29564. this.height = height;
  29565. this.depth = depth;
  29566. this.baseWidth = width;
  29567. this.baseHeight = height;
  29568. this.baseDepth = depth;
  29569. this._size = width * height * depth;
  29570. };
  29571. /** @hidden */
  29572. InternalTexture.prototype._rebuild = function () {
  29573. var _this = this;
  29574. var proxy;
  29575. this.isReady = false;
  29576. this._cachedCoordinatesMode = null;
  29577. this._cachedWrapU = null;
  29578. this._cachedWrapV = null;
  29579. this._cachedAnisotropicFilteringLevel = null;
  29580. switch (this._dataSource) {
  29581. case InternalTexture.DATASOURCE_TEMP:
  29582. return;
  29583. case InternalTexture.DATASOURCE_URL:
  29584. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29585. _this.isReady = true;
  29586. }, null, this._buffer, undefined, this.format);
  29587. proxy._swapAndDie(this);
  29588. return;
  29589. case InternalTexture.DATASOURCE_RAW:
  29590. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29591. proxy._swapAndDie(this);
  29592. this.isReady = true;
  29593. return;
  29594. case InternalTexture.DATASOURCE_RAW3D:
  29595. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29596. proxy._swapAndDie(this);
  29597. this.isReady = true;
  29598. return;
  29599. case InternalTexture.DATASOURCE_DYNAMIC:
  29600. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29601. proxy._swapAndDie(this);
  29602. // The engine will make sure to update content so no need to flag it as isReady = true
  29603. return;
  29604. case InternalTexture.DATASOURCE_RENDERTARGET:
  29605. var options = new BABYLON.RenderTargetCreationOptions();
  29606. options.generateDepthBuffer = this._generateDepthBuffer;
  29607. options.generateMipMaps = this.generateMipMaps;
  29608. options.generateStencilBuffer = this._generateStencilBuffer;
  29609. options.samplingMode = this.samplingMode;
  29610. options.type = this.type;
  29611. if (this.isCube) {
  29612. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29613. }
  29614. else {
  29615. var size = {
  29616. width: this.width,
  29617. height: this.height
  29618. };
  29619. proxy = this._engine.createRenderTargetTexture(size, options);
  29620. }
  29621. proxy._swapAndDie(this);
  29622. this.isReady = true;
  29623. return;
  29624. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29625. var depthTextureOptions = {
  29626. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29627. comparisonFunction: this._comparisonFunction,
  29628. generateStencil: this._generateStencilBuffer,
  29629. isCube: this.isCube
  29630. };
  29631. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29632. proxy._swapAndDie(this);
  29633. this.isReady = true;
  29634. return;
  29635. case InternalTexture.DATASOURCE_CUBE:
  29636. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29637. _this.isReady = true;
  29638. }, null, this.format, this._extension);
  29639. proxy._swapAndDie(this);
  29640. return;
  29641. case InternalTexture.DATASOURCE_CUBERAW:
  29642. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29643. proxy._swapAndDie(this);
  29644. this.isReady = true;
  29645. return;
  29646. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29647. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29648. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29649. _this.isReady = true;
  29650. });
  29651. proxy._swapAndDie(this);
  29652. return;
  29653. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29654. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29655. if (proxy) {
  29656. proxy._swapAndDie(_this);
  29657. }
  29658. _this.isReady = true;
  29659. }, null, this.format, this._extension);
  29660. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29661. return;
  29662. }
  29663. };
  29664. /** @hidden */
  29665. InternalTexture.prototype._swapAndDie = function (target) {
  29666. target._webGLTexture = this._webGLTexture;
  29667. if (this._framebuffer) {
  29668. target._framebuffer = this._framebuffer;
  29669. }
  29670. if (this._depthStencilBuffer) {
  29671. target._depthStencilBuffer = this._depthStencilBuffer;
  29672. }
  29673. if (this._lodTextureHigh) {
  29674. if (target._lodTextureHigh) {
  29675. target._lodTextureHigh.dispose();
  29676. }
  29677. target._lodTextureHigh = this._lodTextureHigh;
  29678. }
  29679. if (this._lodTextureMid) {
  29680. if (target._lodTextureMid) {
  29681. target._lodTextureMid.dispose();
  29682. }
  29683. target._lodTextureMid = this._lodTextureMid;
  29684. }
  29685. if (this._lodTextureLow) {
  29686. if (target._lodTextureLow) {
  29687. target._lodTextureLow.dispose();
  29688. }
  29689. target._lodTextureLow = this._lodTextureLow;
  29690. }
  29691. var cache = this._engine.getLoadedTexturesCache();
  29692. var index = cache.indexOf(this);
  29693. if (index !== -1) {
  29694. cache.splice(index, 1);
  29695. }
  29696. };
  29697. /**
  29698. * Dispose the current allocated resources
  29699. */
  29700. InternalTexture.prototype.dispose = function () {
  29701. if (!this._webGLTexture) {
  29702. return;
  29703. }
  29704. this._references--;
  29705. if (this._references === 0) {
  29706. this._engine._releaseTexture(this);
  29707. this._webGLTexture = null;
  29708. this.previous = null;
  29709. this.next = null;
  29710. }
  29711. };
  29712. /**
  29713. * The source of the texture data is unknown
  29714. */
  29715. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29716. /**
  29717. * Texture data comes from an URL
  29718. */
  29719. InternalTexture.DATASOURCE_URL = 1;
  29720. /**
  29721. * Texture data is only used for temporary storage
  29722. */
  29723. InternalTexture.DATASOURCE_TEMP = 2;
  29724. /**
  29725. * Texture data comes from raw data (ArrayBuffer)
  29726. */
  29727. InternalTexture.DATASOURCE_RAW = 3;
  29728. /**
  29729. * Texture content is dynamic (video or dynamic texture)
  29730. */
  29731. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29732. /**
  29733. * Texture content is generated by rendering to it
  29734. */
  29735. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29736. /**
  29737. * Texture content is part of a multi render target process
  29738. */
  29739. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29740. /**
  29741. * Texture data comes from a cube data file
  29742. */
  29743. InternalTexture.DATASOURCE_CUBE = 7;
  29744. /**
  29745. * Texture data comes from a raw cube data
  29746. */
  29747. InternalTexture.DATASOURCE_CUBERAW = 8;
  29748. /**
  29749. * Texture data come from a prefiltered cube data file
  29750. */
  29751. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29752. /**
  29753. * Texture content is raw 3D data
  29754. */
  29755. InternalTexture.DATASOURCE_RAW3D = 10;
  29756. /**
  29757. * Texture content is a depth texture
  29758. */
  29759. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29760. /**
  29761. * Texture data comes from a raw cube data encoded with RGBD
  29762. */
  29763. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29764. return InternalTexture;
  29765. }());
  29766. BABYLON.InternalTexture = InternalTexture;
  29767. })(BABYLON || (BABYLON = {}));
  29768. //# sourceMappingURL=babylon.internalTexture.js.map
  29769. var BABYLON;
  29770. (function (BABYLON) {
  29771. var BaseTexture = /** @class */ (function () {
  29772. function BaseTexture(scene) {
  29773. this._hasAlpha = false;
  29774. this.getAlphaFromRGB = false;
  29775. this.level = 1;
  29776. this.coordinatesIndex = 0;
  29777. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29778. /**
  29779. * | Value | Type | Description |
  29780. * | ----- | ------------------ | ----------- |
  29781. * | 0 | CLAMP_ADDRESSMODE | |
  29782. * | 1 | WRAP_ADDRESSMODE | |
  29783. * | 2 | MIRROR_ADDRESSMODE | |
  29784. */
  29785. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29786. /**
  29787. * | Value | Type | Description |
  29788. * | ----- | ------------------ | ----------- |
  29789. * | 0 | CLAMP_ADDRESSMODE | |
  29790. * | 1 | WRAP_ADDRESSMODE | |
  29791. * | 2 | MIRROR_ADDRESSMODE | |
  29792. */
  29793. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29794. /**
  29795. * | Value | Type | Description |
  29796. * | ----- | ------------------ | ----------- |
  29797. * | 0 | CLAMP_ADDRESSMODE | |
  29798. * | 1 | WRAP_ADDRESSMODE | |
  29799. * | 2 | MIRROR_ADDRESSMODE | |
  29800. */
  29801. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29802. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29803. this.isCube = false;
  29804. this.is3D = false;
  29805. this.gammaSpace = true;
  29806. this.invertZ = false;
  29807. this.lodLevelInAlpha = false;
  29808. this.isRenderTarget = false;
  29809. this.animations = new Array();
  29810. /**
  29811. * An event triggered when the texture is disposed.
  29812. */
  29813. this.onDisposeObservable = new BABYLON.Observable();
  29814. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29815. this._cachedSize = BABYLON.Size.Zero();
  29816. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29817. if (this._scene) {
  29818. this._scene.textures.push(this);
  29819. }
  29820. this._uid = null;
  29821. }
  29822. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29823. get: function () {
  29824. return this._hasAlpha;
  29825. },
  29826. set: function (value) {
  29827. if (this._hasAlpha === value) {
  29828. return;
  29829. }
  29830. this._hasAlpha = value;
  29831. if (this._scene) {
  29832. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29833. }
  29834. },
  29835. enumerable: true,
  29836. configurable: true
  29837. });
  29838. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29839. get: function () {
  29840. return this._coordinatesMode;
  29841. },
  29842. /**
  29843. * How a texture is mapped.
  29844. *
  29845. * | Value | Type | Description |
  29846. * | ----- | ----------------------------------- | ----------- |
  29847. * | 0 | EXPLICIT_MODE | |
  29848. * | 1 | SPHERICAL_MODE | |
  29849. * | 2 | PLANAR_MODE | |
  29850. * | 3 | CUBIC_MODE | |
  29851. * | 4 | PROJECTION_MODE | |
  29852. * | 5 | SKYBOX_MODE | |
  29853. * | 6 | INVCUBIC_MODE | |
  29854. * | 7 | EQUIRECTANGULAR_MODE | |
  29855. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29856. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29857. */
  29858. set: function (value) {
  29859. if (this._coordinatesMode === value) {
  29860. return;
  29861. }
  29862. this._coordinatesMode = value;
  29863. if (this._scene) {
  29864. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29865. }
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29871. /**
  29872. * Gets whether or not the texture contains RGBD data.
  29873. */
  29874. get: function () {
  29875. return this._texture != null && this._texture._isRGBD;
  29876. },
  29877. enumerable: true,
  29878. configurable: true
  29879. });
  29880. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29881. get: function () {
  29882. if (this._texture)
  29883. return this._texture._lodGenerationOffset;
  29884. return 0.0;
  29885. },
  29886. set: function (value) {
  29887. if (this._texture)
  29888. this._texture._lodGenerationOffset = value;
  29889. },
  29890. enumerable: true,
  29891. configurable: true
  29892. });
  29893. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29894. get: function () {
  29895. if (this._texture)
  29896. return this._texture._lodGenerationScale;
  29897. return 0.0;
  29898. },
  29899. set: function (value) {
  29900. if (this._texture)
  29901. this._texture._lodGenerationScale = value;
  29902. },
  29903. enumerable: true,
  29904. configurable: true
  29905. });
  29906. Object.defineProperty(BaseTexture.prototype, "uid", {
  29907. get: function () {
  29908. if (!this._uid) {
  29909. this._uid = BABYLON.Tools.RandomId();
  29910. }
  29911. return this._uid;
  29912. },
  29913. enumerable: true,
  29914. configurable: true
  29915. });
  29916. BaseTexture.prototype.toString = function () {
  29917. return this.name;
  29918. };
  29919. BaseTexture.prototype.getClassName = function () {
  29920. return "BaseTexture";
  29921. };
  29922. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29923. set: function (callback) {
  29924. if (this._onDisposeObserver) {
  29925. this.onDisposeObservable.remove(this._onDisposeObserver);
  29926. }
  29927. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29928. },
  29929. enumerable: true,
  29930. configurable: true
  29931. });
  29932. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29933. get: function () {
  29934. return true;
  29935. },
  29936. enumerable: true,
  29937. configurable: true
  29938. });
  29939. BaseTexture.prototype.getScene = function () {
  29940. return this._scene;
  29941. };
  29942. BaseTexture.prototype.getTextureMatrix = function () {
  29943. return BABYLON.Matrix.IdentityReadOnly;
  29944. };
  29945. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29946. return BABYLON.Matrix.IdentityReadOnly;
  29947. };
  29948. BaseTexture.prototype.getInternalTexture = function () {
  29949. return this._texture;
  29950. };
  29951. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29952. return !this.isBlocking || this.isReady();
  29953. };
  29954. BaseTexture.prototype.isReady = function () {
  29955. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29956. this.delayLoad();
  29957. return false;
  29958. }
  29959. if (this._texture) {
  29960. return this._texture.isReady;
  29961. }
  29962. return false;
  29963. };
  29964. BaseTexture.prototype.getSize = function () {
  29965. if (this._texture) {
  29966. if (this._texture.width) {
  29967. this._cachedSize.width = this._texture.width;
  29968. this._cachedSize.height = this._texture.height;
  29969. return this._cachedSize;
  29970. }
  29971. if (this._texture._size) {
  29972. this._cachedSize.width = this._texture._size;
  29973. this._cachedSize.height = this._texture._size;
  29974. return this._cachedSize;
  29975. }
  29976. }
  29977. return this._cachedSize;
  29978. };
  29979. BaseTexture.prototype.getBaseSize = function () {
  29980. if (!this.isReady() || !this._texture)
  29981. return BABYLON.Size.Zero();
  29982. if (this._texture._size) {
  29983. return new BABYLON.Size(this._texture._size, this._texture._size);
  29984. }
  29985. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29986. };
  29987. BaseTexture.prototype.scale = function (ratio) {
  29988. };
  29989. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29990. get: function () {
  29991. return false;
  29992. },
  29993. enumerable: true,
  29994. configurable: true
  29995. });
  29996. /** @hidden */
  29997. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29998. if (!this._scene) {
  29999. return null;
  30000. }
  30001. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30002. for (var index = 0; index < texturesCache.length; index++) {
  30003. var texturesCacheEntry = texturesCache[index];
  30004. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30005. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30006. texturesCacheEntry.incrementReferences();
  30007. return texturesCacheEntry;
  30008. }
  30009. }
  30010. }
  30011. return null;
  30012. };
  30013. /** @hidden */
  30014. BaseTexture.prototype._rebuild = function () {
  30015. };
  30016. BaseTexture.prototype.delayLoad = function () {
  30017. };
  30018. BaseTexture.prototype.clone = function () {
  30019. return null;
  30020. };
  30021. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30022. get: function () {
  30023. if (!this._texture) {
  30024. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30025. }
  30026. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30027. },
  30028. enumerable: true,
  30029. configurable: true
  30030. });
  30031. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30032. get: function () {
  30033. if (!this._texture) {
  30034. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30035. }
  30036. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30037. },
  30038. enumerable: true,
  30039. configurable: true
  30040. });
  30041. /**
  30042. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30043. * This will returns an RGBA array buffer containing either in values (0-255) or
  30044. * float values (0-1) depending of the underlying buffer type.
  30045. * @param faceIndex The face of the texture to read (in case of cube texture)
  30046. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30047. * @returns The Array buffer containing the pixels data.
  30048. */
  30049. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30050. if (faceIndex === void 0) { faceIndex = 0; }
  30051. if (level === void 0) { level = 0; }
  30052. if (!this._texture) {
  30053. return null;
  30054. }
  30055. var size = this.getSize();
  30056. var width = size.width;
  30057. var height = size.height;
  30058. var scene = this.getScene();
  30059. if (!scene) {
  30060. return null;
  30061. }
  30062. var engine = scene.getEngine();
  30063. if (level != 0) {
  30064. width = width / Math.pow(2, level);
  30065. height = height / Math.pow(2, level);
  30066. width = Math.round(width);
  30067. height = Math.round(height);
  30068. }
  30069. if (this._texture.isCube) {
  30070. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30071. }
  30072. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30073. };
  30074. BaseTexture.prototype.releaseInternalTexture = function () {
  30075. if (this._texture) {
  30076. this._texture.dispose();
  30077. this._texture = null;
  30078. }
  30079. };
  30080. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30081. get: function () {
  30082. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30083. return null;
  30084. }
  30085. if (!this._texture._sphericalPolynomial) {
  30086. this._texture._sphericalPolynomial =
  30087. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30088. }
  30089. return this._texture._sphericalPolynomial;
  30090. },
  30091. set: function (value) {
  30092. if (this._texture) {
  30093. this._texture._sphericalPolynomial = value;
  30094. }
  30095. },
  30096. enumerable: true,
  30097. configurable: true
  30098. });
  30099. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30100. get: function () {
  30101. if (this._texture) {
  30102. return this._texture._lodTextureHigh;
  30103. }
  30104. return null;
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30110. get: function () {
  30111. if (this._texture) {
  30112. return this._texture._lodTextureMid;
  30113. }
  30114. return null;
  30115. },
  30116. enumerable: true,
  30117. configurable: true
  30118. });
  30119. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30120. get: function () {
  30121. if (this._texture) {
  30122. return this._texture._lodTextureLow;
  30123. }
  30124. return null;
  30125. },
  30126. enumerable: true,
  30127. configurable: true
  30128. });
  30129. BaseTexture.prototype.dispose = function () {
  30130. if (!this._scene) {
  30131. return;
  30132. }
  30133. // Animations
  30134. this._scene.stopAnimation(this);
  30135. // Remove from scene
  30136. this._scene._removePendingData(this);
  30137. var index = this._scene.textures.indexOf(this);
  30138. if (index >= 0) {
  30139. this._scene.textures.splice(index, 1);
  30140. }
  30141. if (this._texture === undefined) {
  30142. return;
  30143. }
  30144. // Release
  30145. this.releaseInternalTexture();
  30146. // Callback
  30147. this.onDisposeObservable.notifyObservers(this);
  30148. this.onDisposeObservable.clear();
  30149. };
  30150. BaseTexture.prototype.serialize = function () {
  30151. if (!this.name) {
  30152. return null;
  30153. }
  30154. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30155. // Animations
  30156. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30157. return serializationObject;
  30158. };
  30159. BaseTexture.WhenAllReady = function (textures, callback) {
  30160. var numRemaining = textures.length;
  30161. if (numRemaining === 0) {
  30162. callback();
  30163. return;
  30164. }
  30165. var _loop_1 = function () {
  30166. texture = textures[i];
  30167. if (texture.isReady()) {
  30168. if (--numRemaining === 0) {
  30169. callback();
  30170. }
  30171. }
  30172. else {
  30173. onLoadObservable = texture.onLoadObservable;
  30174. var onLoadCallback_1 = function () {
  30175. onLoadObservable.removeCallback(onLoadCallback_1);
  30176. if (--numRemaining === 0) {
  30177. callback();
  30178. }
  30179. };
  30180. onLoadObservable.add(onLoadCallback_1);
  30181. }
  30182. };
  30183. var texture, onLoadObservable;
  30184. for (var i = 0; i < textures.length; i++) {
  30185. _loop_1();
  30186. }
  30187. };
  30188. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30189. __decorate([
  30190. BABYLON.serialize()
  30191. ], BaseTexture.prototype, "name", void 0);
  30192. __decorate([
  30193. BABYLON.serialize("hasAlpha")
  30194. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30195. __decorate([
  30196. BABYLON.serialize()
  30197. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30198. __decorate([
  30199. BABYLON.serialize()
  30200. ], BaseTexture.prototype, "level", void 0);
  30201. __decorate([
  30202. BABYLON.serialize()
  30203. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30204. __decorate([
  30205. BABYLON.serialize("coordinatesMode")
  30206. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30207. __decorate([
  30208. BABYLON.serialize()
  30209. ], BaseTexture.prototype, "wrapU", void 0);
  30210. __decorate([
  30211. BABYLON.serialize()
  30212. ], BaseTexture.prototype, "wrapV", void 0);
  30213. __decorate([
  30214. BABYLON.serialize()
  30215. ], BaseTexture.prototype, "wrapR", void 0);
  30216. __decorate([
  30217. BABYLON.serialize()
  30218. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30219. __decorate([
  30220. BABYLON.serialize()
  30221. ], BaseTexture.prototype, "isCube", void 0);
  30222. __decorate([
  30223. BABYLON.serialize()
  30224. ], BaseTexture.prototype, "is3D", void 0);
  30225. __decorate([
  30226. BABYLON.serialize()
  30227. ], BaseTexture.prototype, "gammaSpace", void 0);
  30228. __decorate([
  30229. BABYLON.serialize()
  30230. ], BaseTexture.prototype, "invertZ", void 0);
  30231. __decorate([
  30232. BABYLON.serialize()
  30233. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30234. __decorate([
  30235. BABYLON.serialize()
  30236. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30237. __decorate([
  30238. BABYLON.serialize()
  30239. ], BaseTexture.prototype, "lodGenerationScale", null);
  30240. __decorate([
  30241. BABYLON.serialize()
  30242. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30243. return BaseTexture;
  30244. }());
  30245. BABYLON.BaseTexture = BaseTexture;
  30246. })(BABYLON || (BABYLON = {}));
  30247. //# sourceMappingURL=babylon.baseTexture.js.map
  30248. var BABYLON;
  30249. (function (BABYLON) {
  30250. var Texture = /** @class */ (function (_super) {
  30251. __extends(Texture, _super);
  30252. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30253. if (noMipmap === void 0) { noMipmap = false; }
  30254. if (invertY === void 0) { invertY = true; }
  30255. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30256. if (onLoad === void 0) { onLoad = null; }
  30257. if (onError === void 0) { onError = null; }
  30258. if (buffer === void 0) { buffer = null; }
  30259. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30260. var _this = _super.call(this, scene) || this;
  30261. _this.uOffset = 0;
  30262. _this.vOffset = 0;
  30263. _this.uScale = 1.0;
  30264. _this.vScale = 1.0;
  30265. _this.uAng = 0;
  30266. _this.vAng = 0;
  30267. _this.wAng = 0;
  30268. /**
  30269. * Defines the center of rotation (U)
  30270. */
  30271. _this.uRotationCenter = 0.5;
  30272. /**
  30273. * Defines the center of rotation (V)
  30274. */
  30275. _this.vRotationCenter = 0.5;
  30276. /**
  30277. * Defines the center of rotation (W)
  30278. */
  30279. _this.wRotationCenter = 0.5;
  30280. _this._isBlocking = true;
  30281. _this.name = url || "";
  30282. _this.url = url;
  30283. _this._noMipmap = noMipmap;
  30284. _this._invertY = invertY;
  30285. _this._samplingMode = samplingMode;
  30286. _this._buffer = buffer;
  30287. _this._deleteBuffer = deleteBuffer;
  30288. if (format) {
  30289. _this._format = format;
  30290. }
  30291. scene = _this.getScene();
  30292. if (!scene) {
  30293. return _this;
  30294. }
  30295. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30296. var load = function () {
  30297. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30298. _this.onLoadObservable.notifyObservers(_this);
  30299. }
  30300. if (onLoad) {
  30301. onLoad();
  30302. }
  30303. if (!_this.isBlocking && scene) {
  30304. scene.resetCachedMaterial();
  30305. }
  30306. };
  30307. if (!_this.url) {
  30308. _this._delayedOnLoad = load;
  30309. _this._delayedOnError = onError;
  30310. return _this;
  30311. }
  30312. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30313. if (!_this._texture) {
  30314. if (!scene.useDelayedTextureLoading) {
  30315. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30316. if (deleteBuffer) {
  30317. delete _this._buffer;
  30318. }
  30319. }
  30320. else {
  30321. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30322. _this._delayedOnLoad = load;
  30323. _this._delayedOnError = onError;
  30324. }
  30325. }
  30326. else {
  30327. if (_this._texture.isReady) {
  30328. BABYLON.Tools.SetImmediate(function () { return load(); });
  30329. }
  30330. else {
  30331. _this._texture.onLoadedObservable.add(load);
  30332. }
  30333. }
  30334. return _this;
  30335. }
  30336. Object.defineProperty(Texture.prototype, "noMipmap", {
  30337. get: function () {
  30338. return this._noMipmap;
  30339. },
  30340. enumerable: true,
  30341. configurable: true
  30342. });
  30343. Object.defineProperty(Texture.prototype, "isBlocking", {
  30344. get: function () {
  30345. return this._isBlocking;
  30346. },
  30347. set: function (value) {
  30348. this._isBlocking = value;
  30349. },
  30350. enumerable: true,
  30351. configurable: true
  30352. });
  30353. Object.defineProperty(Texture.prototype, "samplingMode", {
  30354. get: function () {
  30355. return this._samplingMode;
  30356. },
  30357. enumerable: true,
  30358. configurable: true
  30359. });
  30360. /**
  30361. * Update the url (and optional buffer) of this texture if url was null during construction.
  30362. * @param url the url of the texture
  30363. * @param buffer the buffer of the texture (defaults to null)
  30364. */
  30365. Texture.prototype.updateURL = function (url, buffer) {
  30366. if (buffer === void 0) { buffer = null; }
  30367. if (this.url) {
  30368. throw new Error("URL is already set");
  30369. }
  30370. this.url = url;
  30371. this._buffer = buffer;
  30372. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30373. this.delayLoad();
  30374. };
  30375. Texture.prototype.delayLoad = function () {
  30376. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30377. return;
  30378. }
  30379. var scene = this.getScene();
  30380. if (!scene) {
  30381. return;
  30382. }
  30383. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30384. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30385. if (!this._texture) {
  30386. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30387. if (this._deleteBuffer) {
  30388. delete this._buffer;
  30389. }
  30390. }
  30391. else {
  30392. if (this._delayedOnLoad) {
  30393. if (this._texture.isReady) {
  30394. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30395. }
  30396. else {
  30397. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30398. }
  30399. }
  30400. }
  30401. this._delayedOnLoad = null;
  30402. this._delayedOnError = null;
  30403. };
  30404. /**
  30405. * Default is Trilinear mode.
  30406. *
  30407. * | Value | Type | Description |
  30408. * | ----- | ------------------ | ----------- |
  30409. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30410. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30411. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30412. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30413. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30414. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30415. * | 7 | NEAREST_LINEAR | |
  30416. * | 8 | NEAREST_NEAREST | |
  30417. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30418. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30419. * | 11 | LINEAR_LINEAR | |
  30420. * | 12 | LINEAR_NEAREST | |
  30421. *
  30422. * > _mag_: magnification filter (close to the viewer)
  30423. * > _min_: minification filter (far from the viewer)
  30424. * > _mip_: filter used between mip map levels
  30425. *
  30426. */
  30427. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30428. if (!this._texture) {
  30429. return;
  30430. }
  30431. var scene = this.getScene();
  30432. if (!scene) {
  30433. return;
  30434. }
  30435. this._samplingMode = samplingMode;
  30436. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30437. };
  30438. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30439. x *= this.uScale;
  30440. y *= this.vScale;
  30441. x -= this.uRotationCenter * this.uScale;
  30442. y -= this.vRotationCenter * this.vScale;
  30443. z -= this.wRotationCenter;
  30444. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30445. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30446. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30447. t.z += this.wRotationCenter;
  30448. };
  30449. Texture.prototype.getTextureMatrix = function () {
  30450. var _this = this;
  30451. if (this.uOffset === this._cachedUOffset &&
  30452. this.vOffset === this._cachedVOffset &&
  30453. this.uScale === this._cachedUScale &&
  30454. this.vScale === this._cachedVScale &&
  30455. this.uAng === this._cachedUAng &&
  30456. this.vAng === this._cachedVAng &&
  30457. this.wAng === this._cachedWAng) {
  30458. return this._cachedTextureMatrix;
  30459. }
  30460. this._cachedUOffset = this.uOffset;
  30461. this._cachedVOffset = this.vOffset;
  30462. this._cachedUScale = this.uScale;
  30463. this._cachedVScale = this.vScale;
  30464. this._cachedUAng = this.uAng;
  30465. this._cachedVAng = this.vAng;
  30466. this._cachedWAng = this.wAng;
  30467. if (!this._cachedTextureMatrix) {
  30468. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30469. this._rowGenerationMatrix = new BABYLON.Matrix();
  30470. this._t0 = BABYLON.Vector3.Zero();
  30471. this._t1 = BABYLON.Vector3.Zero();
  30472. this._t2 = BABYLON.Vector3.Zero();
  30473. }
  30474. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30475. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30476. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30477. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30478. this._t1.subtractInPlace(this._t0);
  30479. this._t2.subtractInPlace(this._t0);
  30480. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30481. this._cachedTextureMatrix.m[0] = this._t1.x;
  30482. this._cachedTextureMatrix.m[1] = this._t1.y;
  30483. this._cachedTextureMatrix.m[2] = this._t1.z;
  30484. this._cachedTextureMatrix.m[4] = this._t2.x;
  30485. this._cachedTextureMatrix.m[5] = this._t2.y;
  30486. this._cachedTextureMatrix.m[6] = this._t2.z;
  30487. this._cachedTextureMatrix.m[8] = this._t0.x;
  30488. this._cachedTextureMatrix.m[9] = this._t0.y;
  30489. this._cachedTextureMatrix.m[10] = this._t0.z;
  30490. var scene = this.getScene();
  30491. if (!scene) {
  30492. return this._cachedTextureMatrix;
  30493. }
  30494. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30495. return mat.hasTexture(_this);
  30496. });
  30497. return this._cachedTextureMatrix;
  30498. };
  30499. Texture.prototype.getReflectionTextureMatrix = function () {
  30500. var _this = this;
  30501. var scene = this.getScene();
  30502. if (!scene) {
  30503. return this._cachedTextureMatrix;
  30504. }
  30505. if (this.uOffset === this._cachedUOffset &&
  30506. this.vOffset === this._cachedVOffset &&
  30507. this.uScale === this._cachedUScale &&
  30508. this.vScale === this._cachedVScale &&
  30509. this.coordinatesMode === this._cachedCoordinatesMode) {
  30510. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30511. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30512. return this._cachedTextureMatrix;
  30513. }
  30514. }
  30515. else {
  30516. return this._cachedTextureMatrix;
  30517. }
  30518. }
  30519. if (!this._cachedTextureMatrix) {
  30520. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30521. }
  30522. if (!this._projectionModeMatrix) {
  30523. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30524. }
  30525. this._cachedUOffset = this.uOffset;
  30526. this._cachedVOffset = this.vOffset;
  30527. this._cachedUScale = this.uScale;
  30528. this._cachedVScale = this.vScale;
  30529. this._cachedCoordinatesMode = this.coordinatesMode;
  30530. switch (this.coordinatesMode) {
  30531. case Texture.PLANAR_MODE:
  30532. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30533. this._cachedTextureMatrix[0] = this.uScale;
  30534. this._cachedTextureMatrix[5] = this.vScale;
  30535. this._cachedTextureMatrix[12] = this.uOffset;
  30536. this._cachedTextureMatrix[13] = this.vOffset;
  30537. break;
  30538. case Texture.PROJECTION_MODE:
  30539. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30540. this._projectionModeMatrix.m[0] = 0.5;
  30541. this._projectionModeMatrix.m[5] = -0.5;
  30542. this._projectionModeMatrix.m[10] = 0.0;
  30543. this._projectionModeMatrix.m[12] = 0.5;
  30544. this._projectionModeMatrix.m[13] = 0.5;
  30545. this._projectionModeMatrix.m[14] = 1.0;
  30546. this._projectionModeMatrix.m[15] = 1.0;
  30547. var projectionMatrix = scene.getProjectionMatrix();
  30548. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30549. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30550. break;
  30551. default:
  30552. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30553. break;
  30554. }
  30555. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30556. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30557. });
  30558. return this._cachedTextureMatrix;
  30559. };
  30560. Texture.prototype.clone = function () {
  30561. var _this = this;
  30562. return BABYLON.SerializationHelper.Clone(function () {
  30563. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30564. }, this);
  30565. };
  30566. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30567. get: function () {
  30568. if (!this._onLoadObservable) {
  30569. this._onLoadObservable = new BABYLON.Observable();
  30570. }
  30571. return this._onLoadObservable;
  30572. },
  30573. enumerable: true,
  30574. configurable: true
  30575. });
  30576. Texture.prototype.serialize = function () {
  30577. var serializationObject = _super.prototype.serialize.call(this);
  30578. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30579. serializationObject.base64String = this._buffer;
  30580. serializationObject.name = serializationObject.name.replace("data:", "");
  30581. }
  30582. serializationObject.invertY = this._invertY;
  30583. serializationObject.samplingMode = this.samplingMode;
  30584. return serializationObject;
  30585. };
  30586. Texture.prototype.getClassName = function () {
  30587. return "Texture";
  30588. };
  30589. Texture.prototype.dispose = function () {
  30590. _super.prototype.dispose.call(this);
  30591. if (this._onLoadObservable) {
  30592. this._onLoadObservable.clear();
  30593. this._onLoadObservable = null;
  30594. }
  30595. this._delayedOnLoad = null;
  30596. this._delayedOnError = null;
  30597. };
  30598. // Statics
  30599. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30600. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30601. if (onLoad === void 0) { onLoad = null; }
  30602. if (onError === void 0) { onError = null; }
  30603. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30604. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30605. };
  30606. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30607. if (parsedTexture.customType) {
  30608. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30609. // Update Sampling Mode
  30610. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30611. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30612. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30613. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30614. }
  30615. }
  30616. return parsedCustomTexture;
  30617. }
  30618. if (parsedTexture.isCube) {
  30619. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30620. }
  30621. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30622. return null;
  30623. }
  30624. var texture = BABYLON.SerializationHelper.Parse(function () {
  30625. var generateMipMaps = true;
  30626. if (parsedTexture.noMipmap) {
  30627. generateMipMaps = false;
  30628. }
  30629. if (parsedTexture.mirrorPlane) {
  30630. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30631. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30632. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30633. return mirrorTexture;
  30634. }
  30635. else if (parsedTexture.isRenderTarget) {
  30636. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30637. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30638. return renderTargetTexture;
  30639. }
  30640. else {
  30641. var texture;
  30642. if (parsedTexture.base64String) {
  30643. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30644. }
  30645. else {
  30646. var url = rootUrl + parsedTexture.name;
  30647. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30648. url = parsedTexture.url;
  30649. }
  30650. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30651. }
  30652. return texture;
  30653. }
  30654. }, parsedTexture, scene);
  30655. // Update Sampling Mode
  30656. if (parsedTexture.samplingMode) {
  30657. var sampling = parsedTexture.samplingMode;
  30658. if (texture._samplingMode !== sampling) {
  30659. texture.updateSamplingMode(sampling);
  30660. }
  30661. }
  30662. // Animations
  30663. if (parsedTexture.animations) {
  30664. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30665. var parsedAnimation = parsedTexture.animations[animationIndex];
  30666. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30667. }
  30668. }
  30669. return texture;
  30670. };
  30671. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30672. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30673. if (noMipmap === void 0) { noMipmap = false; }
  30674. if (invertY === void 0) { invertY = true; }
  30675. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30676. if (onLoad === void 0) { onLoad = null; }
  30677. if (onError === void 0) { onError = null; }
  30678. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30679. if (name.substr(0, 5) !== "data:") {
  30680. name = "data:" + name;
  30681. }
  30682. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30683. };
  30684. // Constants
  30685. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30686. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30687. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30688. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30689. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30690. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30691. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30692. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30693. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30694. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30695. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30696. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30697. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30698. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30699. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30700. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30701. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30702. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30703. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30704. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30705. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30706. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30707. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30708. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30709. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30710. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30711. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30712. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30713. /**
  30714. * 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
  30715. */
  30716. Texture.UseSerializedUrlIfAny = false;
  30717. __decorate([
  30718. BABYLON.serialize()
  30719. ], Texture.prototype, "url", void 0);
  30720. __decorate([
  30721. BABYLON.serialize()
  30722. ], Texture.prototype, "uOffset", void 0);
  30723. __decorate([
  30724. BABYLON.serialize()
  30725. ], Texture.prototype, "vOffset", void 0);
  30726. __decorate([
  30727. BABYLON.serialize()
  30728. ], Texture.prototype, "uScale", void 0);
  30729. __decorate([
  30730. BABYLON.serialize()
  30731. ], Texture.prototype, "vScale", void 0);
  30732. __decorate([
  30733. BABYLON.serialize()
  30734. ], Texture.prototype, "uAng", void 0);
  30735. __decorate([
  30736. BABYLON.serialize()
  30737. ], Texture.prototype, "vAng", void 0);
  30738. __decorate([
  30739. BABYLON.serialize()
  30740. ], Texture.prototype, "wAng", void 0);
  30741. __decorate([
  30742. BABYLON.serialize()
  30743. ], Texture.prototype, "uRotationCenter", void 0);
  30744. __decorate([
  30745. BABYLON.serialize()
  30746. ], Texture.prototype, "vRotationCenter", void 0);
  30747. __decorate([
  30748. BABYLON.serialize()
  30749. ], Texture.prototype, "wRotationCenter", void 0);
  30750. __decorate([
  30751. BABYLON.serialize()
  30752. ], Texture.prototype, "isBlocking", null);
  30753. return Texture;
  30754. }(BABYLON.BaseTexture));
  30755. BABYLON.Texture = Texture;
  30756. })(BABYLON || (BABYLON = {}));
  30757. //# sourceMappingURL=babylon.texture.js.map
  30758. var BABYLON;
  30759. (function (BABYLON) {
  30760. /**
  30761. * @hidden
  30762. **/
  30763. var _InstancesBatch = /** @class */ (function () {
  30764. function _InstancesBatch() {
  30765. this.mustReturn = false;
  30766. this.visibleInstances = new Array();
  30767. this.renderSelf = new Array();
  30768. }
  30769. return _InstancesBatch;
  30770. }());
  30771. BABYLON._InstancesBatch = _InstancesBatch;
  30772. var Mesh = /** @class */ (function (_super) {
  30773. __extends(Mesh, _super);
  30774. /**
  30775. * @constructor
  30776. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30777. * @param {Scene} scene The scene to add this mesh to.
  30778. * @param {Node} parent The parent of this mesh, if it has one
  30779. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30780. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30781. * When false, achieved by calling a clone(), also passing False.
  30782. * This will make creation of children, recursive.
  30783. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30784. */
  30785. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30786. if (scene === void 0) { scene = null; }
  30787. if (parent === void 0) { parent = null; }
  30788. if (source === void 0) { source = null; }
  30789. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30790. var _this = _super.call(this, name, scene) || this;
  30791. // Members
  30792. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30793. _this.instances = new Array();
  30794. _this._LODLevels = new Array();
  30795. /** @hidden */
  30796. _this._visibleInstances = {};
  30797. _this._renderIdForInstances = new Array();
  30798. _this._batchCache = new _InstancesBatch();
  30799. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30800. // Use by builder only to know what orientation were the mesh build in.
  30801. /** @hidden */
  30802. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30803. _this.overrideMaterialSideOrientation = null;
  30804. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30805. // Will be used to save a source mesh reference, If any
  30806. _this._source = null;
  30807. scene = _this.getScene();
  30808. if (source) {
  30809. // Geometry
  30810. if (source._geometry) {
  30811. source._geometry.applyToMesh(_this);
  30812. }
  30813. // Deep copy
  30814. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30815. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30816. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30817. ], ["_poseMatrix"]);
  30818. // Source mesh
  30819. _this._source = source;
  30820. // Construction Params
  30821. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30822. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30823. var myAnyThis = _this;
  30824. var myAnySource = source;
  30825. myAnyThis._closePath = myAnySource._closePath;
  30826. myAnyThis._idx = myAnySource._idx;
  30827. myAnyThis.dashSize = myAnySource.dashSize;
  30828. myAnyThis.gapSize = myAnySource.gapSize;
  30829. myAnyThis.path3D = myAnySource.path3D;
  30830. myAnyThis.pathArray = myAnySource.pathArray;
  30831. myAnyThis.arc = myAnySource.arc;
  30832. myAnyThis.radius = myAnySource.radius;
  30833. // Animation ranges
  30834. if (_this._source._ranges) {
  30835. var ranges = _this._source._ranges;
  30836. for (var name in ranges) {
  30837. if (!ranges.hasOwnProperty(name)) {
  30838. continue;
  30839. }
  30840. if (!ranges[name]) {
  30841. continue;
  30842. }
  30843. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30844. }
  30845. }
  30846. // Metadata
  30847. if (source.metadata && source.metadata.clone) {
  30848. _this.metadata = source.metadata.clone();
  30849. }
  30850. else {
  30851. _this.metadata = source.metadata;
  30852. }
  30853. // Tags
  30854. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30855. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30856. }
  30857. // Parent
  30858. _this.parent = source.parent;
  30859. // Pivot
  30860. _this.setPivotMatrix(source.getPivotMatrix());
  30861. _this.id = name + "." + source.id;
  30862. // Material
  30863. _this.material = source.material;
  30864. var index;
  30865. if (!doNotCloneChildren) {
  30866. // Children
  30867. var directDescendants = source.getDescendants(true);
  30868. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30869. var child = directDescendants[index_1];
  30870. if (child.clone) {
  30871. child.clone(name + "." + child.name, _this);
  30872. }
  30873. }
  30874. }
  30875. // Physics clone
  30876. var physicsEngine = _this.getScene().getPhysicsEngine();
  30877. if (clonePhysicsImpostor && physicsEngine) {
  30878. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30879. if (impostor) {
  30880. _this.physicsImpostor = impostor.clone(_this);
  30881. }
  30882. }
  30883. // Particles
  30884. for (index = 0; index < scene.particleSystems.length; index++) {
  30885. var system = scene.particleSystems[index];
  30886. if (system.emitter === source) {
  30887. system.clone(system.name, _this);
  30888. }
  30889. }
  30890. _this.refreshBoundingInfo();
  30891. _this.computeWorldMatrix(true);
  30892. }
  30893. // Parent
  30894. if (parent !== null) {
  30895. _this.parent = parent;
  30896. }
  30897. return _this;
  30898. }
  30899. Object.defineProperty(Mesh, "FRONTSIDE", {
  30900. /**
  30901. * Mesh side orientation : usually the external or front surface
  30902. */
  30903. get: function () {
  30904. return Mesh._FRONTSIDE;
  30905. },
  30906. enumerable: true,
  30907. configurable: true
  30908. });
  30909. Object.defineProperty(Mesh, "BACKSIDE", {
  30910. /**
  30911. * Mesh side orientation : usually the internal or back surface
  30912. */
  30913. get: function () {
  30914. return Mesh._BACKSIDE;
  30915. },
  30916. enumerable: true,
  30917. configurable: true
  30918. });
  30919. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30920. /**
  30921. * Mesh side orientation : both internal and external or front and back surfaces
  30922. */
  30923. get: function () {
  30924. return Mesh._DOUBLESIDE;
  30925. },
  30926. enumerable: true,
  30927. configurable: true
  30928. });
  30929. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30930. /**
  30931. * Mesh side orientation : by default, `FRONTSIDE`
  30932. */
  30933. get: function () {
  30934. return Mesh._DEFAULTSIDE;
  30935. },
  30936. enumerable: true,
  30937. configurable: true
  30938. });
  30939. Object.defineProperty(Mesh, "NO_CAP", {
  30940. /**
  30941. * Mesh cap setting : no cap
  30942. */
  30943. get: function () {
  30944. return Mesh._NO_CAP;
  30945. },
  30946. enumerable: true,
  30947. configurable: true
  30948. });
  30949. Object.defineProperty(Mesh, "CAP_START", {
  30950. /**
  30951. * Mesh cap setting : one cap at the beginning of the mesh
  30952. */
  30953. get: function () {
  30954. return Mesh._CAP_START;
  30955. },
  30956. enumerable: true,
  30957. configurable: true
  30958. });
  30959. Object.defineProperty(Mesh, "CAP_END", {
  30960. /**
  30961. * Mesh cap setting : one cap at the end of the mesh
  30962. */
  30963. get: function () {
  30964. return Mesh._CAP_END;
  30965. },
  30966. enumerable: true,
  30967. configurable: true
  30968. });
  30969. Object.defineProperty(Mesh, "CAP_ALL", {
  30970. /**
  30971. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30972. */
  30973. get: function () {
  30974. return Mesh._CAP_ALL;
  30975. },
  30976. enumerable: true,
  30977. configurable: true
  30978. });
  30979. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30980. /**
  30981. * An event triggered before rendering the mesh
  30982. */
  30983. get: function () {
  30984. if (!this._onBeforeRenderObservable) {
  30985. this._onBeforeRenderObservable = new BABYLON.Observable();
  30986. }
  30987. return this._onBeforeRenderObservable;
  30988. },
  30989. enumerable: true,
  30990. configurable: true
  30991. });
  30992. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30993. /**
  30994. * An event triggered after rendering the mesh
  30995. */
  30996. get: function () {
  30997. if (!this._onAfterRenderObservable) {
  30998. this._onAfterRenderObservable = new BABYLON.Observable();
  30999. }
  31000. return this._onAfterRenderObservable;
  31001. },
  31002. enumerable: true,
  31003. configurable: true
  31004. });
  31005. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31006. /**
  31007. * An event triggered before drawing the mesh
  31008. */
  31009. get: function () {
  31010. if (!this._onBeforeDrawObservable) {
  31011. this._onBeforeDrawObservable = new BABYLON.Observable();
  31012. }
  31013. return this._onBeforeDrawObservable;
  31014. },
  31015. enumerable: true,
  31016. configurable: true
  31017. });
  31018. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31019. set: function (callback) {
  31020. if (this._onBeforeDrawObserver) {
  31021. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31022. }
  31023. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31024. },
  31025. enumerable: true,
  31026. configurable: true
  31027. });
  31028. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31029. get: function () {
  31030. return this._morphTargetManager;
  31031. },
  31032. set: function (value) {
  31033. if (this._morphTargetManager === value) {
  31034. return;
  31035. }
  31036. this._morphTargetManager = value;
  31037. this._syncGeometryWithMorphTargetManager();
  31038. },
  31039. enumerable: true,
  31040. configurable: true
  31041. });
  31042. Object.defineProperty(Mesh.prototype, "source", {
  31043. get: function () {
  31044. return this._source;
  31045. },
  31046. enumerable: true,
  31047. configurable: true
  31048. });
  31049. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31050. get: function () {
  31051. return this._unIndexed;
  31052. },
  31053. set: function (value) {
  31054. if (this._unIndexed !== value) {
  31055. this._unIndexed = value;
  31056. this._markSubMeshesAsAttributesDirty();
  31057. }
  31058. },
  31059. enumerable: true,
  31060. configurable: true
  31061. });
  31062. // Methods
  31063. /**
  31064. * Returns the string "Mesh".
  31065. */
  31066. Mesh.prototype.getClassName = function () {
  31067. return "Mesh";
  31068. };
  31069. /**
  31070. * Returns a string.
  31071. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31072. */
  31073. Mesh.prototype.toString = function (fullDetails) {
  31074. var ret = _super.prototype.toString.call(this, fullDetails);
  31075. ret += ", n vertices: " + this.getTotalVertices();
  31076. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31077. if (this.animations) {
  31078. for (var i = 0; i < this.animations.length; i++) {
  31079. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31080. }
  31081. }
  31082. if (fullDetails) {
  31083. if (this._geometry) {
  31084. var ib = this.getIndices();
  31085. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31086. if (vb && ib) {
  31087. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31088. }
  31089. }
  31090. else {
  31091. ret += ", flat shading: UNKNOWN";
  31092. }
  31093. }
  31094. return ret;
  31095. };
  31096. /** @hidden */
  31097. Mesh.prototype._unBindEffect = function () {
  31098. _super.prototype._unBindEffect.call(this);
  31099. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31100. var instance = _a[_i];
  31101. instance._unBindEffect();
  31102. }
  31103. };
  31104. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31105. /**
  31106. * True if the mesh has some Levels Of Details (LOD).
  31107. * Returns a boolean.
  31108. */
  31109. get: function () {
  31110. return this._LODLevels.length > 0;
  31111. },
  31112. enumerable: true,
  31113. configurable: true
  31114. });
  31115. /**
  31116. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31117. * @returns an array of {BABYLON.MeshLODLevel}
  31118. */
  31119. Mesh.prototype.getLODLevels = function () {
  31120. return this._LODLevels;
  31121. };
  31122. Mesh.prototype._sortLODLevels = function () {
  31123. this._LODLevels.sort(function (a, b) {
  31124. if (a.distance < b.distance) {
  31125. return 1;
  31126. }
  31127. if (a.distance > b.distance) {
  31128. return -1;
  31129. }
  31130. return 0;
  31131. });
  31132. };
  31133. /**
  31134. * Add a mesh as LOD level triggered at the given distance.
  31135. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31136. * @param distance The distance from the center of the object to show this level
  31137. * @param mesh The mesh to be added as LOD level (can be null)
  31138. * @return This mesh (for chaining)
  31139. */
  31140. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31141. if (mesh && mesh._masterMesh) {
  31142. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31143. return this;
  31144. }
  31145. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31146. this._LODLevels.push(level);
  31147. if (mesh) {
  31148. mesh._masterMesh = this;
  31149. }
  31150. this._sortLODLevels();
  31151. return this;
  31152. };
  31153. /**
  31154. * Returns the LOD level mesh at the passed distance or null if not found.
  31155. * It is related to the method `addLODLevel(distance, mesh)`.
  31156. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31157. * Returns an object Mesh or `null`.
  31158. */
  31159. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31160. for (var index = 0; index < this._LODLevels.length; index++) {
  31161. var level = this._LODLevels[index];
  31162. if (level.distance === distance) {
  31163. return level.mesh;
  31164. }
  31165. }
  31166. return null;
  31167. };
  31168. /**
  31169. * Remove a mesh from the LOD array
  31170. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31171. * @param {Mesh} mesh The mesh to be removed.
  31172. * @return {Mesh} This mesh (for chaining)
  31173. */
  31174. Mesh.prototype.removeLODLevel = function (mesh) {
  31175. for (var index = 0; index < this._LODLevels.length; index++) {
  31176. if (this._LODLevels[index].mesh === mesh) {
  31177. this._LODLevels.splice(index, 1);
  31178. if (mesh) {
  31179. mesh._masterMesh = null;
  31180. }
  31181. }
  31182. }
  31183. this._sortLODLevels();
  31184. return this;
  31185. };
  31186. /**
  31187. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31188. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31189. */
  31190. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31191. if (!this._LODLevels || this._LODLevels.length === 0) {
  31192. return this;
  31193. }
  31194. var bSphere;
  31195. if (boundingSphere) {
  31196. bSphere = boundingSphere;
  31197. }
  31198. else {
  31199. var boundingInfo = this.getBoundingInfo();
  31200. bSphere = boundingInfo.boundingSphere;
  31201. }
  31202. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31203. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31204. if (this.onLODLevelSelection) {
  31205. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31206. }
  31207. return this;
  31208. }
  31209. for (var index = 0; index < this._LODLevels.length; index++) {
  31210. var level = this._LODLevels[index];
  31211. if (level.distance < distanceToCamera) {
  31212. if (level.mesh) {
  31213. level.mesh._preActivate();
  31214. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31215. }
  31216. if (this.onLODLevelSelection) {
  31217. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31218. }
  31219. return level.mesh;
  31220. }
  31221. }
  31222. if (this.onLODLevelSelection) {
  31223. this.onLODLevelSelection(distanceToCamera, this, this);
  31224. }
  31225. return this;
  31226. };
  31227. Object.defineProperty(Mesh.prototype, "geometry", {
  31228. /**
  31229. * Returns the mesh internal Geometry object.
  31230. */
  31231. get: function () {
  31232. return this._geometry;
  31233. },
  31234. enumerable: true,
  31235. configurable: true
  31236. });
  31237. /**
  31238. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31239. */
  31240. Mesh.prototype.getTotalVertices = function () {
  31241. if (this._geometry === null || this._geometry === undefined) {
  31242. return 0;
  31243. }
  31244. return this._geometry.getTotalVertices();
  31245. };
  31246. /**
  31247. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31248. * 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.
  31249. * You can force the copy with forceCopy === true
  31250. * Returns null if the mesh has no geometry or no vertex buffer.
  31251. * Possible `kind` values :
  31252. * - BABYLON.VertexBuffer.PositionKind
  31253. * - BABYLON.VertexBuffer.UVKind
  31254. * - BABYLON.VertexBuffer.UV2Kind
  31255. * - BABYLON.VertexBuffer.UV3Kind
  31256. * - BABYLON.VertexBuffer.UV4Kind
  31257. * - BABYLON.VertexBuffer.UV5Kind
  31258. * - BABYLON.VertexBuffer.UV6Kind
  31259. * - BABYLON.VertexBuffer.ColorKind
  31260. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31261. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31262. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31263. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31264. */
  31265. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31266. if (!this._geometry) {
  31267. return null;
  31268. }
  31269. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31270. };
  31271. /**
  31272. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31273. * Returns `null` if the mesh has no geometry.
  31274. * Possible `kind` values :
  31275. * - BABYLON.VertexBuffer.PositionKind
  31276. * - BABYLON.VertexBuffer.UVKind
  31277. * - BABYLON.VertexBuffer.UV2Kind
  31278. * - BABYLON.VertexBuffer.UV3Kind
  31279. * - BABYLON.VertexBuffer.UV4Kind
  31280. * - BABYLON.VertexBuffer.UV5Kind
  31281. * - BABYLON.VertexBuffer.UV6Kind
  31282. * - BABYLON.VertexBuffer.ColorKind
  31283. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31284. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31285. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31286. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31287. */
  31288. Mesh.prototype.getVertexBuffer = function (kind) {
  31289. if (!this._geometry) {
  31290. return null;
  31291. }
  31292. return this._geometry.getVertexBuffer(kind);
  31293. };
  31294. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31295. if (!this._geometry) {
  31296. if (this._delayInfo) {
  31297. return this._delayInfo.indexOf(kind) !== -1;
  31298. }
  31299. return false;
  31300. }
  31301. return this._geometry.isVerticesDataPresent(kind);
  31302. };
  31303. /**
  31304. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31305. * Possible `kind` values :
  31306. * - BABYLON.VertexBuffer.PositionKind
  31307. * - BABYLON.VertexBuffer.UVKind
  31308. * - BABYLON.VertexBuffer.UV2Kind
  31309. * - BABYLON.VertexBuffer.UV3Kind
  31310. * - BABYLON.VertexBuffer.UV4Kind
  31311. * - BABYLON.VertexBuffer.UV5Kind
  31312. * - BABYLON.VertexBuffer.UV6Kind
  31313. * - BABYLON.VertexBuffer.ColorKind
  31314. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31315. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31316. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31317. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31318. */
  31319. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31320. if (!this._geometry) {
  31321. if (this._delayInfo) {
  31322. return this._delayInfo.indexOf(kind) !== -1;
  31323. }
  31324. return false;
  31325. }
  31326. return this._geometry.isVertexBufferUpdatable(kind);
  31327. };
  31328. /**
  31329. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31330. * Possible `kind` values :
  31331. * - BABYLON.VertexBuffer.PositionKind
  31332. * - BABYLON.VertexBuffer.UVKind
  31333. * - BABYLON.VertexBuffer.UV2Kind
  31334. * - BABYLON.VertexBuffer.UV3Kind
  31335. * - BABYLON.VertexBuffer.UV4Kind
  31336. * - BABYLON.VertexBuffer.UV5Kind
  31337. * - BABYLON.VertexBuffer.UV6Kind
  31338. * - BABYLON.VertexBuffer.ColorKind
  31339. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31340. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31341. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31342. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31343. */
  31344. Mesh.prototype.getVerticesDataKinds = function () {
  31345. if (!this._geometry) {
  31346. var result = new Array();
  31347. if (this._delayInfo) {
  31348. this._delayInfo.forEach(function (kind, index, array) {
  31349. result.push(kind);
  31350. });
  31351. }
  31352. return result;
  31353. }
  31354. return this._geometry.getVerticesDataKinds();
  31355. };
  31356. /**
  31357. * Returns a positive integer : the total number of indices in this mesh geometry.
  31358. * Returns zero if the mesh has no geometry.
  31359. */
  31360. Mesh.prototype.getTotalIndices = function () {
  31361. if (!this._geometry) {
  31362. return 0;
  31363. }
  31364. return this._geometry.getTotalIndices();
  31365. };
  31366. /**
  31367. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31368. * @param copyWhenShared If 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.
  31369. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31370. * @returns the indices array or an empty array if the mesh has no geometry
  31371. */
  31372. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31373. if (!this._geometry) {
  31374. return [];
  31375. }
  31376. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31377. };
  31378. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31379. get: function () {
  31380. return this._masterMesh !== null && this._masterMesh !== undefined;
  31381. },
  31382. enumerable: true,
  31383. configurable: true
  31384. });
  31385. /**
  31386. * Determine if the current mesh is ready to be rendered
  31387. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31388. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31389. * @returns true if all associated assets are ready (material, textures, shaders)
  31390. */
  31391. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31392. if (completeCheck === void 0) { completeCheck = false; }
  31393. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31394. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31395. return false;
  31396. }
  31397. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31398. return false;
  31399. }
  31400. if (!this.subMeshes || this.subMeshes.length === 0) {
  31401. return true;
  31402. }
  31403. if (!completeCheck) {
  31404. return true;
  31405. }
  31406. var engine = this.getEngine();
  31407. var scene = this.getScene();
  31408. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31409. this.computeWorldMatrix();
  31410. var mat = this.material || scene.defaultMaterial;
  31411. if (mat) {
  31412. if (mat.storeEffectOnSubMeshes) {
  31413. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31414. var subMesh = _a[_i];
  31415. var effectiveMaterial = subMesh.getMaterial();
  31416. if (effectiveMaterial) {
  31417. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31418. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31419. return false;
  31420. }
  31421. }
  31422. else {
  31423. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31424. return false;
  31425. }
  31426. }
  31427. }
  31428. }
  31429. }
  31430. else {
  31431. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31432. return false;
  31433. }
  31434. }
  31435. }
  31436. // Shadows
  31437. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31438. var light = _c[_b];
  31439. var generator = light.getShadowGenerator();
  31440. if (generator) {
  31441. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31442. var subMesh = _e[_d];
  31443. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31444. return false;
  31445. }
  31446. }
  31447. }
  31448. }
  31449. // LOD
  31450. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31451. var lod = _g[_f];
  31452. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31453. return false;
  31454. }
  31455. }
  31456. return true;
  31457. };
  31458. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31459. /**
  31460. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31461. * This property is pertinent only for updatable parametric shapes.
  31462. */
  31463. get: function () {
  31464. return this._areNormalsFrozen;
  31465. },
  31466. enumerable: true,
  31467. configurable: true
  31468. });
  31469. /**
  31470. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31471. * It has no effect at all on other shapes.
  31472. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31473. * Returns the Mesh.
  31474. */
  31475. Mesh.prototype.freezeNormals = function () {
  31476. this._areNormalsFrozen = true;
  31477. return this;
  31478. };
  31479. /**
  31480. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31481. * It has no effect at all on other shapes.
  31482. * It reactivates the mesh normals computation if it was previously frozen.
  31483. * Returns the Mesh.
  31484. */
  31485. Mesh.prototype.unfreezeNormals = function () {
  31486. this._areNormalsFrozen = false;
  31487. return this;
  31488. };
  31489. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31490. /**
  31491. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31492. */
  31493. set: function (count) {
  31494. this._overridenInstanceCount = count;
  31495. },
  31496. enumerable: true,
  31497. configurable: true
  31498. });
  31499. // Methods
  31500. /** @hidden */
  31501. Mesh.prototype._preActivate = function () {
  31502. var sceneRenderId = this.getScene().getRenderId();
  31503. if (this._preActivateId === sceneRenderId) {
  31504. return this;
  31505. }
  31506. this._preActivateId = sceneRenderId;
  31507. this._visibleInstances = null;
  31508. return this;
  31509. };
  31510. /** @hidden */
  31511. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31512. if (this._visibleInstances) {
  31513. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31514. }
  31515. return this;
  31516. };
  31517. /** @hidden */
  31518. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31519. if (!this._visibleInstances) {
  31520. this._visibleInstances = {};
  31521. this._visibleInstances.defaultRenderId = renderId;
  31522. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31523. }
  31524. if (!this._visibleInstances[renderId]) {
  31525. this._visibleInstances[renderId] = new Array();
  31526. }
  31527. this._visibleInstances[renderId].push(instance);
  31528. return this;
  31529. };
  31530. /**
  31531. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31532. * This means the mesh underlying bounding box and sphere are recomputed.
  31533. * Returns the Mesh.
  31534. */
  31535. Mesh.prototype.refreshBoundingInfo = function () {
  31536. return this._refreshBoundingInfo(false);
  31537. };
  31538. /** @hidden */
  31539. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31540. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31541. return this;
  31542. }
  31543. var data = this._getPositionData(applySkeleton);
  31544. if (data) {
  31545. var bias = this.geometry ? this.geometry.boundingBias : null;
  31546. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31547. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31548. }
  31549. if (this.subMeshes) {
  31550. for (var index = 0; index < this.subMeshes.length; index++) {
  31551. this.subMeshes[index].refreshBoundingInfo();
  31552. }
  31553. }
  31554. this._updateBoundingInfo();
  31555. return this;
  31556. };
  31557. Mesh.prototype._getPositionData = function (applySkeleton) {
  31558. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31559. if (data && applySkeleton && this.skeleton) {
  31560. data = BABYLON.Tools.Slice(data);
  31561. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31562. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31563. if (matricesWeightsData && matricesIndicesData) {
  31564. var needExtras = this.numBoneInfluencers > 4;
  31565. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31566. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31567. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31568. var tempVector = BABYLON.Tmp.Vector3[0];
  31569. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31570. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31571. var matWeightIdx = 0;
  31572. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31573. finalMatrix.reset();
  31574. var inf;
  31575. var weight;
  31576. for (inf = 0; inf < 4; inf++) {
  31577. weight = matricesWeightsData[matWeightIdx + inf];
  31578. if (weight > 0) {
  31579. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31580. finalMatrix.addToSelf(tempMatrix);
  31581. }
  31582. }
  31583. if (needExtras) {
  31584. for (inf = 0; inf < 4; inf++) {
  31585. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31586. if (weight > 0) {
  31587. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31588. finalMatrix.addToSelf(tempMatrix);
  31589. }
  31590. }
  31591. }
  31592. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31593. tempVector.toArray(data, index);
  31594. }
  31595. }
  31596. }
  31597. return data;
  31598. };
  31599. /** @hidden */
  31600. Mesh.prototype._createGlobalSubMesh = function (force) {
  31601. var totalVertices = this.getTotalVertices();
  31602. if (!totalVertices || !this.getIndices()) {
  31603. return null;
  31604. }
  31605. // Check if we need to recreate the submeshes
  31606. if (this.subMeshes && this.subMeshes.length > 0) {
  31607. var ib = this.getIndices();
  31608. if (!ib) {
  31609. return null;
  31610. }
  31611. var totalIndices = ib.length;
  31612. var needToRecreate = false;
  31613. if (force) {
  31614. needToRecreate = true;
  31615. }
  31616. else {
  31617. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31618. var submesh = _a[_i];
  31619. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31620. needToRecreate = true;
  31621. break;
  31622. }
  31623. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31624. needToRecreate = true;
  31625. break;
  31626. }
  31627. }
  31628. }
  31629. if (!needToRecreate) {
  31630. return this.subMeshes[0];
  31631. }
  31632. }
  31633. this.releaseSubMeshes();
  31634. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31635. };
  31636. Mesh.prototype.subdivide = function (count) {
  31637. if (count < 1) {
  31638. return;
  31639. }
  31640. var totalIndices = this.getTotalIndices();
  31641. var subdivisionSize = (totalIndices / count) | 0;
  31642. var offset = 0;
  31643. // Ensure that subdivisionSize is a multiple of 3
  31644. while (subdivisionSize % 3 !== 0) {
  31645. subdivisionSize++;
  31646. }
  31647. this.releaseSubMeshes();
  31648. for (var index = 0; index < count; index++) {
  31649. if (offset >= totalIndices) {
  31650. break;
  31651. }
  31652. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31653. offset += subdivisionSize;
  31654. }
  31655. this.synchronizeInstances();
  31656. };
  31657. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31658. if (updatable === void 0) { updatable = false; }
  31659. if (!this._geometry) {
  31660. var vertexData = new BABYLON.VertexData();
  31661. vertexData.set(data, kind);
  31662. var scene = this.getScene();
  31663. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31664. }
  31665. else {
  31666. this._geometry.setVerticesData(kind, data, updatable, stride);
  31667. }
  31668. return this;
  31669. };
  31670. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31671. if (updatable === void 0) { updatable = true; }
  31672. var vb = this.getVertexBuffer(kind);
  31673. if (!vb || vb.isUpdatable() === updatable) {
  31674. return;
  31675. }
  31676. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31677. };
  31678. /**
  31679. * Sets the mesh VertexBuffer.
  31680. * Returns the Mesh.
  31681. */
  31682. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31683. if (!this._geometry) {
  31684. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31685. }
  31686. this._geometry.setVerticesBuffer(buffer);
  31687. return this;
  31688. };
  31689. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31690. if (!this._geometry) {
  31691. return this;
  31692. }
  31693. if (!makeItUnique) {
  31694. this._geometry.updateVerticesData(kind, data, updateExtends);
  31695. }
  31696. else {
  31697. this.makeGeometryUnique();
  31698. this.updateVerticesData(kind, data, updateExtends, false);
  31699. }
  31700. return this;
  31701. };
  31702. /**
  31703. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31704. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31705. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31706. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31707. * Returns the Mesh.
  31708. */
  31709. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31710. if (computeNormals === void 0) { computeNormals = true; }
  31711. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31712. if (!positions) {
  31713. return this;
  31714. }
  31715. positionFunction(positions);
  31716. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31717. if (computeNormals) {
  31718. var indices = this.getIndices();
  31719. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31720. if (!normals) {
  31721. return this;
  31722. }
  31723. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31724. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31725. }
  31726. return this;
  31727. };
  31728. /**
  31729. * Creates a un-shared specific occurence of the geometry for the mesh.
  31730. * Returns the Mesh.
  31731. */
  31732. Mesh.prototype.makeGeometryUnique = function () {
  31733. if (!this._geometry) {
  31734. return this;
  31735. }
  31736. var oldGeometry = this._geometry;
  31737. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31738. oldGeometry.releaseForMesh(this, true);
  31739. geometry.applyToMesh(this);
  31740. return this;
  31741. };
  31742. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31743. if (totalVertices === void 0) { totalVertices = null; }
  31744. if (updatable === void 0) { updatable = false; }
  31745. if (!this._geometry) {
  31746. var vertexData = new BABYLON.VertexData();
  31747. vertexData.indices = indices;
  31748. var scene = this.getScene();
  31749. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31750. }
  31751. else {
  31752. this._geometry.setIndices(indices, totalVertices, updatable);
  31753. }
  31754. return this;
  31755. };
  31756. /**
  31757. * Update the current index buffer
  31758. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31759. * Returns the Mesh.
  31760. */
  31761. Mesh.prototype.updateIndices = function (indices, offset) {
  31762. if (!this._geometry) {
  31763. return this;
  31764. }
  31765. this._geometry.updateIndices(indices, offset);
  31766. return this;
  31767. };
  31768. /**
  31769. * Invert the geometry to move from a right handed system to a left handed one.
  31770. * Returns the Mesh.
  31771. */
  31772. Mesh.prototype.toLeftHanded = function () {
  31773. if (!this._geometry) {
  31774. return this;
  31775. }
  31776. this._geometry.toLeftHanded();
  31777. return this;
  31778. };
  31779. /** @hidden */
  31780. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31781. if (!this._geometry) {
  31782. return this;
  31783. }
  31784. var engine = this.getScene().getEngine();
  31785. // Wireframe
  31786. var indexToBind;
  31787. if (this._unIndexed) {
  31788. indexToBind = null;
  31789. }
  31790. else {
  31791. switch (fillMode) {
  31792. case BABYLON.Material.PointFillMode:
  31793. indexToBind = null;
  31794. break;
  31795. case BABYLON.Material.WireFrameFillMode:
  31796. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31797. break;
  31798. default:
  31799. case BABYLON.Material.TriangleFillMode:
  31800. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31801. break;
  31802. }
  31803. }
  31804. // VBOs
  31805. this._geometry._bind(effect, indexToBind);
  31806. return this;
  31807. };
  31808. /** @hidden */
  31809. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31810. if (alternate === void 0) { alternate = false; }
  31811. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31812. return this;
  31813. }
  31814. if (this._onBeforeDrawObservable) {
  31815. this._onBeforeDrawObservable.notifyObservers(this);
  31816. }
  31817. var scene = this.getScene();
  31818. var engine = scene.getEngine();
  31819. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31820. // or triangles as points
  31821. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31822. }
  31823. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31824. // Triangles as wireframe
  31825. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31826. }
  31827. else {
  31828. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31829. }
  31830. if (scene._isAlternateRenderingEnabled && !alternate) {
  31831. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31832. if (!effect || !scene.activeCamera) {
  31833. return this;
  31834. }
  31835. scene._switchToAlternateCameraConfiguration(true);
  31836. this._effectiveMaterial.bindView(effect);
  31837. this._effectiveMaterial.bindViewProjection(effect);
  31838. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31839. this._draw(subMesh, fillMode, instancesCount, true);
  31840. engine.setViewport(scene.activeCamera.viewport);
  31841. scene._switchToAlternateCameraConfiguration(false);
  31842. this._effectiveMaterial.bindView(effect);
  31843. this._effectiveMaterial.bindViewProjection(effect);
  31844. }
  31845. return this;
  31846. };
  31847. /**
  31848. * Registers for this mesh a javascript function called just before the rendering process.
  31849. * This function is passed the current mesh.
  31850. * Return the Mesh.
  31851. */
  31852. Mesh.prototype.registerBeforeRender = function (func) {
  31853. this.onBeforeRenderObservable.add(func);
  31854. return this;
  31855. };
  31856. /**
  31857. * Disposes a previously registered javascript function called before the rendering.
  31858. * This function is passed the current mesh.
  31859. * Returns the Mesh.
  31860. */
  31861. Mesh.prototype.unregisterBeforeRender = function (func) {
  31862. this.onBeforeRenderObservable.removeCallback(func);
  31863. return this;
  31864. };
  31865. /**
  31866. * Registers for this mesh a javascript function called just after the rendering is complete.
  31867. * This function is passed the current mesh.
  31868. * Returns the Mesh.
  31869. */
  31870. Mesh.prototype.registerAfterRender = function (func) {
  31871. this.onAfterRenderObservable.add(func);
  31872. return this;
  31873. };
  31874. /**
  31875. * Disposes a previously registered javascript function called after the rendering.
  31876. * This function is passed the current mesh.
  31877. * Return the Mesh.
  31878. */
  31879. Mesh.prototype.unregisterAfterRender = function (func) {
  31880. this.onAfterRenderObservable.removeCallback(func);
  31881. return this;
  31882. };
  31883. /** @hidden */
  31884. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31885. var scene = this.getScene();
  31886. this._batchCache.mustReturn = false;
  31887. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31888. this._batchCache.visibleInstances[subMeshId] = null;
  31889. if (this._visibleInstances) {
  31890. var currentRenderId = scene.getRenderId();
  31891. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31892. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31893. var selfRenderId = this._renderId;
  31894. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31895. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31896. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31897. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31898. }
  31899. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31900. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31901. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31902. this._batchCache.mustReturn = true;
  31903. return this._batchCache;
  31904. }
  31905. if (currentRenderId !== selfRenderId) {
  31906. this._batchCache.renderSelf[subMeshId] = false;
  31907. }
  31908. }
  31909. this._renderIdForInstances[subMeshId] = currentRenderId;
  31910. }
  31911. return this._batchCache;
  31912. };
  31913. /** @hidden */
  31914. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31915. var visibleInstances = batch.visibleInstances[subMesh._id];
  31916. if (!visibleInstances) {
  31917. return this;
  31918. }
  31919. var matricesCount = visibleInstances.length + 1;
  31920. var bufferSize = matricesCount * 16 * 4;
  31921. var currentInstancesBufferSize = this._instancesBufferSize;
  31922. var instancesBuffer = this._instancesBuffer;
  31923. while (this._instancesBufferSize < bufferSize) {
  31924. this._instancesBufferSize *= 2;
  31925. }
  31926. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31927. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31928. }
  31929. var offset = 0;
  31930. var instancesCount = 0;
  31931. var world = this.getWorldMatrix();
  31932. if (batch.renderSelf[subMesh._id]) {
  31933. world.copyToArray(this._instancesData, offset);
  31934. offset += 16;
  31935. instancesCount++;
  31936. }
  31937. if (visibleInstances) {
  31938. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31939. var instance = visibleInstances[instanceIndex];
  31940. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31941. offset += 16;
  31942. instancesCount++;
  31943. }
  31944. }
  31945. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31946. if (instancesBuffer) {
  31947. instancesBuffer.dispose();
  31948. }
  31949. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31950. this._instancesBuffer = instancesBuffer;
  31951. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31952. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31953. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31954. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31955. }
  31956. else {
  31957. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31958. }
  31959. this._bind(subMesh, effect, fillMode);
  31960. this._draw(subMesh, fillMode, instancesCount);
  31961. engine.unbindInstanceAttributes();
  31962. return this;
  31963. };
  31964. /** @hidden */
  31965. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31966. var scene = this.getScene();
  31967. var engine = scene.getEngine();
  31968. if (hardwareInstancedRendering) {
  31969. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31970. }
  31971. else {
  31972. if (batch.renderSelf[subMesh._id]) {
  31973. // Draw
  31974. if (onBeforeDraw) {
  31975. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31976. }
  31977. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31978. }
  31979. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31980. if (visibleInstancesForSubMesh) {
  31981. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31982. var instance = visibleInstancesForSubMesh[instanceIndex];
  31983. // World
  31984. var world = instance.getWorldMatrix();
  31985. if (onBeforeDraw) {
  31986. onBeforeDraw(true, world, effectiveMaterial);
  31987. }
  31988. // Draw
  31989. this._draw(subMesh, fillMode);
  31990. }
  31991. }
  31992. }
  31993. return this;
  31994. };
  31995. /**
  31996. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  31997. * @param subMesh defines the subMesh to render
  31998. * @param enableAlphaMode defines if alpha mode can be changed
  31999. * @returns the current mesh
  32000. */
  32001. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32002. this._checkOcclusionQuery();
  32003. if (this._isOccluded) {
  32004. return this;
  32005. }
  32006. var scene = this.getScene();
  32007. // Managing instances
  32008. var batch = this._getInstancesRenderList(subMesh._id);
  32009. if (batch.mustReturn) {
  32010. return this;
  32011. }
  32012. // Checking geometry state
  32013. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32014. return this;
  32015. }
  32016. if (this._onBeforeRenderObservable) {
  32017. this._onBeforeRenderObservable.notifyObservers(this);
  32018. }
  32019. var engine = scene.getEngine();
  32020. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32021. // Material
  32022. var material = subMesh.getMaterial();
  32023. if (!material) {
  32024. return this;
  32025. }
  32026. this._effectiveMaterial = material;
  32027. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32028. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32029. return this;
  32030. }
  32031. }
  32032. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32033. return this;
  32034. }
  32035. // Alpha mode
  32036. if (enableAlphaMode) {
  32037. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32038. }
  32039. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32040. var step = _a[_i];
  32041. step.action(this, subMesh, batch);
  32042. }
  32043. var effect;
  32044. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32045. effect = subMesh.effect;
  32046. }
  32047. else {
  32048. effect = this._effectiveMaterial.getEffect();
  32049. }
  32050. if (!effect) {
  32051. return this;
  32052. }
  32053. var sideOrientation = this.overrideMaterialSideOrientation;
  32054. if (sideOrientation == null) {
  32055. sideOrientation = this._effectiveMaterial.sideOrientation;
  32056. if (this._getWorldMatrixDeterminant() < 0) {
  32057. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32058. }
  32059. }
  32060. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32061. if (this._effectiveMaterial.forceDepthWrite) {
  32062. engine.setDepthWrite(true);
  32063. }
  32064. // Bind
  32065. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32066. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32067. this._bind(subMesh, effect, fillMode);
  32068. }
  32069. var world = this.getWorldMatrix();
  32070. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32071. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32072. }
  32073. else {
  32074. this._effectiveMaterial.bind(world, this);
  32075. }
  32076. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32077. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32078. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32079. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32080. }
  32081. // Draw
  32082. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32083. // Unbind
  32084. this._effectiveMaterial.unbind();
  32085. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32086. var step = _c[_b];
  32087. step.action(this, subMesh, batch);
  32088. }
  32089. if (this._onAfterRenderObservable) {
  32090. this._onAfterRenderObservable.notifyObservers(this);
  32091. }
  32092. return this;
  32093. };
  32094. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32095. if (isInstance && effectiveMaterial) {
  32096. effectiveMaterial.bindOnlyWorldMatrix(world);
  32097. }
  32098. };
  32099. /**
  32100. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32101. */
  32102. Mesh.prototype.getEmittedParticleSystems = function () {
  32103. var results = new Array();
  32104. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32105. var particleSystem = this.getScene().particleSystems[index];
  32106. if (particleSystem.emitter === this) {
  32107. results.push(particleSystem);
  32108. }
  32109. }
  32110. return results;
  32111. };
  32112. /**
  32113. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32114. */
  32115. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32116. var results = new Array();
  32117. var descendants = this.getDescendants();
  32118. descendants.push(this);
  32119. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32120. var particleSystem = this.getScene().particleSystems[index];
  32121. var emitter = particleSystem.emitter;
  32122. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32123. results.push(particleSystem);
  32124. }
  32125. }
  32126. return results;
  32127. };
  32128. /**
  32129. * Normalize matrix weights so that all vertices have a total weight set to 1
  32130. */
  32131. Mesh.prototype.cleanMatrixWeights = function () {
  32132. var epsilon = 1e-3;
  32133. var noInfluenceBoneIndex = 0.0;
  32134. if (this.skeleton) {
  32135. noInfluenceBoneIndex = this.skeleton.bones.length;
  32136. }
  32137. else {
  32138. return;
  32139. }
  32140. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32141. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32142. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32143. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32144. var influencers = this.numBoneInfluencers;
  32145. var size = matricesWeights.length;
  32146. for (var i = 0; i < size; i += 4) {
  32147. var weight = 0.0;
  32148. var firstZeroWeight = -1;
  32149. for (var j = 0; j < 4; j++) {
  32150. var w = matricesWeights[i + j];
  32151. weight += w;
  32152. if (w < epsilon && firstZeroWeight < 0) {
  32153. firstZeroWeight = j;
  32154. }
  32155. }
  32156. if (matricesWeightsExtra) {
  32157. for (var j = 0; j < 4; j++) {
  32158. var w = matricesWeightsExtra[i + j];
  32159. weight += w;
  32160. if (w < epsilon && firstZeroWeight < 0) {
  32161. firstZeroWeight = j + 4;
  32162. }
  32163. }
  32164. }
  32165. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32166. firstZeroWeight = influencers - 1;
  32167. }
  32168. if (weight > epsilon) {
  32169. var mweight = 1.0 / weight;
  32170. for (var j = 0; j < 4; j++) {
  32171. matricesWeights[i + j] *= mweight;
  32172. }
  32173. if (matricesWeightsExtra) {
  32174. for (var j = 0; j < 4; j++) {
  32175. matricesWeightsExtra[i + j] *= mweight;
  32176. }
  32177. }
  32178. }
  32179. else {
  32180. if (firstZeroWeight >= 4) {
  32181. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32182. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32183. }
  32184. else {
  32185. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32186. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32187. }
  32188. }
  32189. }
  32190. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32191. if (matricesIndicesExtra) {
  32192. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32193. }
  32194. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32195. if (matricesWeightsExtra) {
  32196. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32197. }
  32198. };
  32199. /** @hidden */
  32200. Mesh.prototype._checkDelayState = function () {
  32201. var scene = this.getScene();
  32202. if (this._geometry) {
  32203. this._geometry.load(scene);
  32204. }
  32205. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32207. this._queueLoad(scene);
  32208. }
  32209. return this;
  32210. };
  32211. Mesh.prototype._queueLoad = function (scene) {
  32212. var _this = this;
  32213. scene._addPendingData(this);
  32214. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32215. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32216. if (data instanceof ArrayBuffer) {
  32217. _this._delayLoadingFunction(data, _this);
  32218. }
  32219. else {
  32220. _this._delayLoadingFunction(JSON.parse(data), _this);
  32221. }
  32222. _this.instances.forEach(function (instance) {
  32223. instance._syncSubMeshes();
  32224. });
  32225. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32226. scene._removePendingData(_this);
  32227. }, function () { }, scene.database, getBinaryData);
  32228. return this;
  32229. };
  32230. /**
  32231. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32232. * A mesh is in the frustum if its bounding box intersects the frustum
  32233. * @param frustumPlanes defines the frustum to test
  32234. * @returns true if the mesh is in the frustum planes
  32235. */
  32236. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32237. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32238. return false;
  32239. }
  32240. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32241. return false;
  32242. }
  32243. this._checkDelayState();
  32244. return true;
  32245. };
  32246. /**
  32247. * Sets the mesh material by the material or multiMaterial `id` property.
  32248. * The material `id` is a string identifying the material or the multiMaterial.
  32249. * This method returns the Mesh.
  32250. */
  32251. Mesh.prototype.setMaterialByID = function (id) {
  32252. var materials = this.getScene().materials;
  32253. var index;
  32254. for (index = materials.length - 1; index > -1; index--) {
  32255. if (materials[index].id === id) {
  32256. this.material = materials[index];
  32257. return this;
  32258. }
  32259. }
  32260. // Multi
  32261. var multiMaterials = this.getScene().multiMaterials;
  32262. for (index = multiMaterials.length - 1; index > -1; index--) {
  32263. if (multiMaterials[index].id === id) {
  32264. this.material = multiMaterials[index];
  32265. return this;
  32266. }
  32267. }
  32268. return this;
  32269. };
  32270. /**
  32271. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32272. */
  32273. Mesh.prototype.getAnimatables = function () {
  32274. var results = new Array();
  32275. if (this.material) {
  32276. results.push(this.material);
  32277. }
  32278. if (this.skeleton) {
  32279. results.push(this.skeleton);
  32280. }
  32281. return results;
  32282. };
  32283. /**
  32284. * Modifies the mesh geometry according to the passed transformation matrix.
  32285. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32286. * The mesh normals are modified using the same transformation.
  32287. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32288. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32289. * Returns the Mesh.
  32290. */
  32291. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32292. // Position
  32293. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32294. return this;
  32295. }
  32296. var submeshes = this.subMeshes.splice(0);
  32297. this._resetPointsArrayCache();
  32298. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32299. var temp = new Array();
  32300. var index;
  32301. for (index = 0; index < data.length; index += 3) {
  32302. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32303. }
  32304. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32305. // Normals
  32306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32307. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32308. temp = [];
  32309. for (index = 0; index < data.length; index += 3) {
  32310. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32311. }
  32312. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32313. }
  32314. // flip faces?
  32315. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32316. this.flipFaces();
  32317. }
  32318. // Restore submeshes
  32319. this.releaseSubMeshes();
  32320. this.subMeshes = submeshes;
  32321. return this;
  32322. };
  32323. /**
  32324. * Modifies the mesh geometry according to its own current World Matrix.
  32325. * The mesh World Matrix is then reset.
  32326. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32327. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32328. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32329. * Returns the Mesh.
  32330. */
  32331. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32332. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32333. this.scaling.copyFromFloats(1, 1, 1);
  32334. this.position.copyFromFloats(0, 0, 0);
  32335. this.rotation.copyFromFloats(0, 0, 0);
  32336. //only if quaternion is already set
  32337. if (this.rotationQuaternion) {
  32338. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32339. }
  32340. this._worldMatrix = BABYLON.Matrix.Identity();
  32341. return this;
  32342. };
  32343. Object.defineProperty(Mesh.prototype, "_positions", {
  32344. // Cache
  32345. get: function () {
  32346. if (this._geometry) {
  32347. return this._geometry._positions;
  32348. }
  32349. return null;
  32350. },
  32351. enumerable: true,
  32352. configurable: true
  32353. });
  32354. /** @hidden */
  32355. Mesh.prototype._resetPointsArrayCache = function () {
  32356. if (this._geometry) {
  32357. this._geometry._resetPointsArrayCache();
  32358. }
  32359. return this;
  32360. };
  32361. /** @hidden */
  32362. Mesh.prototype._generatePointsArray = function () {
  32363. if (this._geometry) {
  32364. return this._geometry._generatePointsArray();
  32365. }
  32366. return false;
  32367. };
  32368. /**
  32369. * Returns a new Mesh object generated from the current mesh properties.
  32370. * This method must not get confused with createInstance().
  32371. * The parameter `name` is a string, the name given to the new mesh.
  32372. * The optional parameter `newParent` can be any Node object (default `null`).
  32373. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32374. * 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.
  32375. */
  32376. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32377. if (name === void 0) { name = ""; }
  32378. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32379. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32380. };
  32381. /**
  32382. * Releases resources associated with this mesh.
  32383. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32384. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32385. */
  32386. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32387. var _this = this;
  32388. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32389. this.morphTargetManager = null;
  32390. if (this._geometry) {
  32391. this._geometry.releaseForMesh(this, true);
  32392. }
  32393. if (this._onBeforeDrawObservable) {
  32394. this._onBeforeDrawObservable.clear();
  32395. }
  32396. if (this._onBeforeRenderObservable) {
  32397. this._onBeforeRenderObservable.clear();
  32398. }
  32399. if (this._onAfterRenderObservable) {
  32400. this._onAfterRenderObservable.clear();
  32401. }
  32402. // Sources
  32403. var meshes = this.getScene().meshes;
  32404. meshes.forEach(function (abstractMesh) {
  32405. var mesh = abstractMesh;
  32406. if (mesh._source && mesh._source === _this) {
  32407. mesh._source = null;
  32408. }
  32409. });
  32410. this._source = null;
  32411. // Instances
  32412. if (this._instancesBuffer) {
  32413. this._instancesBuffer.dispose();
  32414. this._instancesBuffer = null;
  32415. }
  32416. while (this.instances.length) {
  32417. this.instances[0].dispose();
  32418. }
  32419. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32420. };
  32421. /**
  32422. * Modifies the mesh geometry according to a displacement map.
  32423. * 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.
  32424. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32425. * This method returns nothing.
  32426. * @param url is a string, the URL from the image file is to be downloaded.
  32427. * @param minHeight is the lower limit of the displacement.
  32428. * @param maxHeight is the upper limit of the displacement.
  32429. * @param 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.
  32430. * @param uvOffset is an optional vector2 used to offset UV.
  32431. * @param uvScale is an optional vector2 used to scale UV.
  32432. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32433. * @returns the Mesh.
  32434. */
  32435. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32436. var _this = this;
  32437. if (forceUpdate === void 0) { forceUpdate = false; }
  32438. var scene = this.getScene();
  32439. var onload = function (img) {
  32440. // Getting height map data
  32441. var canvas = document.createElement("canvas");
  32442. var context = canvas.getContext("2d");
  32443. var heightMapWidth = img.width;
  32444. var heightMapHeight = img.height;
  32445. canvas.width = heightMapWidth;
  32446. canvas.height = heightMapHeight;
  32447. context.drawImage(img, 0, 0);
  32448. // Create VertexData from map data
  32449. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32450. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32451. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32452. //execute success callback, if set
  32453. if (onSuccess) {
  32454. onSuccess(_this);
  32455. }
  32456. };
  32457. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32458. return this;
  32459. };
  32460. /**
  32461. * Modifies the mesh geometry according to a displacementMap buffer.
  32462. * 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.
  32463. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32464. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32465. * @param heightMapWidth is the width of the buffer image.
  32466. * @param heightMapHeight is the height of the buffer image.
  32467. * @param minHeight is the lower limit of the displacement.
  32468. * @param maxHeight is the upper limit of the displacement.
  32469. * @param 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.
  32470. * @param uvOffset is an optional vector2 used to offset UV.
  32471. * @param uvScale is an optional vector2 used to scale UV.
  32472. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32473. * @returns the Mesh.
  32474. */
  32475. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32476. if (forceUpdate === void 0) { forceUpdate = false; }
  32477. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32478. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32479. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32480. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32481. return this;
  32482. }
  32483. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32484. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32485. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32486. var position = BABYLON.Vector3.Zero();
  32487. var normal = BABYLON.Vector3.Zero();
  32488. var uv = BABYLON.Vector2.Zero();
  32489. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32490. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32491. for (var index = 0; index < positions.length; index += 3) {
  32492. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32493. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32494. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32495. // Compute height
  32496. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32497. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32498. var pos = (u + v * heightMapWidth) * 4;
  32499. var r = buffer[pos] / 255.0;
  32500. var g = buffer[pos + 1] / 255.0;
  32501. var b = buffer[pos + 2] / 255.0;
  32502. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32503. normal.normalize();
  32504. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32505. position = position.add(normal);
  32506. position.toArray(positions, index);
  32507. }
  32508. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32509. if (forceUpdate) {
  32510. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32511. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32512. }
  32513. else {
  32514. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32515. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32516. }
  32517. return this;
  32518. };
  32519. /**
  32520. * Modify the mesh to get a flat shading rendering.
  32521. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32522. * This method returns the Mesh.
  32523. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32524. */
  32525. Mesh.prototype.convertToFlatShadedMesh = function () {
  32526. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32527. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32528. var kinds = this.getVerticesDataKinds();
  32529. var vbs = {};
  32530. var data = {};
  32531. var newdata = {};
  32532. var updatableNormals = false;
  32533. var kindIndex;
  32534. var kind;
  32535. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32536. kind = kinds[kindIndex];
  32537. var vertexBuffer = this.getVertexBuffer(kind);
  32538. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32539. updatableNormals = vertexBuffer.isUpdatable();
  32540. kinds.splice(kindIndex, 1);
  32541. kindIndex--;
  32542. continue;
  32543. }
  32544. vbs[kind] = vertexBuffer;
  32545. data[kind] = vbs[kind].getData();
  32546. newdata[kind] = [];
  32547. }
  32548. // Save previous submeshes
  32549. var previousSubmeshes = this.subMeshes.slice(0);
  32550. var indices = this.getIndices();
  32551. var totalIndices = this.getTotalIndices();
  32552. // Generating unique vertices per face
  32553. var index;
  32554. for (index = 0; index < totalIndices; index++) {
  32555. var vertexIndex = indices[index];
  32556. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32557. kind = kinds[kindIndex];
  32558. var stride = vbs[kind].getStrideSize();
  32559. for (var offset = 0; offset < stride; offset++) {
  32560. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32561. }
  32562. }
  32563. }
  32564. // Updating faces & normal
  32565. var normals = [];
  32566. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32567. for (index = 0; index < totalIndices; index += 3) {
  32568. indices[index] = index;
  32569. indices[index + 1] = index + 1;
  32570. indices[index + 2] = index + 2;
  32571. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32572. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32573. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32574. var p1p2 = p1.subtract(p2);
  32575. var p3p2 = p3.subtract(p2);
  32576. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32577. // Store same normals for every vertex
  32578. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32579. normals.push(normal.x);
  32580. normals.push(normal.y);
  32581. normals.push(normal.z);
  32582. }
  32583. }
  32584. this.setIndices(indices);
  32585. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32586. // Updating vertex buffers
  32587. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32588. kind = kinds[kindIndex];
  32589. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32590. }
  32591. // Updating submeshes
  32592. this.releaseSubMeshes();
  32593. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32594. var previousOne = previousSubmeshes[submeshIndex];
  32595. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32596. }
  32597. this.synchronizeInstances();
  32598. return this;
  32599. };
  32600. /**
  32601. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32602. * In other words, more vertices, no more indices and a single bigger VBO.
  32603. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32604. * Returns the Mesh.
  32605. */
  32606. Mesh.prototype.convertToUnIndexedMesh = function () {
  32607. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32608. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32609. var kinds = this.getVerticesDataKinds();
  32610. var vbs = {};
  32611. var data = {};
  32612. var newdata = {};
  32613. var kindIndex;
  32614. var kind;
  32615. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32616. kind = kinds[kindIndex];
  32617. var vertexBuffer = this.getVertexBuffer(kind);
  32618. vbs[kind] = vertexBuffer;
  32619. data[kind] = vbs[kind].getData();
  32620. newdata[kind] = [];
  32621. }
  32622. // Save previous submeshes
  32623. var previousSubmeshes = this.subMeshes.slice(0);
  32624. var indices = this.getIndices();
  32625. var totalIndices = this.getTotalIndices();
  32626. // Generating unique vertices per face
  32627. var index;
  32628. for (index = 0; index < totalIndices; index++) {
  32629. var vertexIndex = indices[index];
  32630. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32631. kind = kinds[kindIndex];
  32632. var stride = vbs[kind].getStrideSize();
  32633. for (var offset = 0; offset < stride; offset++) {
  32634. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32635. }
  32636. }
  32637. }
  32638. // Updating indices
  32639. for (index = 0; index < totalIndices; index += 3) {
  32640. indices[index] = index;
  32641. indices[index + 1] = index + 1;
  32642. indices[index + 2] = index + 2;
  32643. }
  32644. this.setIndices(indices);
  32645. // Updating vertex buffers
  32646. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32647. kind = kinds[kindIndex];
  32648. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32649. }
  32650. // Updating submeshes
  32651. this.releaseSubMeshes();
  32652. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32653. var previousOne = previousSubmeshes[submeshIndex];
  32654. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32655. }
  32656. this._unIndexed = true;
  32657. this.synchronizeInstances();
  32658. return this;
  32659. };
  32660. /**
  32661. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32662. * This method returns the Mesh.
  32663. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32664. */
  32665. Mesh.prototype.flipFaces = function (flipNormals) {
  32666. if (flipNormals === void 0) { flipNormals = false; }
  32667. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32668. var i;
  32669. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32670. for (i = 0; i < vertex_data.normals.length; i++) {
  32671. vertex_data.normals[i] *= -1;
  32672. }
  32673. }
  32674. if (vertex_data.indices) {
  32675. var temp;
  32676. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32677. // reassign indices
  32678. temp = vertex_data.indices[i + 1];
  32679. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32680. vertex_data.indices[i + 2] = temp;
  32681. }
  32682. }
  32683. vertex_data.applyToMesh(this);
  32684. return this;
  32685. };
  32686. // Instances
  32687. /**
  32688. * Creates a new InstancedMesh object from the mesh model.
  32689. * An instance shares the same properties and the same material than its model.
  32690. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32691. * Only these properties of each instance can then be set individually :
  32692. * - position
  32693. * - rotation
  32694. * - rotationQuaternion
  32695. * - setPivotMatrix
  32696. * - scaling
  32697. *
  32698. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32699. * Warning : this method is not supported for Line mesh and LineSystem
  32700. */
  32701. Mesh.prototype.createInstance = function (name) {
  32702. return new BABYLON.InstancedMesh(name, this);
  32703. };
  32704. /**
  32705. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32706. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32707. * This method returns the Mesh.
  32708. */
  32709. Mesh.prototype.synchronizeInstances = function () {
  32710. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32711. var instance = this.instances[instanceIndex];
  32712. instance._syncSubMeshes();
  32713. }
  32714. return this;
  32715. };
  32716. /**
  32717. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32718. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32719. * This should be used together with the simplification to avoid disappearing triangles.
  32720. * Returns the Mesh.
  32721. * @param successCallback an optional success callback to be called after the optimization finished.
  32722. */
  32723. Mesh.prototype.optimizeIndices = function (successCallback) {
  32724. var _this = this;
  32725. var indices = this.getIndices();
  32726. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32727. if (!positions || !indices) {
  32728. return this;
  32729. }
  32730. var vectorPositions = new Array();
  32731. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32732. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32733. }
  32734. var dupes = new Array();
  32735. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32736. var realPos = vectorPositions.length - 1 - iteration;
  32737. var testedPosition = vectorPositions[realPos];
  32738. for (var j = 0; j < realPos; ++j) {
  32739. var againstPosition = vectorPositions[j];
  32740. if (testedPosition.equals(againstPosition)) {
  32741. dupes[realPos] = j;
  32742. break;
  32743. }
  32744. }
  32745. }, function () {
  32746. for (var i = 0; i < indices.length; ++i) {
  32747. indices[i] = dupes[indices[i]] || indices[i];
  32748. }
  32749. //indices are now reordered
  32750. var originalSubMeshes = _this.subMeshes.slice(0);
  32751. _this.setIndices(indices);
  32752. _this.subMeshes = originalSubMeshes;
  32753. if (successCallback) {
  32754. successCallback(_this);
  32755. }
  32756. });
  32757. return this;
  32758. };
  32759. Mesh.prototype.serialize = function (serializationObject) {
  32760. serializationObject.name = this.name;
  32761. serializationObject.id = this.id;
  32762. serializationObject.type = this.getClassName();
  32763. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32764. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32765. }
  32766. serializationObject.position = this.position.asArray();
  32767. if (this.rotationQuaternion) {
  32768. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32769. }
  32770. else if (this.rotation) {
  32771. serializationObject.rotation = this.rotation.asArray();
  32772. }
  32773. serializationObject.scaling = this.scaling.asArray();
  32774. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32775. serializationObject.isEnabled = this.isEnabled(false);
  32776. serializationObject.isVisible = this.isVisible;
  32777. serializationObject.infiniteDistance = this.infiniteDistance;
  32778. serializationObject.pickable = this.isPickable;
  32779. serializationObject.receiveShadows = this.receiveShadows;
  32780. serializationObject.billboardMode = this.billboardMode;
  32781. serializationObject.visibility = this.visibility;
  32782. serializationObject.checkCollisions = this.checkCollisions;
  32783. serializationObject.isBlocker = this.isBlocker;
  32784. // Parent
  32785. if (this.parent) {
  32786. serializationObject.parentId = this.parent.id;
  32787. }
  32788. // Geometry
  32789. serializationObject.isUnIndexed = this.isUnIndexed;
  32790. var geometry = this._geometry;
  32791. if (geometry) {
  32792. var geometryId = geometry.id;
  32793. serializationObject.geometryId = geometryId;
  32794. // SubMeshes
  32795. serializationObject.subMeshes = [];
  32796. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32797. var subMesh = this.subMeshes[subIndex];
  32798. serializationObject.subMeshes.push({
  32799. materialIndex: subMesh.materialIndex,
  32800. verticesStart: subMesh.verticesStart,
  32801. verticesCount: subMesh.verticesCount,
  32802. indexStart: subMesh.indexStart,
  32803. indexCount: subMesh.indexCount
  32804. });
  32805. }
  32806. }
  32807. // Material
  32808. if (this.material) {
  32809. serializationObject.materialId = this.material.id;
  32810. }
  32811. else {
  32812. this.material = null;
  32813. }
  32814. // Morph targets
  32815. if (this.morphTargetManager) {
  32816. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32817. }
  32818. // Skeleton
  32819. if (this.skeleton) {
  32820. serializationObject.skeletonId = this.skeleton.id;
  32821. }
  32822. // Physics
  32823. //TODO implement correct serialization for physics impostors.
  32824. var impostor = this.getPhysicsImpostor();
  32825. if (impostor) {
  32826. serializationObject.physicsMass = impostor.getParam("mass");
  32827. serializationObject.physicsFriction = impostor.getParam("friction");
  32828. serializationObject.physicsRestitution = impostor.getParam("mass");
  32829. serializationObject.physicsImpostor = impostor.type;
  32830. }
  32831. // Metadata
  32832. if (this.metadata) {
  32833. serializationObject.metadata = this.metadata;
  32834. }
  32835. // Instances
  32836. serializationObject.instances = [];
  32837. for (var index = 0; index < this.instances.length; index++) {
  32838. var instance = this.instances[index];
  32839. if (instance.doNotSerialize) {
  32840. continue;
  32841. }
  32842. var serializationInstance = {
  32843. name: instance.name,
  32844. id: instance.id,
  32845. position: instance.position.asArray(),
  32846. scaling: instance.scaling.asArray()
  32847. };
  32848. if (instance.parent) {
  32849. serializationInstance.parentId = instance.parent.id;
  32850. }
  32851. if (instance.rotationQuaternion) {
  32852. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32853. }
  32854. else if (instance.rotation) {
  32855. serializationInstance.rotation = instance.rotation.asArray();
  32856. }
  32857. serializationObject.instances.push(serializationInstance);
  32858. // Animations
  32859. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32860. serializationInstance.ranges = instance.serializeAnimationRanges();
  32861. }
  32862. //
  32863. // Animations
  32864. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32865. serializationObject.ranges = this.serializeAnimationRanges();
  32866. // Layer mask
  32867. serializationObject.layerMask = this.layerMask;
  32868. // Alpha
  32869. serializationObject.alphaIndex = this.alphaIndex;
  32870. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32871. // Overlay
  32872. serializationObject.overlayAlpha = this.overlayAlpha;
  32873. serializationObject.overlayColor = this.overlayColor.asArray();
  32874. serializationObject.renderOverlay = this.renderOverlay;
  32875. // Fog
  32876. serializationObject.applyFog = this.applyFog;
  32877. // Action Manager
  32878. if (this.actionManager) {
  32879. serializationObject.actions = this.actionManager.serialize(this.name);
  32880. }
  32881. };
  32882. /** @hidden */
  32883. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32884. if (!this.geometry) {
  32885. return;
  32886. }
  32887. this._markSubMeshesAsAttributesDirty();
  32888. var morphTargetManager = this._morphTargetManager;
  32889. if (morphTargetManager && morphTargetManager.vertexCount) {
  32890. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32891. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32892. this.morphTargetManager = null;
  32893. return;
  32894. }
  32895. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32896. var morphTarget = morphTargetManager.getActiveTarget(index);
  32897. var positions = morphTarget.getPositions();
  32898. if (!positions) {
  32899. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32900. return;
  32901. }
  32902. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32903. var normals = morphTarget.getNormals();
  32904. if (normals) {
  32905. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32906. }
  32907. var tangents = morphTarget.getTangents();
  32908. if (tangents) {
  32909. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32910. }
  32911. }
  32912. }
  32913. else {
  32914. var index = 0;
  32915. // Positions
  32916. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32917. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32918. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32919. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32920. }
  32921. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32922. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32923. }
  32924. index++;
  32925. }
  32926. }
  32927. };
  32928. // Statics
  32929. /**
  32930. * Returns a new Mesh object parsed from the source provided.
  32931. * The parameter `parsedMesh` is the source.
  32932. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32933. */
  32934. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32935. var mesh;
  32936. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32937. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32938. }
  32939. else {
  32940. mesh = new Mesh(parsedMesh.name, scene);
  32941. }
  32942. mesh.id = parsedMesh.id;
  32943. if (BABYLON.Tags) {
  32944. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32945. }
  32946. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32947. if (parsedMesh.metadata !== undefined) {
  32948. mesh.metadata = parsedMesh.metadata;
  32949. }
  32950. if (parsedMesh.rotationQuaternion) {
  32951. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32952. }
  32953. else if (parsedMesh.rotation) {
  32954. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32955. }
  32956. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32957. if (parsedMesh.localMatrix) {
  32958. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32959. }
  32960. else if (parsedMesh.pivotMatrix) {
  32961. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32962. }
  32963. mesh.setEnabled(parsedMesh.isEnabled);
  32964. mesh.isVisible = parsedMesh.isVisible;
  32965. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32966. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32967. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32968. if (parsedMesh.applyFog !== undefined) {
  32969. mesh.applyFog = parsedMesh.applyFog;
  32970. }
  32971. if (parsedMesh.pickable !== undefined) {
  32972. mesh.isPickable = parsedMesh.pickable;
  32973. }
  32974. if (parsedMesh.alphaIndex !== undefined) {
  32975. mesh.alphaIndex = parsedMesh.alphaIndex;
  32976. }
  32977. mesh.receiveShadows = parsedMesh.receiveShadows;
  32978. mesh.billboardMode = parsedMesh.billboardMode;
  32979. if (parsedMesh.visibility !== undefined) {
  32980. mesh.visibility = parsedMesh.visibility;
  32981. }
  32982. mesh.checkCollisions = parsedMesh.checkCollisions;
  32983. if (parsedMesh.isBlocker !== undefined) {
  32984. mesh.isBlocker = parsedMesh.isBlocker;
  32985. }
  32986. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32987. // freezeWorldMatrix
  32988. if (parsedMesh.freezeWorldMatrix) {
  32989. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32990. }
  32991. // Parent
  32992. if (parsedMesh.parentId) {
  32993. mesh._waitingParentId = parsedMesh.parentId;
  32994. }
  32995. // Actions
  32996. if (parsedMesh.actions !== undefined) {
  32997. mesh._waitingActions = parsedMesh.actions;
  32998. }
  32999. // Overlay
  33000. if (parsedMesh.overlayAlpha !== undefined) {
  33001. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33002. }
  33003. if (parsedMesh.overlayColor !== undefined) {
  33004. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33005. }
  33006. if (parsedMesh.renderOverlay !== undefined) {
  33007. mesh.renderOverlay = parsedMesh.renderOverlay;
  33008. }
  33009. // Geometry
  33010. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33011. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33012. if (parsedMesh.delayLoadingFile) {
  33013. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33014. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33015. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33016. if (parsedMesh._binaryInfo) {
  33017. mesh._binaryInfo = parsedMesh._binaryInfo;
  33018. }
  33019. mesh._delayInfo = [];
  33020. if (parsedMesh.hasUVs) {
  33021. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33022. }
  33023. if (parsedMesh.hasUVs2) {
  33024. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33025. }
  33026. if (parsedMesh.hasUVs3) {
  33027. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33028. }
  33029. if (parsedMesh.hasUVs4) {
  33030. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33031. }
  33032. if (parsedMesh.hasUVs5) {
  33033. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33034. }
  33035. if (parsedMesh.hasUVs6) {
  33036. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33037. }
  33038. if (parsedMesh.hasColors) {
  33039. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33040. }
  33041. if (parsedMesh.hasMatricesIndices) {
  33042. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33043. }
  33044. if (parsedMesh.hasMatricesWeights) {
  33045. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33046. }
  33047. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33048. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33049. mesh._checkDelayState();
  33050. }
  33051. }
  33052. else {
  33053. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33054. }
  33055. // Material
  33056. if (parsedMesh.materialId) {
  33057. mesh.setMaterialByID(parsedMesh.materialId);
  33058. }
  33059. else {
  33060. mesh.material = null;
  33061. }
  33062. // Morph targets
  33063. if (parsedMesh.morphTargetManagerId > -1) {
  33064. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33065. }
  33066. // Skeleton
  33067. if (parsedMesh.skeletonId > -1) {
  33068. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33069. if (parsedMesh.numBoneInfluencers) {
  33070. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33071. }
  33072. }
  33073. // Animations
  33074. if (parsedMesh.animations) {
  33075. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33076. var parsedAnimation = parsedMesh.animations[animationIndex];
  33077. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33078. }
  33079. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33080. }
  33081. if (parsedMesh.autoAnimate) {
  33082. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33083. }
  33084. // Layer Mask
  33085. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33086. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33087. }
  33088. else {
  33089. mesh.layerMask = 0x0FFFFFFF;
  33090. }
  33091. // Physics
  33092. if (parsedMesh.physicsImpostor) {
  33093. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33094. mass: parsedMesh.physicsMass,
  33095. friction: parsedMesh.physicsFriction,
  33096. restitution: parsedMesh.physicsRestitution
  33097. }, scene);
  33098. }
  33099. // Instances
  33100. if (parsedMesh.instances) {
  33101. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33102. var parsedInstance = parsedMesh.instances[index];
  33103. var instance = mesh.createInstance(parsedInstance.name);
  33104. if (parsedInstance.id) {
  33105. instance.id = parsedInstance.id;
  33106. }
  33107. if (BABYLON.Tags) {
  33108. if (parsedInstance.tags) {
  33109. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33110. }
  33111. else {
  33112. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33113. }
  33114. }
  33115. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33116. if (parsedInstance.parentId) {
  33117. instance._waitingParentId = parsedInstance.parentId;
  33118. }
  33119. if (parsedInstance.rotationQuaternion) {
  33120. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33121. }
  33122. else if (parsedInstance.rotation) {
  33123. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33124. }
  33125. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33126. instance.checkCollisions = mesh.checkCollisions;
  33127. if (parsedMesh.animations) {
  33128. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33129. parsedAnimation = parsedMesh.animations[animationIndex];
  33130. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33131. }
  33132. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33133. if (parsedMesh.autoAnimate) {
  33134. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33135. }
  33136. }
  33137. }
  33138. }
  33139. return mesh;
  33140. };
  33141. /**
  33142. * Creates a ribbon mesh.
  33143. * Please consider using the same method from the MeshBuilder class instead.
  33144. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33145. *
  33146. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33147. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33148. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33149. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33150. * 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.
  33151. * 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.
  33152. * 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
  33153. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33154. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33156. */
  33157. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33158. if (closeArray === void 0) { closeArray = false; }
  33159. if (updatable === void 0) { updatable = false; }
  33160. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33161. pathArray: pathArray,
  33162. closeArray: closeArray,
  33163. closePath: closePath,
  33164. offset: offset,
  33165. updatable: updatable,
  33166. sideOrientation: sideOrientation,
  33167. instance: instance
  33168. }, scene);
  33169. };
  33170. /**
  33171. * Creates a plane polygonal mesh. By default, this is a disc.
  33172. * Please consider using the same method from the MeshBuilder class instead.
  33173. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33174. * 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.
  33175. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33176. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33178. */
  33179. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33180. if (scene === void 0) { scene = null; }
  33181. var options = {
  33182. radius: radius,
  33183. tessellation: tessellation,
  33184. sideOrientation: sideOrientation,
  33185. updatable: updatable
  33186. };
  33187. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33188. };
  33189. /**
  33190. * Creates a box mesh.
  33191. * Please consider using the same method from the MeshBuilder class instead.
  33192. * The parameter `size` sets the size (float) of each box side (default 1).
  33193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33194. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33196. */
  33197. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33198. if (scene === void 0) { scene = null; }
  33199. var options = {
  33200. size: size,
  33201. sideOrientation: sideOrientation,
  33202. updatable: updatable
  33203. };
  33204. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33205. };
  33206. /**
  33207. * Creates a sphere mesh.
  33208. * Please consider using the same method from the MeshBuilder class instead.
  33209. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33210. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33211. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33212. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33214. */
  33215. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33216. var options = {
  33217. segments: segments,
  33218. diameterX: diameter,
  33219. diameterY: diameter,
  33220. diameterZ: diameter,
  33221. sideOrientation: sideOrientation,
  33222. updatable: updatable
  33223. };
  33224. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33225. };
  33226. /**
  33227. * Creates a cylinder or a cone mesh.
  33228. * Please consider using the same method from the MeshBuilder class instead.
  33229. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33230. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33231. * 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.
  33232. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33233. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33234. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33235. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33237. */
  33238. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33239. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33240. if (scene !== undefined) {
  33241. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33242. updatable = scene;
  33243. }
  33244. scene = subdivisions;
  33245. subdivisions = 1;
  33246. }
  33247. var options = {
  33248. height: height,
  33249. diameterTop: diameterTop,
  33250. diameterBottom: diameterBottom,
  33251. tessellation: tessellation,
  33252. subdivisions: subdivisions,
  33253. sideOrientation: sideOrientation,
  33254. updatable: updatable
  33255. };
  33256. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33257. };
  33258. // Torus (Code from SharpDX.org)
  33259. /**
  33260. * Creates a torus mesh.
  33261. * Please consider using the same method from the MeshBuilder class instead.
  33262. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33263. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33264. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33266. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33268. */
  33269. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33270. var options = {
  33271. diameter: diameter,
  33272. thickness: thickness,
  33273. tessellation: tessellation,
  33274. sideOrientation: sideOrientation,
  33275. updatable: updatable
  33276. };
  33277. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33278. };
  33279. /**
  33280. * Creates a torus knot mesh.
  33281. * Please consider using the same method from the MeshBuilder class instead.
  33282. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33283. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33284. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33285. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33286. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33287. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33288. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33289. */
  33290. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33291. var options = {
  33292. radius: radius,
  33293. tube: tube,
  33294. radialSegments: radialSegments,
  33295. tubularSegments: tubularSegments,
  33296. p: p,
  33297. q: q,
  33298. sideOrientation: sideOrientation,
  33299. updatable: updatable
  33300. };
  33301. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33302. };
  33303. /**
  33304. * Creates a line mesh.
  33305. * Please consider using the same method from the MeshBuilder class instead.
  33306. * 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.
  33307. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33308. * The parameter `points` is an array successive Vector3.
  33309. * 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
  33310. * When updating an instance, remember that only point positions can change, not the number of points.
  33311. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33312. */
  33313. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33314. if (scene === void 0) { scene = null; }
  33315. if (updatable === void 0) { updatable = false; }
  33316. if (instance === void 0) { instance = null; }
  33317. var options = {
  33318. points: points,
  33319. updatable: updatable,
  33320. instance: instance
  33321. };
  33322. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33323. };
  33324. /**
  33325. * Creates a dashed line mesh.
  33326. * Please consider using the same method from the MeshBuilder class instead.
  33327. * 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.
  33328. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33329. * The parameter `points` is an array successive Vector3.
  33330. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33331. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33332. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33333. * 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
  33334. * When updating an instance, remember that only point positions can change, not the number of points.
  33335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33336. */
  33337. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33338. if (scene === void 0) { scene = null; }
  33339. var options = {
  33340. points: points,
  33341. dashSize: dashSize,
  33342. gapSize: gapSize,
  33343. dashNb: dashNb,
  33344. updatable: updatable,
  33345. instance: instance
  33346. };
  33347. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33348. };
  33349. /**
  33350. * Creates a polygon mesh.
  33351. * Please consider using the same method from the MeshBuilder class instead.
  33352. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33353. * 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.
  33354. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33356. * Remember you can only change the shape positions, not their number when updating a polygon.
  33357. */
  33358. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33359. var options = {
  33360. shape: shape,
  33361. holes: holes,
  33362. updatable: updatable,
  33363. sideOrientation: sideOrientation
  33364. };
  33365. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33366. };
  33367. /**
  33368. * Creates an extruded polygon mesh, with depth in the Y direction.
  33369. * Please consider using the same method from the MeshBuilder class instead.
  33370. */
  33371. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33372. var options = {
  33373. shape: shape,
  33374. holes: holes,
  33375. depth: depth,
  33376. updatable: updatable,
  33377. sideOrientation: sideOrientation
  33378. };
  33379. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33380. };
  33381. /**
  33382. * Creates an extruded shape mesh.
  33383. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33384. * Please consider using the same method from the MeshBuilder class instead.
  33385. *
  33386. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33387. * 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
  33388. * extruded along the Z axis.
  33389. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33390. * 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.
  33391. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33392. * 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
  33393. * 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
  33394. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33395. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33396. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33397. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33398. */
  33399. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33400. if (scene === void 0) { scene = null; }
  33401. var options = {
  33402. shape: shape,
  33403. path: path,
  33404. scale: scale,
  33405. rotation: rotation,
  33406. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33407. sideOrientation: sideOrientation,
  33408. instance: instance,
  33409. updatable: updatable
  33410. };
  33411. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33412. };
  33413. /**
  33414. * Creates an custom extruded shape mesh.
  33415. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33416. * Please consider using the same method from the MeshBuilder class instead.
  33417. *
  33418. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33419. * 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
  33420. * extruded along the Z axis.
  33421. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33422. * 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
  33423. * and the distance of this point from the begining of the path :
  33424. * ```javascript
  33425. * var rotationFunction = function(i, distance) {
  33426. * // do things
  33427. * return rotationValue; }
  33428. * ```
  33429. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33430. * 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
  33431. * and the distance of this point from the begining of the path :
  33432. * ```javascript
  33433. * var scaleFunction = function(i, distance) {
  33434. * // do things
  33435. * return scaleValue;}
  33436. * ```
  33437. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33438. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33439. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33440. * 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
  33441. * 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
  33442. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33443. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33444. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33446. */
  33447. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33448. var options = {
  33449. shape: shape,
  33450. path: path,
  33451. scaleFunction: scaleFunction,
  33452. rotationFunction: rotationFunction,
  33453. ribbonCloseArray: ribbonCloseArray,
  33454. ribbonClosePath: ribbonClosePath,
  33455. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33456. sideOrientation: sideOrientation,
  33457. instance: instance,
  33458. updatable: updatable
  33459. };
  33460. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33461. };
  33462. /**
  33463. * Creates lathe mesh.
  33464. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33465. * Please consider using the same method from the MeshBuilder class instead.
  33466. * 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
  33467. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33468. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33469. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33470. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33471. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33473. */
  33474. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33475. var options = {
  33476. shape: shape,
  33477. radius: radius,
  33478. tessellation: tessellation,
  33479. sideOrientation: sideOrientation,
  33480. updatable: updatable
  33481. };
  33482. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33483. };
  33484. /**
  33485. * Creates a plane mesh.
  33486. * Please consider using the same method from the MeshBuilder class instead.
  33487. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33489. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33490. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33491. */
  33492. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33493. var options = {
  33494. size: size,
  33495. width: size,
  33496. height: size,
  33497. sideOrientation: sideOrientation,
  33498. updatable: updatable
  33499. };
  33500. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33501. };
  33502. /**
  33503. * Creates a ground mesh.
  33504. * Please consider using the same method from the MeshBuilder class instead.
  33505. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33506. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33508. */
  33509. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33510. var options = {
  33511. width: width,
  33512. height: height,
  33513. subdivisions: subdivisions,
  33514. updatable: updatable
  33515. };
  33516. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33517. };
  33518. /**
  33519. * Creates a tiled ground mesh.
  33520. * Please consider using the same method from the MeshBuilder class instead.
  33521. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33522. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33523. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33524. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33525. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33526. * numbers of subdivisions on the ground width and height of each tile.
  33527. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33528. */
  33529. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33530. var options = {
  33531. xmin: xmin,
  33532. zmin: zmin,
  33533. xmax: xmax,
  33534. zmax: zmax,
  33535. subdivisions: subdivisions,
  33536. precision: precision,
  33537. updatable: updatable
  33538. };
  33539. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33540. };
  33541. /**
  33542. * Creates a ground mesh from a height map.
  33543. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33544. * Please consider using the same method from the MeshBuilder class instead.
  33545. * The parameter `url` sets the URL of the height map image resource.
  33546. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33547. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33548. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33549. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33550. * 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).
  33551. * This function is passed the newly built mesh :
  33552. * ```javascript
  33553. * function(mesh) { // do things
  33554. * return; }
  33555. * ```
  33556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33557. */
  33558. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33559. var options = {
  33560. width: width,
  33561. height: height,
  33562. subdivisions: subdivisions,
  33563. minHeight: minHeight,
  33564. maxHeight: maxHeight,
  33565. updatable: updatable,
  33566. onReady: onReady
  33567. };
  33568. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33569. };
  33570. /**
  33571. * Creates a tube mesh.
  33572. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33573. * Please consider using the same method from the MeshBuilder class instead.
  33574. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33575. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33576. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33577. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33578. * 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.
  33579. * It must return a radius value (positive float) :
  33580. * ```javascript
  33581. * var radiusFunction = function(i, distance) {
  33582. * // do things
  33583. * return radius; }
  33584. * ```
  33585. * 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
  33586. * 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
  33587. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33588. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33590. */
  33591. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33592. var options = {
  33593. path: path,
  33594. radius: radius,
  33595. tessellation: tessellation,
  33596. radiusFunction: radiusFunction,
  33597. arc: 1,
  33598. cap: cap,
  33599. updatable: updatable,
  33600. sideOrientation: sideOrientation,
  33601. instance: instance
  33602. };
  33603. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33604. };
  33605. /**
  33606. * Creates a polyhedron mesh.
  33607. * Please consider using the same method from the MeshBuilder class instead.
  33608. * 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
  33609. * to choose the wanted type.
  33610. * The parameter `size` (positive float, default 1) sets the polygon size.
  33611. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33612. * 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`.
  33613. * 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
  33614. * 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)`).
  33615. * 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
  33616. * 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.
  33617. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33618. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33619. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33620. */
  33621. Mesh.CreatePolyhedron = function (name, options, scene) {
  33622. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33623. };
  33624. /**
  33625. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33626. * Please consider using the same method from the MeshBuilder class instead.
  33627. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33628. * 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`).
  33629. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33630. * 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.
  33631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33632. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33634. */
  33635. Mesh.CreateIcoSphere = function (name, options, scene) {
  33636. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33637. };
  33638. /**
  33639. * Creates a decal mesh.
  33640. * Please consider using the same method from the MeshBuilder class instead.
  33641. * 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.
  33642. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33643. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33644. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33645. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33646. */
  33647. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33648. var options = {
  33649. position: position,
  33650. normal: normal,
  33651. size: size,
  33652. angle: angle
  33653. };
  33654. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33655. };
  33656. // Skeletons
  33657. /**
  33658. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33659. */
  33660. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33661. if (!this._sourcePositions) {
  33662. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33663. if (!source) {
  33664. return this._sourcePositions;
  33665. }
  33666. this._sourcePositions = new Float32Array(source);
  33667. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33668. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33669. }
  33670. }
  33671. return this._sourcePositions;
  33672. };
  33673. /**
  33674. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33675. */
  33676. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33677. if (!this._sourceNormals) {
  33678. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33679. if (!source) {
  33680. return this._sourceNormals;
  33681. }
  33682. this._sourceNormals = new Float32Array(source);
  33683. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33684. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33685. }
  33686. }
  33687. return this._sourceNormals;
  33688. };
  33689. /**
  33690. * Updates the vertex buffer by applying transformation from the bones.
  33691. * Returns the Mesh.
  33692. *
  33693. * @param {skeleton} skeleton to apply
  33694. */
  33695. Mesh.prototype.applySkeleton = function (skeleton) {
  33696. if (!this.geometry) {
  33697. return this;
  33698. }
  33699. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33700. return this;
  33701. }
  33702. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33703. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33704. return this;
  33705. }
  33706. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33707. return this;
  33708. }
  33709. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33710. return this;
  33711. }
  33712. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33713. return this;
  33714. }
  33715. if (!this._sourcePositions) {
  33716. var submeshes = this.subMeshes.slice();
  33717. this.setPositionsForCPUSkinning();
  33718. this.subMeshes = submeshes;
  33719. }
  33720. if (!this._sourceNormals) {
  33721. this.setNormalsForCPUSkinning();
  33722. }
  33723. // positionsData checks for not being Float32Array will only pass at most once
  33724. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33725. if (!positionsData) {
  33726. return this;
  33727. }
  33728. if (!(positionsData instanceof Float32Array)) {
  33729. positionsData = new Float32Array(positionsData);
  33730. }
  33731. // normalsData checks for not being Float32Array will only pass at most once
  33732. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33733. if (!normalsData) {
  33734. return this;
  33735. }
  33736. if (!(normalsData instanceof Float32Array)) {
  33737. normalsData = new Float32Array(normalsData);
  33738. }
  33739. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33740. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33741. if (!matricesWeightsData || !matricesIndicesData) {
  33742. return this;
  33743. }
  33744. var needExtras = this.numBoneInfluencers > 4;
  33745. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33746. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33747. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33748. var tempVector3 = BABYLON.Vector3.Zero();
  33749. var finalMatrix = new BABYLON.Matrix();
  33750. var tempMatrix = new BABYLON.Matrix();
  33751. var matWeightIdx = 0;
  33752. var inf;
  33753. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33754. var weight;
  33755. for (inf = 0; inf < 4; inf++) {
  33756. weight = matricesWeightsData[matWeightIdx + inf];
  33757. if (weight > 0) {
  33758. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33759. finalMatrix.addToSelf(tempMatrix);
  33760. }
  33761. }
  33762. if (needExtras) {
  33763. for (inf = 0; inf < 4; inf++) {
  33764. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33765. if (weight > 0) {
  33766. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33767. finalMatrix.addToSelf(tempMatrix);
  33768. }
  33769. }
  33770. }
  33771. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33772. tempVector3.toArray(positionsData, index);
  33773. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33774. tempVector3.toArray(normalsData, index);
  33775. finalMatrix.reset();
  33776. }
  33777. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33778. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33779. return this;
  33780. };
  33781. // Tools
  33782. /**
  33783. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33784. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33785. */
  33786. Mesh.MinMax = function (meshes) {
  33787. var minVector = null;
  33788. var maxVector = null;
  33789. meshes.forEach(function (mesh, index, array) {
  33790. var boundingInfo = mesh.getBoundingInfo();
  33791. var boundingBox = boundingInfo.boundingBox;
  33792. if (!minVector || !maxVector) {
  33793. minVector = boundingBox.minimumWorld;
  33794. maxVector = boundingBox.maximumWorld;
  33795. }
  33796. else {
  33797. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33798. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33799. }
  33800. });
  33801. if (!minVector || !maxVector) {
  33802. return {
  33803. min: BABYLON.Vector3.Zero(),
  33804. max: BABYLON.Vector3.Zero()
  33805. };
  33806. }
  33807. return {
  33808. min: minVector,
  33809. max: maxVector
  33810. };
  33811. };
  33812. /**
  33813. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33814. */
  33815. Mesh.Center = function (meshesOrMinMaxVector) {
  33816. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33817. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33818. };
  33819. /**
  33820. * Merge the array of meshes into a single mesh for performance reasons.
  33821. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  33822. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  33823. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33824. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33825. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33826. */
  33827. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33828. if (disposeSource === void 0) { disposeSource = true; }
  33829. var index;
  33830. if (!allow32BitsIndices) {
  33831. var totalVertices = 0;
  33832. // Counting vertices
  33833. for (index = 0; index < meshes.length; index++) {
  33834. if (meshes[index]) {
  33835. totalVertices += meshes[index].getTotalVertices();
  33836. if (totalVertices > 65536) {
  33837. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33838. return null;
  33839. }
  33840. }
  33841. }
  33842. }
  33843. // Merge
  33844. var vertexData = null;
  33845. var otherVertexData;
  33846. var indiceArray = new Array();
  33847. var source = null;
  33848. for (index = 0; index < meshes.length; index++) {
  33849. if (meshes[index]) {
  33850. var wm = meshes[index].computeWorldMatrix(true);
  33851. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33852. otherVertexData.transform(wm);
  33853. if (vertexData) {
  33854. vertexData.merge(otherVertexData, allow32BitsIndices);
  33855. }
  33856. else {
  33857. vertexData = otherVertexData;
  33858. source = meshes[index];
  33859. }
  33860. if (subdivideWithSubMeshes) {
  33861. indiceArray.push(meshes[index].getTotalIndices());
  33862. }
  33863. }
  33864. }
  33865. source = source;
  33866. if (!meshSubclass) {
  33867. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33868. }
  33869. vertexData.applyToMesh(meshSubclass);
  33870. // Setting properties
  33871. meshSubclass.material = source.material;
  33872. meshSubclass.checkCollisions = source.checkCollisions;
  33873. // Cleaning
  33874. if (disposeSource) {
  33875. for (index = 0; index < meshes.length; index++) {
  33876. if (meshes[index]) {
  33877. meshes[index].dispose();
  33878. }
  33879. }
  33880. }
  33881. // Subdivide
  33882. if (subdivideWithSubMeshes) {
  33883. //-- removal of global submesh
  33884. meshSubclass.releaseSubMeshes();
  33885. index = 0;
  33886. var offset = 0;
  33887. //-- apply subdivision according to index table
  33888. while (index < indiceArray.length) {
  33889. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33890. offset += indiceArray[index];
  33891. index++;
  33892. }
  33893. }
  33894. return meshSubclass;
  33895. };
  33896. // Consts
  33897. Mesh._FRONTSIDE = 0;
  33898. Mesh._BACKSIDE = 1;
  33899. Mesh._DOUBLESIDE = 2;
  33900. Mesh._DEFAULTSIDE = 0;
  33901. Mesh._NO_CAP = 0;
  33902. Mesh._CAP_START = 1;
  33903. Mesh._CAP_END = 2;
  33904. Mesh._CAP_ALL = 3;
  33905. return Mesh;
  33906. }(BABYLON.AbstractMesh));
  33907. BABYLON.Mesh = Mesh;
  33908. })(BABYLON || (BABYLON = {}));
  33909. //# sourceMappingURL=babylon.mesh.js.map
  33910. var BABYLON;
  33911. (function (BABYLON) {
  33912. var BaseSubMesh = /** @class */ (function () {
  33913. function BaseSubMesh() {
  33914. }
  33915. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33916. get: function () {
  33917. return this._materialEffect;
  33918. },
  33919. enumerable: true,
  33920. configurable: true
  33921. });
  33922. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33923. if (defines === void 0) { defines = null; }
  33924. if (this._materialEffect === effect) {
  33925. if (!effect) {
  33926. this._materialDefines = null;
  33927. }
  33928. return;
  33929. }
  33930. this._materialDefines = defines;
  33931. this._materialEffect = effect;
  33932. };
  33933. return BaseSubMesh;
  33934. }());
  33935. BABYLON.BaseSubMesh = BaseSubMesh;
  33936. var SubMesh = /** @class */ (function (_super) {
  33937. __extends(SubMesh, _super);
  33938. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33939. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33940. var _this = _super.call(this) || this;
  33941. _this.materialIndex = materialIndex;
  33942. _this.verticesStart = verticesStart;
  33943. _this.verticesCount = verticesCount;
  33944. _this.indexStart = indexStart;
  33945. _this.indexCount = indexCount;
  33946. /** @hidden */
  33947. _this._renderId = 0;
  33948. _this._mesh = mesh;
  33949. _this._renderingMesh = renderingMesh || mesh;
  33950. mesh.subMeshes.push(_this);
  33951. _this._trianglePlanes = [];
  33952. _this._id = mesh.subMeshes.length - 1;
  33953. if (createBoundingBox) {
  33954. _this.refreshBoundingInfo();
  33955. mesh.computeWorldMatrix(true);
  33956. }
  33957. return _this;
  33958. }
  33959. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33960. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33961. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33962. };
  33963. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33964. get: function () {
  33965. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  33966. },
  33967. enumerable: true,
  33968. configurable: true
  33969. });
  33970. /**
  33971. * Returns the submesh BoudingInfo object.
  33972. */
  33973. SubMesh.prototype.getBoundingInfo = function () {
  33974. if (this.IsGlobal) {
  33975. return this._mesh.getBoundingInfo();
  33976. }
  33977. return this._boundingInfo;
  33978. };
  33979. /**
  33980. * Sets the submesh BoundingInfo.
  33981. * Return the SubMesh.
  33982. */
  33983. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33984. this._boundingInfo = boundingInfo;
  33985. return this;
  33986. };
  33987. /**
  33988. * Returns the mesh of the current submesh.
  33989. */
  33990. SubMesh.prototype.getMesh = function () {
  33991. return this._mesh;
  33992. };
  33993. /**
  33994. * Returns the rendering mesh of the submesh.
  33995. */
  33996. SubMesh.prototype.getRenderingMesh = function () {
  33997. return this._renderingMesh;
  33998. };
  33999. /**
  34000. * Returns the submesh material.
  34001. */
  34002. SubMesh.prototype.getMaterial = function () {
  34003. var rootMaterial = this._renderingMesh.material;
  34004. if (rootMaterial === null || rootMaterial === undefined) {
  34005. return this._mesh.getScene().defaultMaterial;
  34006. }
  34007. else if (rootMaterial.getSubMaterial) {
  34008. var multiMaterial = rootMaterial;
  34009. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34010. if (this._currentMaterial !== effectiveMaterial) {
  34011. this._currentMaterial = effectiveMaterial;
  34012. this._materialDefines = null;
  34013. }
  34014. return effectiveMaterial;
  34015. }
  34016. return rootMaterial;
  34017. };
  34018. // Methods
  34019. /**
  34020. * Sets a new updated BoundingInfo object to the submesh.
  34021. * Returns the SubMesh.
  34022. */
  34023. SubMesh.prototype.refreshBoundingInfo = function () {
  34024. this._lastColliderWorldVertices = null;
  34025. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34026. return this;
  34027. }
  34028. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34029. if (!data) {
  34030. this._boundingInfo = this._mesh.getBoundingInfo();
  34031. return this;
  34032. }
  34033. var indices = this._renderingMesh.getIndices();
  34034. var extend;
  34035. //is this the only submesh?
  34036. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34037. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34038. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34039. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34040. }
  34041. else {
  34042. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34043. }
  34044. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34045. return this;
  34046. };
  34047. /** @hidden */
  34048. SubMesh.prototype._checkCollision = function (collider) {
  34049. var boundingInfo = this.getBoundingInfo();
  34050. return boundingInfo._checkCollision(collider);
  34051. };
  34052. /**
  34053. * Updates the submesh BoundingInfo.
  34054. * Returns the Submesh.
  34055. */
  34056. SubMesh.prototype.updateBoundingInfo = function (world) {
  34057. var boundingInfo = this.getBoundingInfo();
  34058. if (!boundingInfo) {
  34059. this.refreshBoundingInfo();
  34060. boundingInfo = this.getBoundingInfo();
  34061. }
  34062. boundingInfo.update(world);
  34063. return this;
  34064. };
  34065. /**
  34066. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34067. * Boolean returned.
  34068. */
  34069. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34070. var boundingInfo = this.getBoundingInfo();
  34071. if (!boundingInfo) {
  34072. return false;
  34073. }
  34074. return boundingInfo.isInFrustum(frustumPlanes);
  34075. };
  34076. /**
  34077. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34078. * Boolean returned.
  34079. */
  34080. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34081. var boundingInfo = this.getBoundingInfo();
  34082. if (!boundingInfo) {
  34083. return false;
  34084. }
  34085. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34086. };
  34087. /**
  34088. * Renders the submesh.
  34089. * Returns it.
  34090. */
  34091. SubMesh.prototype.render = function (enableAlphaMode) {
  34092. this._renderingMesh.render(this, enableAlphaMode);
  34093. return this;
  34094. };
  34095. /**
  34096. * Returns a new Index Buffer.
  34097. * Type returned : WebGLBuffer.
  34098. */
  34099. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34100. if (!this._linesIndexBuffer) {
  34101. var linesIndices = [];
  34102. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34103. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34104. }
  34105. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34106. this.linesIndexCount = linesIndices.length;
  34107. }
  34108. return this._linesIndexBuffer;
  34109. };
  34110. /**
  34111. * True is the passed Ray intersects the submesh bounding box.
  34112. * Boolean returned.
  34113. */
  34114. SubMesh.prototype.canIntersects = function (ray) {
  34115. var boundingInfo = this.getBoundingInfo();
  34116. if (!boundingInfo) {
  34117. return false;
  34118. }
  34119. return ray.intersectsBox(boundingInfo.boundingBox);
  34120. };
  34121. /**
  34122. * Returns an object IntersectionInfo.
  34123. */
  34124. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34125. var intersectInfo = null;
  34126. var material = this.getMaterial();
  34127. if (!material) {
  34128. return null;
  34129. }
  34130. switch (material.fillMode) {
  34131. case BABYLON.Material.PointListDrawMode:
  34132. case BABYLON.Material.LineListDrawMode:
  34133. case BABYLON.Material.LineLoopDrawMode:
  34134. case BABYLON.Material.LineStripDrawMode:
  34135. case BABYLON.Material.TriangleFanDrawMode:
  34136. case BABYLON.Material.TriangleStripDrawMode:
  34137. return null;
  34138. }
  34139. // LineMesh first as it's also a Mesh...
  34140. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34141. var lineMesh = this._mesh;
  34142. // Line test
  34143. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34144. var p0 = positions[indices[index]];
  34145. var p1 = positions[indices[index + 1]];
  34146. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34147. if (length < 0) {
  34148. continue;
  34149. }
  34150. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34151. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34152. if (fastCheck) {
  34153. break;
  34154. }
  34155. }
  34156. }
  34157. }
  34158. else {
  34159. // Triangles test
  34160. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34161. var p0 = positions[indices[index]];
  34162. var p1 = positions[indices[index + 1]];
  34163. var p2 = positions[indices[index + 2]];
  34164. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34165. if (currentIntersectInfo) {
  34166. if (currentIntersectInfo.distance < 0) {
  34167. continue;
  34168. }
  34169. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34170. intersectInfo = currentIntersectInfo;
  34171. intersectInfo.faceId = index / 3;
  34172. if (fastCheck) {
  34173. break;
  34174. }
  34175. }
  34176. }
  34177. }
  34178. }
  34179. return intersectInfo;
  34180. };
  34181. /** @hidden */
  34182. SubMesh.prototype._rebuild = function () {
  34183. if (this._linesIndexBuffer) {
  34184. this._linesIndexBuffer = null;
  34185. }
  34186. };
  34187. // Clone
  34188. /**
  34189. * Creates a new Submesh from the passed Mesh.
  34190. */
  34191. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34192. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34193. if (!this.IsGlobal) {
  34194. var boundingInfo = this.getBoundingInfo();
  34195. if (!boundingInfo) {
  34196. return result;
  34197. }
  34198. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34199. }
  34200. return result;
  34201. };
  34202. // Dispose
  34203. /**
  34204. * Disposes the Submesh.
  34205. * Returns nothing.
  34206. */
  34207. SubMesh.prototype.dispose = function () {
  34208. if (this._linesIndexBuffer) {
  34209. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34210. this._linesIndexBuffer = null;
  34211. }
  34212. // Remove from mesh
  34213. var index = this._mesh.subMeshes.indexOf(this);
  34214. this._mesh.subMeshes.splice(index, 1);
  34215. };
  34216. // Statics
  34217. /**
  34218. * Creates a new Submesh from the passed parameters :
  34219. * - materialIndex (integer) : the index of the main mesh material.
  34220. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34221. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34222. * - mesh (Mesh) : the main mesh to create the submesh from.
  34223. * - renderingMesh (optional Mesh) : rendering mesh.
  34224. */
  34225. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34226. var minVertexIndex = Number.MAX_VALUE;
  34227. var maxVertexIndex = -Number.MAX_VALUE;
  34228. renderingMesh = (renderingMesh || mesh);
  34229. var indices = renderingMesh.getIndices();
  34230. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34231. var vertexIndex = indices[index];
  34232. if (vertexIndex < minVertexIndex)
  34233. minVertexIndex = vertexIndex;
  34234. if (vertexIndex > maxVertexIndex)
  34235. maxVertexIndex = vertexIndex;
  34236. }
  34237. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34238. };
  34239. return SubMesh;
  34240. }(BaseSubMesh));
  34241. BABYLON.SubMesh = SubMesh;
  34242. })(BABYLON || (BABYLON = {}));
  34243. //# sourceMappingURL=babylon.subMesh.js.map
  34244. var __assign = (this && this.__assign) || function () {
  34245. __assign = Object.assign || function(t) {
  34246. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34247. s = arguments[i];
  34248. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34249. t[p] = s[p];
  34250. }
  34251. return t;
  34252. };
  34253. return __assign.apply(this, arguments);
  34254. };
  34255. var BABYLON;
  34256. (function (BABYLON) {
  34257. /**
  34258. * Manages the defines for the Material
  34259. */
  34260. var MaterialDefines = /** @class */ (function () {
  34261. function MaterialDefines() {
  34262. this._isDirty = true;
  34263. /** @hidden */
  34264. this._areLightsDirty = true;
  34265. /** @hidden */
  34266. this._areAttributesDirty = true;
  34267. /** @hidden */
  34268. this._areTexturesDirty = true;
  34269. /** @hidden */
  34270. this._areFresnelDirty = true;
  34271. /** @hidden */
  34272. this._areMiscDirty = true;
  34273. /** @hidden */
  34274. this._areImageProcessingDirty = true;
  34275. /** @hidden */
  34276. this._normals = false;
  34277. /** @hidden */
  34278. this._uvs = false;
  34279. /** @hidden */
  34280. this._needNormals = false;
  34281. /** @hidden */
  34282. this._needUVs = false;
  34283. }
  34284. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34285. /**
  34286. * Specifies if the material needs to be re-calculated
  34287. */
  34288. get: function () {
  34289. return this._isDirty;
  34290. },
  34291. enumerable: true,
  34292. configurable: true
  34293. });
  34294. /**
  34295. * Marks the material to indicate that it has been re-calculated
  34296. */
  34297. MaterialDefines.prototype.markAsProcessed = function () {
  34298. this._isDirty = false;
  34299. this._areAttributesDirty = false;
  34300. this._areTexturesDirty = false;
  34301. this._areFresnelDirty = false;
  34302. this._areLightsDirty = false;
  34303. this._areMiscDirty = false;
  34304. this._areImageProcessingDirty = false;
  34305. };
  34306. /**
  34307. * Marks the material to indicate that it needs to be re-calculated
  34308. */
  34309. MaterialDefines.prototype.markAsUnprocessed = function () {
  34310. this._isDirty = true;
  34311. };
  34312. /**
  34313. * Marks the material to indicate all of its defines need to be re-calculated
  34314. */
  34315. MaterialDefines.prototype.markAllAsDirty = function () {
  34316. this._areTexturesDirty = true;
  34317. this._areAttributesDirty = true;
  34318. this._areLightsDirty = true;
  34319. this._areFresnelDirty = true;
  34320. this._areMiscDirty = true;
  34321. this._areImageProcessingDirty = true;
  34322. this._isDirty = true;
  34323. };
  34324. /**
  34325. * Marks the material to indicate that image processing needs to be re-calculated
  34326. */
  34327. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34328. this._areImageProcessingDirty = true;
  34329. this._isDirty = true;
  34330. };
  34331. /**
  34332. * Marks the material to indicate the lights need to be re-calculated
  34333. */
  34334. MaterialDefines.prototype.markAsLightDirty = function () {
  34335. this._areLightsDirty = true;
  34336. this._isDirty = true;
  34337. };
  34338. /**
  34339. * Marks the attribute state as changed
  34340. */
  34341. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34342. this._areAttributesDirty = true;
  34343. this._isDirty = true;
  34344. };
  34345. /**
  34346. * Marks the texture state as changed
  34347. */
  34348. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34349. this._areTexturesDirty = true;
  34350. this._isDirty = true;
  34351. };
  34352. /**
  34353. * Marks the fresnel state as changed
  34354. */
  34355. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34356. this._areFresnelDirty = true;
  34357. this._isDirty = true;
  34358. };
  34359. /**
  34360. * Marks the misc state as changed
  34361. */
  34362. MaterialDefines.prototype.markAsMiscDirty = function () {
  34363. this._areMiscDirty = true;
  34364. this._isDirty = true;
  34365. };
  34366. /**
  34367. * Rebuilds the material defines
  34368. */
  34369. MaterialDefines.prototype.rebuild = function () {
  34370. if (this._keys) {
  34371. delete this._keys;
  34372. }
  34373. this._keys = [];
  34374. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34375. var key = _a[_i];
  34376. if (key[0] === "_") {
  34377. continue;
  34378. }
  34379. this._keys.push(key);
  34380. }
  34381. };
  34382. /**
  34383. * Specifies if two material defines are equal
  34384. * @param other - A material define instance to compare to
  34385. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34386. */
  34387. MaterialDefines.prototype.isEqual = function (other) {
  34388. if (this._keys.length !== other._keys.length) {
  34389. return false;
  34390. }
  34391. for (var index = 0; index < this._keys.length; index++) {
  34392. var prop = this._keys[index];
  34393. if (this[prop] !== other[prop]) {
  34394. return false;
  34395. }
  34396. }
  34397. return true;
  34398. };
  34399. /**
  34400. * Clones this instance's defines to another instance
  34401. * @param other - material defines to clone values to
  34402. */
  34403. MaterialDefines.prototype.cloneTo = function (other) {
  34404. if (this._keys.length !== other._keys.length) {
  34405. other._keys = this._keys.slice(0);
  34406. }
  34407. for (var index = 0; index < this._keys.length; index++) {
  34408. var prop = this._keys[index];
  34409. other[prop] = this[prop];
  34410. }
  34411. };
  34412. /**
  34413. * Resets the material define values
  34414. */
  34415. MaterialDefines.prototype.reset = function () {
  34416. for (var index = 0; index < this._keys.length; index++) {
  34417. var prop = this._keys[index];
  34418. var type = typeof this[prop];
  34419. switch (type) {
  34420. case "number":
  34421. this[prop] = 0;
  34422. break;
  34423. case "string":
  34424. this[prop] = "";
  34425. break;
  34426. default:
  34427. this[prop] = false;
  34428. break;
  34429. }
  34430. }
  34431. };
  34432. /**
  34433. * Converts the material define values to a string
  34434. * @returns - String of material define information
  34435. */
  34436. MaterialDefines.prototype.toString = function () {
  34437. var result = "";
  34438. for (var index = 0; index < this._keys.length; index++) {
  34439. var prop = this._keys[index];
  34440. var value = this[prop];
  34441. var type = typeof value;
  34442. switch (type) {
  34443. case "number":
  34444. case "string":
  34445. result += "#define " + prop + " " + value + "\n";
  34446. break;
  34447. default:
  34448. if (value) {
  34449. result += "#define " + prop + "\n";
  34450. }
  34451. break;
  34452. }
  34453. }
  34454. return result;
  34455. };
  34456. return MaterialDefines;
  34457. }());
  34458. BABYLON.MaterialDefines = MaterialDefines;
  34459. /**
  34460. * Base class for the main features of a material in Babylon.js
  34461. */
  34462. var Material = /** @class */ (function () {
  34463. /**
  34464. * Creates a material instance
  34465. * @param name defines the name of the material
  34466. * @param scene defines the scene to reference
  34467. * @param doNotAdd specifies if the material should be added to the scene
  34468. */
  34469. function Material(name, scene, doNotAdd) {
  34470. /**
  34471. * Specifies if the ready state should be checked on each call
  34472. */
  34473. this.checkReadyOnEveryCall = false;
  34474. /**
  34475. * Specifies if the ready state should be checked once
  34476. */
  34477. this.checkReadyOnlyOnce = false;
  34478. /**
  34479. * The state of the material
  34480. */
  34481. this.state = "";
  34482. /**
  34483. * The alpha value of the material
  34484. */
  34485. this._alpha = 1.0;
  34486. /**
  34487. * Specifies if back face culling is enabled
  34488. */
  34489. this._backFaceCulling = true;
  34490. /**
  34491. * Gets a boolean indicating that current material needs to register RTT
  34492. */
  34493. this.hasRenderTargetTextures = false;
  34494. /**
  34495. * Specifies if the material should be serialized
  34496. */
  34497. this.doNotSerialize = false;
  34498. /**
  34499. * Specifies if the effect should be stored on sub meshes
  34500. */
  34501. this.storeEffectOnSubMeshes = false;
  34502. /**
  34503. * An event triggered when the material is disposed
  34504. */
  34505. this.onDisposeObservable = new BABYLON.Observable();
  34506. /**
  34507. * Stores the value of the alpha mode
  34508. */
  34509. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34510. /**
  34511. * Stores the state of the need depth pre-pass value
  34512. */
  34513. this._needDepthPrePass = false;
  34514. /**
  34515. * Specifies if depth writing should be disabled
  34516. */
  34517. this.disableDepthWrite = false;
  34518. /**
  34519. * Specifies if depth writing should be forced
  34520. */
  34521. this.forceDepthWrite = false;
  34522. /**
  34523. * Specifies if there should be a separate pass for culling
  34524. */
  34525. this.separateCullingPass = false;
  34526. /**
  34527. * Stores the state specifing if fog should be enabled
  34528. */
  34529. this._fogEnabled = true;
  34530. /**
  34531. * Stores the size of points
  34532. */
  34533. this.pointSize = 1.0;
  34534. /**
  34535. * Stores the z offset value
  34536. */
  34537. this.zOffset = 0;
  34538. /**
  34539. * @hidden
  34540. * Specifies if the material was previously ready
  34541. */
  34542. this._wasPreviouslyReady = false;
  34543. /**
  34544. * Stores the fill mode state
  34545. */
  34546. this._fillMode = Material.TriangleFillMode;
  34547. this.name = name;
  34548. this.id = name || BABYLON.Tools.RandomId();
  34549. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34550. this.uniqueId = this._scene.getUniqueId();
  34551. if (this._scene.useRightHandedSystem) {
  34552. this.sideOrientation = Material.ClockWiseSideOrientation;
  34553. }
  34554. else {
  34555. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34556. }
  34557. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34558. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34559. if (!doNotAdd) {
  34560. this._scene.materials.push(this);
  34561. }
  34562. }
  34563. Object.defineProperty(Material, "TriangleFillMode", {
  34564. /**
  34565. * Returns the triangle fill mode
  34566. */
  34567. get: function () {
  34568. return Material._TriangleFillMode;
  34569. },
  34570. enumerable: true,
  34571. configurable: true
  34572. });
  34573. Object.defineProperty(Material, "WireFrameFillMode", {
  34574. /**
  34575. * Returns the wireframe mode
  34576. */
  34577. get: function () {
  34578. return Material._WireFrameFillMode;
  34579. },
  34580. enumerable: true,
  34581. configurable: true
  34582. });
  34583. Object.defineProperty(Material, "PointFillMode", {
  34584. /**
  34585. * Returns the point fill mode
  34586. */
  34587. get: function () {
  34588. return Material._PointFillMode;
  34589. },
  34590. enumerable: true,
  34591. configurable: true
  34592. });
  34593. Object.defineProperty(Material, "PointListDrawMode", {
  34594. /**
  34595. * Returns the point list draw mode
  34596. */
  34597. get: function () {
  34598. return Material._PointListDrawMode;
  34599. },
  34600. enumerable: true,
  34601. configurable: true
  34602. });
  34603. Object.defineProperty(Material, "LineListDrawMode", {
  34604. /**
  34605. * Returns the line list draw mode
  34606. */
  34607. get: function () {
  34608. return Material._LineListDrawMode;
  34609. },
  34610. enumerable: true,
  34611. configurable: true
  34612. });
  34613. Object.defineProperty(Material, "LineLoopDrawMode", {
  34614. /**
  34615. * Returns the line loop draw mode
  34616. */
  34617. get: function () {
  34618. return Material._LineLoopDrawMode;
  34619. },
  34620. enumerable: true,
  34621. configurable: true
  34622. });
  34623. Object.defineProperty(Material, "LineStripDrawMode", {
  34624. /**
  34625. * Returns the line strip draw mode
  34626. */
  34627. get: function () {
  34628. return Material._LineStripDrawMode;
  34629. },
  34630. enumerable: true,
  34631. configurable: true
  34632. });
  34633. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34634. /**
  34635. * Returns the triangle strip draw mode
  34636. */
  34637. get: function () {
  34638. return Material._TriangleStripDrawMode;
  34639. },
  34640. enumerable: true,
  34641. configurable: true
  34642. });
  34643. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34644. /**
  34645. * Returns the triangle fan draw mode
  34646. */
  34647. get: function () {
  34648. return Material._TriangleFanDrawMode;
  34649. },
  34650. enumerable: true,
  34651. configurable: true
  34652. });
  34653. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34654. /**
  34655. * Returns the clock-wise side orientation
  34656. */
  34657. get: function () {
  34658. return Material._ClockWiseSideOrientation;
  34659. },
  34660. enumerable: true,
  34661. configurable: true
  34662. });
  34663. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34664. /**
  34665. * Returns the counter clock-wise side orientation
  34666. */
  34667. get: function () {
  34668. return Material._CounterClockWiseSideOrientation;
  34669. },
  34670. enumerable: true,
  34671. configurable: true
  34672. });
  34673. Object.defineProperty(Material, "TextureDirtyFlag", {
  34674. /**
  34675. * Returns the dirty texture flag value
  34676. */
  34677. get: function () {
  34678. return Material._TextureDirtyFlag;
  34679. },
  34680. enumerable: true,
  34681. configurable: true
  34682. });
  34683. Object.defineProperty(Material, "LightDirtyFlag", {
  34684. /**
  34685. * Returns the dirty light flag value
  34686. */
  34687. get: function () {
  34688. return Material._LightDirtyFlag;
  34689. },
  34690. enumerable: true,
  34691. configurable: true
  34692. });
  34693. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34694. /**
  34695. * Returns the dirty fresnel flag value
  34696. */
  34697. get: function () {
  34698. return Material._FresnelDirtyFlag;
  34699. },
  34700. enumerable: true,
  34701. configurable: true
  34702. });
  34703. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34704. /**
  34705. * Returns the dirty attributes flag value
  34706. */
  34707. get: function () {
  34708. return Material._AttributesDirtyFlag;
  34709. },
  34710. enumerable: true,
  34711. configurable: true
  34712. });
  34713. Object.defineProperty(Material, "MiscDirtyFlag", {
  34714. /**
  34715. * Returns the dirty misc flag value
  34716. */
  34717. get: function () {
  34718. return Material._MiscDirtyFlag;
  34719. },
  34720. enumerable: true,
  34721. configurable: true
  34722. });
  34723. Object.defineProperty(Material.prototype, "alpha", {
  34724. /**
  34725. * Gets the alpha value of the material
  34726. */
  34727. get: function () {
  34728. return this._alpha;
  34729. },
  34730. /**
  34731. * Sets the alpha value of the material
  34732. */
  34733. set: function (value) {
  34734. if (this._alpha === value) {
  34735. return;
  34736. }
  34737. this._alpha = value;
  34738. this.markAsDirty(Material.MiscDirtyFlag);
  34739. },
  34740. enumerable: true,
  34741. configurable: true
  34742. });
  34743. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34744. /**
  34745. * Gets the back-face culling state
  34746. */
  34747. get: function () {
  34748. return this._backFaceCulling;
  34749. },
  34750. /**
  34751. * Sets the back-face culling state
  34752. */
  34753. set: function (value) {
  34754. if (this._backFaceCulling === value) {
  34755. return;
  34756. }
  34757. this._backFaceCulling = value;
  34758. this.markAsDirty(Material.TextureDirtyFlag);
  34759. },
  34760. enumerable: true,
  34761. configurable: true
  34762. });
  34763. Object.defineProperty(Material.prototype, "onDispose", {
  34764. /**
  34765. * Called during a dispose event
  34766. */
  34767. set: function (callback) {
  34768. if (this._onDisposeObserver) {
  34769. this.onDisposeObservable.remove(this._onDisposeObserver);
  34770. }
  34771. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34772. },
  34773. enumerable: true,
  34774. configurable: true
  34775. });
  34776. Object.defineProperty(Material.prototype, "onBindObservable", {
  34777. /**
  34778. * An event triggered when the material is bound
  34779. */
  34780. get: function () {
  34781. if (!this._onBindObservable) {
  34782. this._onBindObservable = new BABYLON.Observable();
  34783. }
  34784. return this._onBindObservable;
  34785. },
  34786. enumerable: true,
  34787. configurable: true
  34788. });
  34789. Object.defineProperty(Material.prototype, "onBind", {
  34790. /**
  34791. * Called during a bind event
  34792. */
  34793. set: function (callback) {
  34794. if (this._onBindObserver) {
  34795. this.onBindObservable.remove(this._onBindObserver);
  34796. }
  34797. this._onBindObserver = this.onBindObservable.add(callback);
  34798. },
  34799. enumerable: true,
  34800. configurable: true
  34801. });
  34802. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34803. /**
  34804. * An event triggered when the material is unbound
  34805. */
  34806. get: function () {
  34807. if (!this._onUnBindObservable) {
  34808. this._onUnBindObservable = new BABYLON.Observable();
  34809. }
  34810. return this._onUnBindObservable;
  34811. },
  34812. enumerable: true,
  34813. configurable: true
  34814. });
  34815. Object.defineProperty(Material.prototype, "alphaMode", {
  34816. /**
  34817. * Gets the value of the alpha mode
  34818. */
  34819. get: function () {
  34820. return this._alphaMode;
  34821. },
  34822. /**
  34823. * Sets the value of the alpha mode.
  34824. *
  34825. * | Value | Type | Description |
  34826. * | --- | --- | --- |
  34827. * | 0 | ALPHA_DISABLE | |
  34828. * | 1 | ALPHA_ADD | |
  34829. * | 2 | ALPHA_COMBINE | |
  34830. * | 3 | ALPHA_SUBTRACT | |
  34831. * | 4 | ALPHA_MULTIPLY | |
  34832. * | 5 | ALPHA_MAXIMIZED | |
  34833. * | 6 | ALPHA_ONEONE | |
  34834. * | 7 | ALPHA_PREMULTIPLIED | |
  34835. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34836. * | 9 | ALPHA_INTERPOLATE | |
  34837. * | 10 | ALPHA_SCREENMODE | |
  34838. *
  34839. */
  34840. set: function (value) {
  34841. if (this._alphaMode === value) {
  34842. return;
  34843. }
  34844. this._alphaMode = value;
  34845. this.markAsDirty(Material.TextureDirtyFlag);
  34846. },
  34847. enumerable: true,
  34848. configurable: true
  34849. });
  34850. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34851. /**
  34852. * Gets the depth pre-pass value
  34853. */
  34854. get: function () {
  34855. return this._needDepthPrePass;
  34856. },
  34857. /**
  34858. * Sets the need depth pre-pass value
  34859. */
  34860. set: function (value) {
  34861. if (this._needDepthPrePass === value) {
  34862. return;
  34863. }
  34864. this._needDepthPrePass = value;
  34865. if (this._needDepthPrePass) {
  34866. this.checkReadyOnEveryCall = true;
  34867. }
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(Material.prototype, "fogEnabled", {
  34873. /**
  34874. * Gets the value of the fog enabled state
  34875. */
  34876. get: function () {
  34877. return this._fogEnabled;
  34878. },
  34879. /**
  34880. * Sets the state for enabling fog
  34881. */
  34882. set: function (value) {
  34883. if (this._fogEnabled === value) {
  34884. return;
  34885. }
  34886. this._fogEnabled = value;
  34887. this.markAsDirty(Material.MiscDirtyFlag);
  34888. },
  34889. enumerable: true,
  34890. configurable: true
  34891. });
  34892. Object.defineProperty(Material.prototype, "wireframe", {
  34893. /**
  34894. * Gets a value specifying if wireframe mode is enabled
  34895. */
  34896. get: function () {
  34897. switch (this._fillMode) {
  34898. case Material.WireFrameFillMode:
  34899. case Material.LineListDrawMode:
  34900. case Material.LineLoopDrawMode:
  34901. case Material.LineStripDrawMode:
  34902. return true;
  34903. }
  34904. return this._scene.forceWireframe;
  34905. },
  34906. /**
  34907. * Sets the state of wireframe mode
  34908. */
  34909. set: function (value) {
  34910. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34911. },
  34912. enumerable: true,
  34913. configurable: true
  34914. });
  34915. Object.defineProperty(Material.prototype, "pointsCloud", {
  34916. /**
  34917. * Gets the value specifying if point clouds are enabled
  34918. */
  34919. get: function () {
  34920. switch (this._fillMode) {
  34921. case Material.PointFillMode:
  34922. case Material.PointListDrawMode:
  34923. return true;
  34924. }
  34925. return this._scene.forcePointsCloud;
  34926. },
  34927. /**
  34928. * Sets the state of point cloud mode
  34929. */
  34930. set: function (value) {
  34931. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34932. },
  34933. enumerable: true,
  34934. configurable: true
  34935. });
  34936. Object.defineProperty(Material.prototype, "fillMode", {
  34937. /**
  34938. * Gets the material fill mode
  34939. */
  34940. get: function () {
  34941. return this._fillMode;
  34942. },
  34943. /**
  34944. * Sets the material fill mode
  34945. */
  34946. set: function (value) {
  34947. if (this._fillMode === value) {
  34948. return;
  34949. }
  34950. this._fillMode = value;
  34951. this.markAsDirty(Material.MiscDirtyFlag);
  34952. },
  34953. enumerable: true,
  34954. configurable: true
  34955. });
  34956. /**
  34957. * Returns a string representation of the current material
  34958. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34959. * @returns a string with material information
  34960. */
  34961. Material.prototype.toString = function (fullDetails) {
  34962. var ret = "Name: " + this.name;
  34963. if (fullDetails) {
  34964. }
  34965. return ret;
  34966. };
  34967. /**
  34968. * Gets the class name of the material
  34969. * @returns a string with the class name of the material
  34970. */
  34971. Material.prototype.getClassName = function () {
  34972. return "Material";
  34973. };
  34974. Object.defineProperty(Material.prototype, "isFrozen", {
  34975. /**
  34976. * Specifies if updates for the material been locked
  34977. */
  34978. get: function () {
  34979. return this.checkReadyOnlyOnce;
  34980. },
  34981. enumerable: true,
  34982. configurable: true
  34983. });
  34984. /**
  34985. * Locks updates for the material
  34986. */
  34987. Material.prototype.freeze = function () {
  34988. this.checkReadyOnlyOnce = true;
  34989. };
  34990. /**
  34991. * Unlocks updates for the material
  34992. */
  34993. Material.prototype.unfreeze = function () {
  34994. this.checkReadyOnlyOnce = false;
  34995. };
  34996. /**
  34997. * Specifies if the material is ready to be used
  34998. * @param mesh defines the mesh to check
  34999. * @param useInstances specifies if instances should be used
  35000. * @returns a boolean indicating if the material is ready to be used
  35001. */
  35002. Material.prototype.isReady = function (mesh, useInstances) {
  35003. return true;
  35004. };
  35005. /**
  35006. * Specifies that the submesh is ready to be used
  35007. * @param mesh defines the mesh to check
  35008. * @param subMesh defines which submesh to check
  35009. * @param useInstances specifies that instances should be used
  35010. * @returns a boolean indicating that the submesh is ready or not
  35011. */
  35012. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35013. return false;
  35014. };
  35015. /**
  35016. * Returns the material effect
  35017. * @returns the effect associated with the material
  35018. */
  35019. Material.prototype.getEffect = function () {
  35020. return this._effect;
  35021. };
  35022. /**
  35023. * Returns the current scene
  35024. * @returns a Scene
  35025. */
  35026. Material.prototype.getScene = function () {
  35027. return this._scene;
  35028. };
  35029. /**
  35030. * Specifies if the material will require alpha blending
  35031. * @returns a boolean specifying if alpha blending is needed
  35032. */
  35033. Material.prototype.needAlphaBlending = function () {
  35034. return (this.alpha < 1.0);
  35035. };
  35036. /**
  35037. * Specifies if the mesh will require alpha blending
  35038. * @param mesh defines the mesh to check
  35039. * @returns a boolean specifying if alpha blending is needed for the mesh
  35040. */
  35041. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35042. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35043. };
  35044. /**
  35045. * Specifies if this material should be rendered in alpha test mode
  35046. * @returns a boolean specifying if an alpha test is needed.
  35047. */
  35048. Material.prototype.needAlphaTesting = function () {
  35049. return false;
  35050. };
  35051. /**
  35052. * Gets the texture used for the alpha test
  35053. * @returns the texture to use for alpha testing
  35054. */
  35055. Material.prototype.getAlphaTestTexture = function () {
  35056. return null;
  35057. };
  35058. /**
  35059. * Marks the material to indicate that it needs to be re-calculated
  35060. */
  35061. Material.prototype.markDirty = function () {
  35062. this._wasPreviouslyReady = false;
  35063. };
  35064. /** @hidden */
  35065. Material.prototype._preBind = function (effect, overrideOrientation) {
  35066. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35067. var engine = this._scene.getEngine();
  35068. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35069. var reverse = orientation === Material.ClockWiseSideOrientation;
  35070. engine.enableEffect(effect ? effect : this._effect);
  35071. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35072. return reverse;
  35073. };
  35074. /**
  35075. * Binds the material to the mesh
  35076. * @param world defines the world transformation matrix
  35077. * @param mesh defines the mesh to bind the material to
  35078. */
  35079. Material.prototype.bind = function (world, mesh) {
  35080. };
  35081. /**
  35082. * Binds the submesh to the material
  35083. * @param world defines the world transformation matrix
  35084. * @param mesh defines the mesh containing the submesh
  35085. * @param subMesh defines the submesh to bind the material to
  35086. */
  35087. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35088. };
  35089. /**
  35090. * Binds the world matrix to the material
  35091. * @param world defines the world transformation matrix
  35092. */
  35093. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35094. };
  35095. /**
  35096. * Binds the scene's uniform buffer to the effect.
  35097. * @param effect defines the effect to bind to the scene uniform buffer
  35098. * @param sceneUbo defines the uniform buffer storing scene data
  35099. */
  35100. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35101. sceneUbo.bindToEffect(effect, "Scene");
  35102. };
  35103. /**
  35104. * Binds the view matrix to the effect
  35105. * @param effect defines the effect to bind the view matrix to
  35106. */
  35107. Material.prototype.bindView = function (effect) {
  35108. if (!this._useUBO) {
  35109. effect.setMatrix("view", this.getScene().getViewMatrix());
  35110. }
  35111. else {
  35112. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35113. }
  35114. };
  35115. /**
  35116. * Binds the view projection matrix to the effect
  35117. * @param effect defines the effect to bind the view projection matrix to
  35118. */
  35119. Material.prototype.bindViewProjection = function (effect) {
  35120. if (!this._useUBO) {
  35121. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35122. }
  35123. else {
  35124. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35125. }
  35126. };
  35127. /**
  35128. * Specifies if material alpha testing should be turned on for the mesh
  35129. * @param mesh defines the mesh to check
  35130. */
  35131. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35132. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35133. };
  35134. /**
  35135. * Processes to execute after binding the material to a mesh
  35136. * @param mesh defines the rendered mesh
  35137. */
  35138. Material.prototype._afterBind = function (mesh) {
  35139. this._scene._cachedMaterial = this;
  35140. if (mesh) {
  35141. this._scene._cachedVisibility = mesh.visibility;
  35142. }
  35143. else {
  35144. this._scene._cachedVisibility = 1;
  35145. }
  35146. if (this._onBindObservable && mesh) {
  35147. this._onBindObservable.notifyObservers(mesh);
  35148. }
  35149. if (this.disableDepthWrite) {
  35150. var engine = this._scene.getEngine();
  35151. this._cachedDepthWriteState = engine.getDepthWrite();
  35152. engine.setDepthWrite(false);
  35153. }
  35154. };
  35155. /**
  35156. * Unbinds the material from the mesh
  35157. */
  35158. Material.prototype.unbind = function () {
  35159. if (this._onUnBindObservable) {
  35160. this._onUnBindObservable.notifyObservers(this);
  35161. }
  35162. if (this.disableDepthWrite) {
  35163. var engine = this._scene.getEngine();
  35164. engine.setDepthWrite(this._cachedDepthWriteState);
  35165. }
  35166. };
  35167. /**
  35168. * Gets the active textures from the material
  35169. * @returns an array of textures
  35170. */
  35171. Material.prototype.getActiveTextures = function () {
  35172. return [];
  35173. };
  35174. /**
  35175. * Specifies if the material uses a texture
  35176. * @param texture defines the texture to check against the material
  35177. * @returns a boolean specifying if the material uses the texture
  35178. */
  35179. Material.prototype.hasTexture = function (texture) {
  35180. return false;
  35181. };
  35182. /**
  35183. * Makes a duplicate of the material, and gives it a new name
  35184. * @param name defines the new name for the duplicated material
  35185. * @returns the cloned material
  35186. */
  35187. Material.prototype.clone = function (name) {
  35188. return null;
  35189. };
  35190. /**
  35191. * Gets the meshes bound to the material
  35192. * @returns an array of meshes bound to the material
  35193. */
  35194. Material.prototype.getBindedMeshes = function () {
  35195. var result = new Array();
  35196. for (var index = 0; index < this._scene.meshes.length; index++) {
  35197. var mesh = this._scene.meshes[index];
  35198. if (mesh.material === this) {
  35199. result.push(mesh);
  35200. }
  35201. }
  35202. return result;
  35203. };
  35204. /**
  35205. * Force shader compilation
  35206. * @param mesh defines the mesh associated with this material
  35207. * @param onCompiled defines a function to execute once the material is compiled
  35208. * @param options defines the options to configure the compilation
  35209. */
  35210. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35211. var _this = this;
  35212. var localOptions = __assign({ clipPlane: false }, options);
  35213. var subMesh = new BABYLON.BaseSubMesh();
  35214. var scene = this.getScene();
  35215. var checkReady = function () {
  35216. if (!_this._scene || !_this._scene.getEngine()) {
  35217. return;
  35218. }
  35219. if (subMesh._materialDefines) {
  35220. subMesh._materialDefines._renderId = -1;
  35221. }
  35222. var clipPlaneState = scene.clipPlane;
  35223. if (localOptions.clipPlane) {
  35224. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35225. }
  35226. if (_this.storeEffectOnSubMeshes) {
  35227. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35228. if (onCompiled) {
  35229. onCompiled(_this);
  35230. }
  35231. }
  35232. else {
  35233. setTimeout(checkReady, 16);
  35234. }
  35235. }
  35236. else {
  35237. if (_this.isReady(mesh)) {
  35238. if (onCompiled) {
  35239. onCompiled(_this);
  35240. }
  35241. }
  35242. else {
  35243. setTimeout(checkReady, 16);
  35244. }
  35245. }
  35246. if (localOptions.clipPlane) {
  35247. scene.clipPlane = clipPlaneState;
  35248. }
  35249. };
  35250. checkReady();
  35251. };
  35252. /**
  35253. * Force shader compilation
  35254. * @param mesh defines the mesh that will use this material
  35255. * @param options defines additional options for compiling the shaders
  35256. * @returns a promise that resolves when the compilation completes
  35257. */
  35258. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35259. var _this = this;
  35260. return new Promise(function (resolve) {
  35261. _this.forceCompilation(mesh, function () {
  35262. resolve();
  35263. }, options);
  35264. });
  35265. };
  35266. /**
  35267. * Marks a define in the material to indicate that it needs to be re-computed
  35268. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35269. */
  35270. Material.prototype.markAsDirty = function (flag) {
  35271. if (flag & Material.TextureDirtyFlag) {
  35272. this._markAllSubMeshesAsTexturesDirty();
  35273. }
  35274. if (flag & Material.LightDirtyFlag) {
  35275. this._markAllSubMeshesAsLightsDirty();
  35276. }
  35277. if (flag & Material.FresnelDirtyFlag) {
  35278. this._markAllSubMeshesAsFresnelDirty();
  35279. }
  35280. if (flag & Material.AttributesDirtyFlag) {
  35281. this._markAllSubMeshesAsAttributesDirty();
  35282. }
  35283. if (flag & Material.MiscDirtyFlag) {
  35284. this._markAllSubMeshesAsMiscDirty();
  35285. }
  35286. this.getScene().resetCachedMaterial();
  35287. };
  35288. /**
  35289. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35290. * @param func defines a function which checks material defines against the submeshes
  35291. */
  35292. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35293. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35294. var mesh = _a[_i];
  35295. if (!mesh.subMeshes) {
  35296. continue;
  35297. }
  35298. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35299. var subMesh = _c[_b];
  35300. if (subMesh.getMaterial() !== this) {
  35301. continue;
  35302. }
  35303. if (!subMesh._materialDefines) {
  35304. continue;
  35305. }
  35306. func(subMesh._materialDefines);
  35307. }
  35308. }
  35309. };
  35310. /**
  35311. * Indicates that image processing needs to be re-calculated for all submeshes
  35312. */
  35313. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35314. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35315. };
  35316. /**
  35317. * Indicates that textures need to be re-calculated for all submeshes
  35318. */
  35319. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35320. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35321. };
  35322. /**
  35323. * Indicates that fresnel needs to be re-calculated for all submeshes
  35324. */
  35325. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35326. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35327. };
  35328. /**
  35329. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35330. */
  35331. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35332. this._markAllSubMeshesAsDirty(function (defines) {
  35333. defines.markAsFresnelDirty();
  35334. defines.markAsMiscDirty();
  35335. });
  35336. };
  35337. /**
  35338. * Indicates that lights need to be re-calculated for all submeshes
  35339. */
  35340. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35341. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35342. };
  35343. /**
  35344. * Indicates that attributes need to be re-calculated for all submeshes
  35345. */
  35346. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35347. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35348. };
  35349. /**
  35350. * Indicates that misc needs to be re-calculated for all submeshes
  35351. */
  35352. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35353. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35354. };
  35355. /**
  35356. * Indicates that textures and misc need to be re-calculated for all submeshes
  35357. */
  35358. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35359. this._markAllSubMeshesAsDirty(function (defines) {
  35360. defines.markAsTexturesDirty();
  35361. defines.markAsMiscDirty();
  35362. });
  35363. };
  35364. /**
  35365. * Disposes the material
  35366. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35367. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35368. */
  35369. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35370. // Animations
  35371. this.getScene().stopAnimation(this);
  35372. this.getScene().freeProcessedMaterials();
  35373. // Remove from scene
  35374. var index = this._scene.materials.indexOf(this);
  35375. if (index >= 0) {
  35376. this._scene.materials.splice(index, 1);
  35377. }
  35378. // Remove from meshes
  35379. for (index = 0; index < this._scene.meshes.length; index++) {
  35380. var mesh = this._scene.meshes[index];
  35381. if (mesh.material === this) {
  35382. mesh.material = null;
  35383. if (mesh.geometry) {
  35384. var geometry = (mesh.geometry);
  35385. if (this.storeEffectOnSubMeshes) {
  35386. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35387. var subMesh = _a[_i];
  35388. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35389. if (forceDisposeEffect && subMesh._materialEffect) {
  35390. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35391. }
  35392. }
  35393. }
  35394. else {
  35395. geometry._releaseVertexArrayObject(this._effect);
  35396. }
  35397. }
  35398. }
  35399. }
  35400. this._uniformBuffer.dispose();
  35401. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35402. if (forceDisposeEffect && this._effect) {
  35403. if (!this.storeEffectOnSubMeshes) {
  35404. this._scene.getEngine()._releaseEffect(this._effect);
  35405. }
  35406. this._effect = null;
  35407. }
  35408. // Callback
  35409. this.onDisposeObservable.notifyObservers(this);
  35410. this.onDisposeObservable.clear();
  35411. if (this._onBindObservable) {
  35412. this._onBindObservable.clear();
  35413. }
  35414. if (this._onUnBindObservable) {
  35415. this._onUnBindObservable.clear();
  35416. }
  35417. };
  35418. /**
  35419. * Serializes this material
  35420. * @returns the serialized material object
  35421. */
  35422. Material.prototype.serialize = function () {
  35423. return BABYLON.SerializationHelper.Serialize(this);
  35424. };
  35425. /**
  35426. * Creates a MultiMaterial from parsed MultiMaterial data.
  35427. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35428. * @param scene defines the hosting scene
  35429. * @returns a new MultiMaterial
  35430. */
  35431. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35432. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35433. multiMaterial.id = parsedMultiMaterial.id;
  35434. if (BABYLON.Tags) {
  35435. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35436. }
  35437. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35438. var subMatId = parsedMultiMaterial.materials[matIndex];
  35439. if (subMatId) {
  35440. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35441. }
  35442. else {
  35443. multiMaterial.subMaterials.push(null);
  35444. }
  35445. }
  35446. return multiMaterial;
  35447. };
  35448. /**
  35449. * Creates a material from parsed material data
  35450. * @param parsedMaterial defines parsed material data
  35451. * @param scene defines the hosting scene
  35452. * @param rootUrl defines the root URL to use to load textures
  35453. * @returns a new material
  35454. */
  35455. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35456. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35457. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35458. }
  35459. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35460. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35461. if (!BABYLON.LegacyPBRMaterial) {
  35462. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35463. return;
  35464. }
  35465. }
  35466. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35467. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35468. };
  35469. // Triangle views
  35470. Material._TriangleFillMode = 0;
  35471. Material._WireFrameFillMode = 1;
  35472. Material._PointFillMode = 2;
  35473. // Draw modes
  35474. Material._PointListDrawMode = 3;
  35475. Material._LineListDrawMode = 4;
  35476. Material._LineLoopDrawMode = 5;
  35477. Material._LineStripDrawMode = 6;
  35478. Material._TriangleStripDrawMode = 7;
  35479. Material._TriangleFanDrawMode = 8;
  35480. /**
  35481. * Stores the clock-wise side orientation
  35482. */
  35483. Material._ClockWiseSideOrientation = 0;
  35484. /**
  35485. * Stores the counter clock-wise side orientation
  35486. */
  35487. Material._CounterClockWiseSideOrientation = 1;
  35488. /**
  35489. * The dirty texture flag value
  35490. */
  35491. Material._TextureDirtyFlag = 1;
  35492. /**
  35493. * The dirty light flag value
  35494. */
  35495. Material._LightDirtyFlag = 2;
  35496. /**
  35497. * The dirty fresnel flag value
  35498. */
  35499. Material._FresnelDirtyFlag = 4;
  35500. /**
  35501. * The dirty attribute flag value
  35502. */
  35503. Material._AttributesDirtyFlag = 8;
  35504. /**
  35505. * The dirty misc flag value
  35506. */
  35507. Material._MiscDirtyFlag = 16;
  35508. __decorate([
  35509. BABYLON.serialize()
  35510. ], Material.prototype, "id", void 0);
  35511. __decorate([
  35512. BABYLON.serialize()
  35513. ], Material.prototype, "uniqueId", void 0);
  35514. __decorate([
  35515. BABYLON.serialize()
  35516. ], Material.prototype, "name", void 0);
  35517. __decorate([
  35518. BABYLON.serialize()
  35519. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35520. __decorate([
  35521. BABYLON.serialize()
  35522. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35523. __decorate([
  35524. BABYLON.serialize()
  35525. ], Material.prototype, "state", void 0);
  35526. __decorate([
  35527. BABYLON.serialize("alpha")
  35528. ], Material.prototype, "_alpha", void 0);
  35529. __decorate([
  35530. BABYLON.serialize("backFaceCulling")
  35531. ], Material.prototype, "_backFaceCulling", void 0);
  35532. __decorate([
  35533. BABYLON.serialize()
  35534. ], Material.prototype, "sideOrientation", void 0);
  35535. __decorate([
  35536. BABYLON.serialize("alphaMode")
  35537. ], Material.prototype, "_alphaMode", void 0);
  35538. __decorate([
  35539. BABYLON.serialize()
  35540. ], Material.prototype, "_needDepthPrePass", void 0);
  35541. __decorate([
  35542. BABYLON.serialize()
  35543. ], Material.prototype, "disableDepthWrite", void 0);
  35544. __decorate([
  35545. BABYLON.serialize()
  35546. ], Material.prototype, "forceDepthWrite", void 0);
  35547. __decorate([
  35548. BABYLON.serialize()
  35549. ], Material.prototype, "separateCullingPass", void 0);
  35550. __decorate([
  35551. BABYLON.serialize("fogEnabled")
  35552. ], Material.prototype, "_fogEnabled", void 0);
  35553. __decorate([
  35554. BABYLON.serialize()
  35555. ], Material.prototype, "pointSize", void 0);
  35556. __decorate([
  35557. BABYLON.serialize()
  35558. ], Material.prototype, "zOffset", void 0);
  35559. __decorate([
  35560. BABYLON.serialize()
  35561. ], Material.prototype, "wireframe", null);
  35562. __decorate([
  35563. BABYLON.serialize()
  35564. ], Material.prototype, "pointsCloud", null);
  35565. __decorate([
  35566. BABYLON.serialize()
  35567. ], Material.prototype, "fillMode", null);
  35568. return Material;
  35569. }());
  35570. BABYLON.Material = Material;
  35571. })(BABYLON || (BABYLON = {}));
  35572. //# sourceMappingURL=babylon.material.js.map
  35573. var BABYLON;
  35574. (function (BABYLON) {
  35575. var UniformBuffer = /** @class */ (function () {
  35576. /**
  35577. * Uniform buffer objects.
  35578. *
  35579. * Handles blocks of uniform on the GPU.
  35580. *
  35581. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35582. *
  35583. * For more information, please refer to :
  35584. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35585. */
  35586. function UniformBuffer(engine, data, dynamic) {
  35587. this._engine = engine;
  35588. this._noUBO = !engine.supportsUniformBuffers;
  35589. this._dynamic = dynamic;
  35590. this._data = data || [];
  35591. this._uniformLocations = {};
  35592. this._uniformSizes = {};
  35593. this._uniformLocationPointer = 0;
  35594. this._needSync = false;
  35595. if (this._noUBO) {
  35596. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35597. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35598. this.updateFloat = this._updateFloatForEffect;
  35599. this.updateFloat2 = this._updateFloat2ForEffect;
  35600. this.updateFloat3 = this._updateFloat3ForEffect;
  35601. this.updateFloat4 = this._updateFloat4ForEffect;
  35602. this.updateMatrix = this._updateMatrixForEffect;
  35603. this.updateVector3 = this._updateVector3ForEffect;
  35604. this.updateVector4 = this._updateVector4ForEffect;
  35605. this.updateColor3 = this._updateColor3ForEffect;
  35606. this.updateColor4 = this._updateColor4ForEffect;
  35607. }
  35608. else {
  35609. this._engine._uniformBuffers.push(this);
  35610. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35611. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35612. this.updateFloat = this._updateFloatForUniform;
  35613. this.updateFloat2 = this._updateFloat2ForUniform;
  35614. this.updateFloat3 = this._updateFloat3ForUniform;
  35615. this.updateFloat4 = this._updateFloat4ForUniform;
  35616. this.updateMatrix = this._updateMatrixForUniform;
  35617. this.updateVector3 = this._updateVector3ForUniform;
  35618. this.updateVector4 = this._updateVector4ForUniform;
  35619. this.updateColor3 = this._updateColor3ForUniform;
  35620. this.updateColor4 = this._updateColor4ForUniform;
  35621. }
  35622. }
  35623. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35624. // Properties
  35625. /**
  35626. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35627. * or just falling back on setUniformXXX calls.
  35628. */
  35629. get: function () {
  35630. return !this._noUBO;
  35631. },
  35632. enumerable: true,
  35633. configurable: true
  35634. });
  35635. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35636. /**
  35637. * Indicates if the WebGL underlying uniform buffer is in sync
  35638. * with the javascript cache data.
  35639. */
  35640. get: function () {
  35641. return !this._needSync;
  35642. },
  35643. enumerable: true,
  35644. configurable: true
  35645. });
  35646. /**
  35647. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35648. * Also, a dynamic UniformBuffer will disable cache verification and always
  35649. * update the underlying WebGL uniform buffer to the GPU.
  35650. */
  35651. UniformBuffer.prototype.isDynamic = function () {
  35652. return this._dynamic !== undefined;
  35653. };
  35654. /**
  35655. * The data cache on JS side.
  35656. */
  35657. UniformBuffer.prototype.getData = function () {
  35658. return this._bufferData;
  35659. };
  35660. /**
  35661. * The underlying WebGL Uniform buffer.
  35662. */
  35663. UniformBuffer.prototype.getBuffer = function () {
  35664. return this._buffer;
  35665. };
  35666. /**
  35667. * std140 layout specifies how to align data within an UBO structure.
  35668. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35669. * for specs.
  35670. */
  35671. UniformBuffer.prototype._fillAlignment = function (size) {
  35672. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35673. // and 4x4 matrices
  35674. // TODO : change if other types are used
  35675. var alignment;
  35676. if (size <= 2) {
  35677. alignment = size;
  35678. }
  35679. else {
  35680. alignment = 4;
  35681. }
  35682. if ((this._uniformLocationPointer % alignment) !== 0) {
  35683. var oldPointer = this._uniformLocationPointer;
  35684. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35685. var diff = this._uniformLocationPointer - oldPointer;
  35686. for (var i = 0; i < diff; i++) {
  35687. this._data.push(0);
  35688. }
  35689. }
  35690. };
  35691. /**
  35692. * Adds an uniform in the buffer.
  35693. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35694. * for the layout to be correct !
  35695. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35696. * @param {number|number[]} size Data size, or data directly.
  35697. */
  35698. UniformBuffer.prototype.addUniform = function (name, size) {
  35699. if (this._noUBO) {
  35700. return;
  35701. }
  35702. if (this._uniformLocations[name] !== undefined) {
  35703. // Already existing uniform
  35704. return;
  35705. }
  35706. // This function must be called in the order of the shader layout !
  35707. // size can be the size of the uniform, or data directly
  35708. var data;
  35709. if (size instanceof Array) {
  35710. data = size;
  35711. size = data.length;
  35712. }
  35713. else {
  35714. size = size;
  35715. data = [];
  35716. // Fill with zeros
  35717. for (var i = 0; i < size; i++) {
  35718. data.push(0);
  35719. }
  35720. }
  35721. this._fillAlignment(size);
  35722. this._uniformSizes[name] = size;
  35723. this._uniformLocations[name] = this._uniformLocationPointer;
  35724. this._uniformLocationPointer += size;
  35725. for (var i = 0; i < size; i++) {
  35726. this._data.push(data[i]);
  35727. }
  35728. this._needSync = true;
  35729. };
  35730. /**
  35731. * Wrapper for addUniform.
  35732. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35733. * @param {Matrix} mat A 4x4 matrix.
  35734. */
  35735. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35736. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35737. };
  35738. /**
  35739. * Wrapper for addUniform.
  35740. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35741. * @param {number} x
  35742. * @param {number} y
  35743. */
  35744. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35745. var temp = [x, y];
  35746. this.addUniform(name, temp);
  35747. };
  35748. /**
  35749. * Wrapper for addUniform.
  35750. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35751. * @param {number} x
  35752. * @param {number} y
  35753. * @param {number} z
  35754. */
  35755. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35756. var temp = [x, y, z];
  35757. this.addUniform(name, temp);
  35758. };
  35759. /**
  35760. * Wrapper for addUniform.
  35761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35762. * @param {Color3} color
  35763. */
  35764. UniformBuffer.prototype.addColor3 = function (name, color) {
  35765. var temp = new Array();
  35766. color.toArray(temp);
  35767. this.addUniform(name, temp);
  35768. };
  35769. /**
  35770. * Wrapper for addUniform.
  35771. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35772. * @param {Color3} color
  35773. * @param {number} alpha
  35774. */
  35775. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35776. var temp = new Array();
  35777. color.toArray(temp);
  35778. temp.push(alpha);
  35779. this.addUniform(name, temp);
  35780. };
  35781. /**
  35782. * Wrapper for addUniform.
  35783. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35784. * @param {Vector3} vector
  35785. */
  35786. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35787. var temp = new Array();
  35788. vector.toArray(temp);
  35789. this.addUniform(name, temp);
  35790. };
  35791. /**
  35792. * Wrapper for addUniform.
  35793. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35794. */
  35795. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35796. this.addUniform(name, 12);
  35797. };
  35798. /**
  35799. * Wrapper for addUniform.
  35800. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35801. */
  35802. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35803. this.addUniform(name, 8);
  35804. };
  35805. /**
  35806. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35807. */
  35808. UniformBuffer.prototype.create = function () {
  35809. if (this._noUBO) {
  35810. return;
  35811. }
  35812. if (this._buffer) {
  35813. return; // nothing to do
  35814. }
  35815. // See spec, alignment must be filled as a vec4
  35816. this._fillAlignment(4);
  35817. this._bufferData = new Float32Array(this._data);
  35818. this._rebuild();
  35819. this._needSync = true;
  35820. };
  35821. /** @hidden */
  35822. UniformBuffer.prototype._rebuild = function () {
  35823. if (this._noUBO) {
  35824. return;
  35825. }
  35826. if (this._dynamic) {
  35827. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35828. }
  35829. else {
  35830. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35831. }
  35832. };
  35833. /**
  35834. * Updates the WebGL Uniform Buffer on the GPU.
  35835. * If the `dynamic` flag is set to true, no cache comparison is done.
  35836. * Otherwise, the buffer will be updated only if the cache differs.
  35837. */
  35838. UniformBuffer.prototype.update = function () {
  35839. if (!this._buffer) {
  35840. this.create();
  35841. return;
  35842. }
  35843. if (!this._dynamic && !this._needSync) {
  35844. return;
  35845. }
  35846. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35847. this._needSync = false;
  35848. };
  35849. /**
  35850. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35851. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35852. * @param {number[]|Float32Array} data Flattened data
  35853. * @param {number} size Size of the data.
  35854. */
  35855. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35856. var location = this._uniformLocations[uniformName];
  35857. if (location === undefined) {
  35858. if (this._buffer) {
  35859. // Cannot add an uniform if the buffer is already created
  35860. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35861. return;
  35862. }
  35863. this.addUniform(uniformName, size);
  35864. location = this._uniformLocations[uniformName];
  35865. }
  35866. if (!this._buffer) {
  35867. this.create();
  35868. }
  35869. if (!this._dynamic) {
  35870. // Cache for static uniform buffers
  35871. var changed = false;
  35872. for (var i = 0; i < size; i++) {
  35873. if (this._bufferData[location + i] !== data[i]) {
  35874. changed = true;
  35875. this._bufferData[location + i] = data[i];
  35876. }
  35877. }
  35878. this._needSync = this._needSync || changed;
  35879. }
  35880. else {
  35881. // No cache for dynamic
  35882. for (var i = 0; i < size; i++) {
  35883. this._bufferData[location + i] = data[i];
  35884. }
  35885. }
  35886. };
  35887. // Update methods
  35888. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35889. // To match std140, matrix must be realigned
  35890. for (var i = 0; i < 3; i++) {
  35891. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35892. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35893. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35894. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35895. }
  35896. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35897. };
  35898. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35899. this._currentEffect.setMatrix3x3(name, matrix);
  35900. };
  35901. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35902. this._currentEffect.setMatrix2x2(name, matrix);
  35903. };
  35904. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35905. // To match std140, matrix must be realigned
  35906. for (var i = 0; i < 2; i++) {
  35907. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35908. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35909. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35910. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35911. }
  35912. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35913. };
  35914. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35915. this._currentEffect.setFloat(name, x);
  35916. };
  35917. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35918. UniformBuffer._tempBuffer[0] = x;
  35919. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35920. };
  35921. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35922. if (suffix === void 0) { suffix = ""; }
  35923. this._currentEffect.setFloat2(name + suffix, x, y);
  35924. };
  35925. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35926. if (suffix === void 0) { suffix = ""; }
  35927. UniformBuffer._tempBuffer[0] = x;
  35928. UniformBuffer._tempBuffer[1] = y;
  35929. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35930. };
  35931. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35932. if (suffix === void 0) { suffix = ""; }
  35933. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35934. };
  35935. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35936. if (suffix === void 0) { suffix = ""; }
  35937. UniformBuffer._tempBuffer[0] = x;
  35938. UniformBuffer._tempBuffer[1] = y;
  35939. UniformBuffer._tempBuffer[2] = z;
  35940. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35941. };
  35942. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35943. if (suffix === void 0) { suffix = ""; }
  35944. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35945. };
  35946. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35947. if (suffix === void 0) { suffix = ""; }
  35948. UniformBuffer._tempBuffer[0] = x;
  35949. UniformBuffer._tempBuffer[1] = y;
  35950. UniformBuffer._tempBuffer[2] = z;
  35951. UniformBuffer._tempBuffer[3] = w;
  35952. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35953. };
  35954. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35955. this._currentEffect.setMatrix(name, mat);
  35956. };
  35957. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35958. this.updateUniform(name, mat.toArray(), 16);
  35959. };
  35960. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35961. this._currentEffect.setVector3(name, vector);
  35962. };
  35963. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35964. vector.toArray(UniformBuffer._tempBuffer);
  35965. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35966. };
  35967. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35968. this._currentEffect.setVector4(name, vector);
  35969. };
  35970. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35971. vector.toArray(UniformBuffer._tempBuffer);
  35972. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35973. };
  35974. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35975. if (suffix === void 0) { suffix = ""; }
  35976. this._currentEffect.setColor3(name + suffix, color);
  35977. };
  35978. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35979. if (suffix === void 0) { suffix = ""; }
  35980. color.toArray(UniformBuffer._tempBuffer);
  35981. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35982. };
  35983. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35984. if (suffix === void 0) { suffix = ""; }
  35985. this._currentEffect.setColor4(name + suffix, color, alpha);
  35986. };
  35987. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35988. if (suffix === void 0) { suffix = ""; }
  35989. color.toArray(UniformBuffer._tempBuffer);
  35990. UniformBuffer._tempBuffer[3] = alpha;
  35991. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35992. };
  35993. /**
  35994. * Sets a sampler uniform on the effect.
  35995. * @param {string} name Name of the sampler.
  35996. * @param {Texture} texture
  35997. */
  35998. UniformBuffer.prototype.setTexture = function (name, texture) {
  35999. this._currentEffect.setTexture(name, texture);
  36000. };
  36001. /**
  36002. * Directly updates the value of the uniform in the cache AND on the GPU.
  36003. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36004. * @param {number[]|Float32Array} data Flattened data
  36005. */
  36006. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36007. this.updateUniform(uniformName, data, data.length);
  36008. this.update();
  36009. };
  36010. /**
  36011. * Binds this uniform buffer to an effect.
  36012. * @param {Effect} effect
  36013. * @param {string} name Name of the uniform block in the shader.
  36014. */
  36015. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36016. this._currentEffect = effect;
  36017. if (this._noUBO || !this._buffer) {
  36018. return;
  36019. }
  36020. effect.bindUniformBuffer(this._buffer, name);
  36021. };
  36022. /**
  36023. * Disposes the uniform buffer.
  36024. */
  36025. UniformBuffer.prototype.dispose = function () {
  36026. if (this._noUBO) {
  36027. return;
  36028. }
  36029. var index = this._engine._uniformBuffers.indexOf(this);
  36030. if (index !== -1) {
  36031. this._engine._uniformBuffers.splice(index, 1);
  36032. }
  36033. if (!this._buffer) {
  36034. return;
  36035. }
  36036. if (this._engine._releaseBuffer(this._buffer)) {
  36037. this._buffer = null;
  36038. }
  36039. };
  36040. // Pool for avoiding memory leaks
  36041. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36042. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36043. return UniformBuffer;
  36044. }());
  36045. BABYLON.UniformBuffer = UniformBuffer;
  36046. })(BABYLON || (BABYLON = {}));
  36047. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36048. var BABYLON;
  36049. (function (BABYLON) {
  36050. /**
  36051. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36052. */
  36053. var VertexData = /** @class */ (function () {
  36054. function VertexData() {
  36055. }
  36056. /**
  36057. * Uses the passed data array to set the set the values for the specified kind of data
  36058. * @param data a linear array of floating numbers
  36059. * @param kind the type of data that is being set, eg positions, colors etc
  36060. */
  36061. VertexData.prototype.set = function (data, kind) {
  36062. switch (kind) {
  36063. case BABYLON.VertexBuffer.PositionKind:
  36064. this.positions = data;
  36065. break;
  36066. case BABYLON.VertexBuffer.NormalKind:
  36067. this.normals = data;
  36068. break;
  36069. case BABYLON.VertexBuffer.TangentKind:
  36070. this.tangents = data;
  36071. break;
  36072. case BABYLON.VertexBuffer.UVKind:
  36073. this.uvs = data;
  36074. break;
  36075. case BABYLON.VertexBuffer.UV2Kind:
  36076. this.uvs2 = data;
  36077. break;
  36078. case BABYLON.VertexBuffer.UV3Kind:
  36079. this.uvs3 = data;
  36080. break;
  36081. case BABYLON.VertexBuffer.UV4Kind:
  36082. this.uvs4 = data;
  36083. break;
  36084. case BABYLON.VertexBuffer.UV5Kind:
  36085. this.uvs5 = data;
  36086. break;
  36087. case BABYLON.VertexBuffer.UV6Kind:
  36088. this.uvs6 = data;
  36089. break;
  36090. case BABYLON.VertexBuffer.ColorKind:
  36091. this.colors = data;
  36092. break;
  36093. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36094. this.matricesIndices = data;
  36095. break;
  36096. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36097. this.matricesWeights = data;
  36098. break;
  36099. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36100. this.matricesIndicesExtra = data;
  36101. break;
  36102. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36103. this.matricesWeightsExtra = data;
  36104. break;
  36105. }
  36106. };
  36107. /**
  36108. * Associates the vertexData to the passed Mesh.
  36109. * Sets it as updatable or not (default `false`)
  36110. * @param mesh the mesh the vertexData is applied to
  36111. * @param updatable when used and having the value true allows new data to update the vertexData
  36112. * @returns the VertexData
  36113. */
  36114. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36115. this._applyTo(mesh, updatable);
  36116. return this;
  36117. };
  36118. /**
  36119. * Associates the vertexData to the passed Geometry.
  36120. * Sets it as updatable or not (default `false`)
  36121. * @param geometry the geometry the vertexData is applied to
  36122. * @param updatable when used and having the value true allows new data to update the vertexData
  36123. * @returns VertexData
  36124. */
  36125. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36126. this._applyTo(geometry, updatable);
  36127. return this;
  36128. };
  36129. /**
  36130. * Updates the associated mesh
  36131. * @param mesh the mesh to be updated
  36132. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36133. * @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
  36134. * @returns VertexData
  36135. */
  36136. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36137. this._update(mesh);
  36138. return this;
  36139. };
  36140. /**
  36141. * Updates the associated geometry
  36142. * @param geometry the geometry to be updated
  36143. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36144. * @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
  36145. * @returns VertexData.
  36146. */
  36147. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36148. this._update(geometry);
  36149. return this;
  36150. };
  36151. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36152. if (updatable === void 0) { updatable = false; }
  36153. if (this.positions) {
  36154. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36155. }
  36156. if (this.normals) {
  36157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36158. }
  36159. if (this.tangents) {
  36160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36161. }
  36162. if (this.uvs) {
  36163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36164. }
  36165. if (this.uvs2) {
  36166. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36167. }
  36168. if (this.uvs3) {
  36169. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36170. }
  36171. if (this.uvs4) {
  36172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36173. }
  36174. if (this.uvs5) {
  36175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36176. }
  36177. if (this.uvs6) {
  36178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36179. }
  36180. if (this.colors) {
  36181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36182. }
  36183. if (this.matricesIndices) {
  36184. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36185. }
  36186. if (this.matricesWeights) {
  36187. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36188. }
  36189. if (this.matricesIndicesExtra) {
  36190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36191. }
  36192. if (this.matricesWeightsExtra) {
  36193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36194. }
  36195. if (this.indices) {
  36196. meshOrGeometry.setIndices(this.indices, null, updatable);
  36197. }
  36198. else {
  36199. meshOrGeometry.setIndices([], null);
  36200. }
  36201. return this;
  36202. };
  36203. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36204. if (this.positions) {
  36205. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36206. }
  36207. if (this.normals) {
  36208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36209. }
  36210. if (this.tangents) {
  36211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36212. }
  36213. if (this.uvs) {
  36214. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36215. }
  36216. if (this.uvs2) {
  36217. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36218. }
  36219. if (this.uvs3) {
  36220. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36221. }
  36222. if (this.uvs4) {
  36223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36224. }
  36225. if (this.uvs5) {
  36226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36227. }
  36228. if (this.uvs6) {
  36229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36230. }
  36231. if (this.colors) {
  36232. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36233. }
  36234. if (this.matricesIndices) {
  36235. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36236. }
  36237. if (this.matricesWeights) {
  36238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36239. }
  36240. if (this.matricesIndicesExtra) {
  36241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36242. }
  36243. if (this.matricesWeightsExtra) {
  36244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36245. }
  36246. if (this.indices) {
  36247. meshOrGeometry.setIndices(this.indices, null);
  36248. }
  36249. return this;
  36250. };
  36251. /**
  36252. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36253. * @param matrix the transforming matrix
  36254. * @returns the VertexData
  36255. */
  36256. VertexData.prototype.transform = function (matrix) {
  36257. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36258. var transformed = BABYLON.Vector3.Zero();
  36259. var index;
  36260. if (this.positions) {
  36261. var position = BABYLON.Vector3.Zero();
  36262. for (index = 0; index < this.positions.length; index += 3) {
  36263. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36264. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36265. this.positions[index] = transformed.x;
  36266. this.positions[index + 1] = transformed.y;
  36267. this.positions[index + 2] = transformed.z;
  36268. }
  36269. }
  36270. if (this.normals) {
  36271. var normal = BABYLON.Vector3.Zero();
  36272. for (index = 0; index < this.normals.length; index += 3) {
  36273. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36274. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36275. this.normals[index] = transformed.x;
  36276. this.normals[index + 1] = transformed.y;
  36277. this.normals[index + 2] = transformed.z;
  36278. }
  36279. }
  36280. if (this.tangents) {
  36281. var tangent = BABYLON.Vector4.Zero();
  36282. var tangentTransformed = BABYLON.Vector4.Zero();
  36283. for (index = 0; index < this.tangents.length; index += 4) {
  36284. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36285. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36286. this.tangents[index] = tangentTransformed.x;
  36287. this.tangents[index + 1] = tangentTransformed.y;
  36288. this.tangents[index + 2] = tangentTransformed.z;
  36289. this.tangents[index + 3] = tangentTransformed.w;
  36290. }
  36291. }
  36292. if (flip && this.indices) {
  36293. for (index = 0; index < this.indices.length; index += 3) {
  36294. var tmp = this.indices[index + 1];
  36295. this.indices[index + 1] = this.indices[index + 2];
  36296. this.indices[index + 2] = tmp;
  36297. }
  36298. }
  36299. return this;
  36300. };
  36301. /**
  36302. * Merges the passed VertexData into the current one
  36303. * @param other the VertexData to be merged into the current one
  36304. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36305. * @returns the modified VertexData
  36306. */
  36307. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36308. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36309. this._validate();
  36310. other._validate();
  36311. if (!this.normals !== !other.normals ||
  36312. !this.tangents !== !other.tangents ||
  36313. !this.uvs !== !other.uvs ||
  36314. !this.uvs2 !== !other.uvs2 ||
  36315. !this.uvs3 !== !other.uvs3 ||
  36316. !this.uvs4 !== !other.uvs4 ||
  36317. !this.uvs5 !== !other.uvs5 ||
  36318. !this.uvs6 !== !other.uvs6 ||
  36319. !this.colors !== !other.colors ||
  36320. !this.matricesIndices !== !other.matricesIndices ||
  36321. !this.matricesWeights !== !other.matricesWeights ||
  36322. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36323. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36324. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36325. }
  36326. if (other.indices) {
  36327. if (!this.indices) {
  36328. this.indices = [];
  36329. }
  36330. var offset = this.positions ? this.positions.length / 3 : 0;
  36331. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36332. if (isSrcTypedArray) {
  36333. var len = this.indices.length + other.indices.length;
  36334. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36335. temp.set(this.indices);
  36336. var decal = this.indices.length;
  36337. for (var index = 0; index < other.indices.length; index++) {
  36338. temp[decal + index] = other.indices[index] + offset;
  36339. }
  36340. this.indices = temp;
  36341. }
  36342. else {
  36343. for (var index = 0; index < other.indices.length; index++) {
  36344. this.indices.push(other.indices[index] + offset);
  36345. }
  36346. }
  36347. }
  36348. this.positions = this._mergeElement(this.positions, other.positions);
  36349. this.normals = this._mergeElement(this.normals, other.normals);
  36350. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36351. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36352. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36353. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36354. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36355. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36356. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36357. this.colors = this._mergeElement(this.colors, other.colors);
  36358. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36359. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36360. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36361. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36362. return this;
  36363. };
  36364. VertexData.prototype._mergeElement = function (source, other) {
  36365. if (!source) {
  36366. return other;
  36367. }
  36368. if (!other) {
  36369. return source;
  36370. }
  36371. var len = other.length + source.length;
  36372. var isSrcTypedArray = source instanceof Float32Array;
  36373. var isOthTypedArray = other instanceof Float32Array;
  36374. // use non-loop method when the source is Float32Array
  36375. if (isSrcTypedArray) {
  36376. var ret32 = new Float32Array(len);
  36377. ret32.set(source);
  36378. ret32.set(other, source.length);
  36379. return ret32;
  36380. // source is number[], when other is also use concat
  36381. }
  36382. else if (!isOthTypedArray) {
  36383. return source.concat(other);
  36384. // source is a number[], but other is a Float32Array, loop required
  36385. }
  36386. else {
  36387. var ret = source.slice(0); // copy source to a separate array
  36388. for (var i = 0, len = other.length; i < len; i++) {
  36389. ret.push(other[i]);
  36390. }
  36391. return ret;
  36392. }
  36393. };
  36394. VertexData.prototype._validate = function () {
  36395. if (!this.positions) {
  36396. throw new Error("Positions are required");
  36397. }
  36398. var getElementCount = function (kind, values) {
  36399. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36400. if ((values.length % stride) !== 0) {
  36401. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36402. }
  36403. return values.length / stride;
  36404. };
  36405. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36406. var validateElementCount = function (kind, values) {
  36407. var elementCount = getElementCount(kind, values);
  36408. if (elementCount !== positionsElementCount) {
  36409. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36410. }
  36411. };
  36412. if (this.normals)
  36413. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36414. if (this.tangents)
  36415. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36416. if (this.uvs)
  36417. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36418. if (this.uvs2)
  36419. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36420. if (this.uvs3)
  36421. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36422. if (this.uvs4)
  36423. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36424. if (this.uvs5)
  36425. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36426. if (this.uvs6)
  36427. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36428. if (this.colors)
  36429. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36430. if (this.matricesIndices)
  36431. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36432. if (this.matricesWeights)
  36433. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36434. if (this.matricesIndicesExtra)
  36435. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36436. if (this.matricesWeightsExtra)
  36437. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36438. };
  36439. /**
  36440. * Serializes the VertexData
  36441. * @returns a serialized object
  36442. */
  36443. VertexData.prototype.serialize = function () {
  36444. var serializationObject = this.serialize();
  36445. if (this.positions) {
  36446. serializationObject.positions = this.positions;
  36447. }
  36448. if (this.normals) {
  36449. serializationObject.normals = this.normals;
  36450. }
  36451. if (this.tangents) {
  36452. serializationObject.tangents = this.tangents;
  36453. }
  36454. if (this.uvs) {
  36455. serializationObject.uvs = this.uvs;
  36456. }
  36457. if (this.uvs2) {
  36458. serializationObject.uvs2 = this.uvs2;
  36459. }
  36460. if (this.uvs3) {
  36461. serializationObject.uvs3 = this.uvs3;
  36462. }
  36463. if (this.uvs4) {
  36464. serializationObject.uvs4 = this.uvs4;
  36465. }
  36466. if (this.uvs5) {
  36467. serializationObject.uvs5 = this.uvs5;
  36468. }
  36469. if (this.uvs6) {
  36470. serializationObject.uvs6 = this.uvs6;
  36471. }
  36472. if (this.colors) {
  36473. serializationObject.colors = this.colors;
  36474. }
  36475. if (this.matricesIndices) {
  36476. serializationObject.matricesIndices = this.matricesIndices;
  36477. serializationObject.matricesIndices._isExpanded = true;
  36478. }
  36479. if (this.matricesWeights) {
  36480. serializationObject.matricesWeights = this.matricesWeights;
  36481. }
  36482. if (this.matricesIndicesExtra) {
  36483. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36484. serializationObject.matricesIndicesExtra._isExpanded = true;
  36485. }
  36486. if (this.matricesWeightsExtra) {
  36487. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36488. }
  36489. serializationObject.indices = this.indices;
  36490. return serializationObject;
  36491. };
  36492. // Statics
  36493. /**
  36494. * Extracts the vertexData from a mesh
  36495. * @param mesh the mesh from which to extract the VertexData
  36496. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36497. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36498. * @returns the object VertexData associated to the passed mesh
  36499. */
  36500. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36501. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36502. };
  36503. /**
  36504. * Extracts the vertexData from the geometry
  36505. * @param geometry the geometry from which to extract the VertexData
  36506. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36507. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36508. * @returns the object VertexData associated to the passed mesh
  36509. */
  36510. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36511. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36512. };
  36513. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36514. var result = new VertexData();
  36515. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36516. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36517. }
  36518. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36519. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36520. }
  36521. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36522. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36523. }
  36524. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36525. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36526. }
  36527. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36528. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36529. }
  36530. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36531. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36532. }
  36533. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36534. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36535. }
  36536. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36537. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36538. }
  36539. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36540. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36541. }
  36542. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36543. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36544. }
  36545. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36546. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36547. }
  36548. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36549. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36550. }
  36551. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36552. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36553. }
  36554. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36555. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36556. }
  36557. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36558. return result;
  36559. };
  36560. /**
  36561. * Creates the VertexData for a Ribbon
  36562. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36563. * * pathArray array of paths, each of which an array of successive Vector3
  36564. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36565. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36566. * * 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
  36567. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36568. * * 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)
  36569. * * 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)
  36570. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36571. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36572. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36573. * @returns the VertexData of the ribbon
  36574. */
  36575. VertexData.CreateRibbon = function (options) {
  36576. var pathArray = options.pathArray;
  36577. var closeArray = options.closeArray || false;
  36578. var closePath = options.closePath || false;
  36579. var invertUV = options.invertUV || false;
  36580. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36581. var offset = options.offset || defaultOffset;
  36582. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36583. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36584. var customUV = options.uvs;
  36585. var customColors = options.colors;
  36586. var positions = [];
  36587. var indices = [];
  36588. var normals = [];
  36589. var uvs = [];
  36590. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36591. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36592. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36593. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36594. var minlg; // minimal length among all paths from pathArray
  36595. var lg = []; // array of path lengths : nb of vertex per path
  36596. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36597. var p; // path iterator
  36598. var i; // point iterator
  36599. var j; // point iterator
  36600. // if single path in pathArray
  36601. if (pathArray.length < 2) {
  36602. var ar1 = [];
  36603. var ar2 = [];
  36604. for (i = 0; i < pathArray[0].length - offset; i++) {
  36605. ar1.push(pathArray[0][i]);
  36606. ar2.push(pathArray[0][i + offset]);
  36607. }
  36608. pathArray = [ar1, ar2];
  36609. }
  36610. // positions and horizontal distances (u)
  36611. var idc = 0;
  36612. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36613. var path;
  36614. var l;
  36615. minlg = pathArray[0].length;
  36616. var vectlg;
  36617. var dist;
  36618. for (p = 0; p < pathArray.length; p++) {
  36619. uTotalDistance[p] = 0;
  36620. us[p] = [0];
  36621. path = pathArray[p];
  36622. l = path.length;
  36623. minlg = (minlg < l) ? minlg : l;
  36624. j = 0;
  36625. while (j < l) {
  36626. positions.push(path[j].x, path[j].y, path[j].z);
  36627. if (j > 0) {
  36628. vectlg = path[j].subtract(path[j - 1]).length();
  36629. dist = vectlg + uTotalDistance[p];
  36630. us[p].push(dist);
  36631. uTotalDistance[p] = dist;
  36632. }
  36633. j++;
  36634. }
  36635. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36636. j--;
  36637. positions.push(path[0].x, path[0].y, path[0].z);
  36638. vectlg = path[j].subtract(path[0]).length();
  36639. dist = vectlg + uTotalDistance[p];
  36640. us[p].push(dist);
  36641. uTotalDistance[p] = dist;
  36642. }
  36643. lg[p] = l + closePathCorr;
  36644. idx[p] = idc;
  36645. idc += (l + closePathCorr);
  36646. }
  36647. // vertical distances (v)
  36648. var path1;
  36649. var path2;
  36650. var vertex1 = null;
  36651. var vertex2 = null;
  36652. for (i = 0; i < minlg + closePathCorr; i++) {
  36653. vTotalDistance[i] = 0;
  36654. vs[i] = [0];
  36655. for (p = 0; p < pathArray.length - 1; p++) {
  36656. path1 = pathArray[p];
  36657. path2 = pathArray[p + 1];
  36658. if (i === minlg) { // closePath
  36659. vertex1 = path1[0];
  36660. vertex2 = path2[0];
  36661. }
  36662. else {
  36663. vertex1 = path1[i];
  36664. vertex2 = path2[i];
  36665. }
  36666. vectlg = vertex2.subtract(vertex1).length();
  36667. dist = vectlg + vTotalDistance[i];
  36668. vs[i].push(dist);
  36669. vTotalDistance[i] = dist;
  36670. }
  36671. if (closeArray && vertex2 && vertex1) {
  36672. path1 = pathArray[p];
  36673. path2 = pathArray[0];
  36674. if (i === minlg) { // closePath
  36675. vertex2 = path2[0];
  36676. }
  36677. vectlg = vertex2.subtract(vertex1).length();
  36678. dist = vectlg + vTotalDistance[i];
  36679. vTotalDistance[i] = dist;
  36680. }
  36681. }
  36682. // uvs
  36683. var u;
  36684. var v;
  36685. if (customUV) {
  36686. for (p = 0; p < customUV.length; p++) {
  36687. uvs.push(customUV[p].x, customUV[p].y);
  36688. }
  36689. }
  36690. else {
  36691. for (p = 0; p < pathArray.length; p++) {
  36692. for (i = 0; i < minlg + closePathCorr; i++) {
  36693. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36694. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36695. if (invertUV) {
  36696. uvs.push(v, u);
  36697. }
  36698. else {
  36699. uvs.push(u, v);
  36700. }
  36701. }
  36702. }
  36703. }
  36704. // indices
  36705. p = 0; // path index
  36706. var pi = 0; // positions array index
  36707. var l1 = lg[p] - 1; // path1 length
  36708. var l2 = lg[p + 1] - 1; // path2 length
  36709. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36710. var shft = idx[1] - idx[0]; // shift
  36711. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36712. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36713. // 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
  36714. indices.push(pi, pi + shft, pi + 1);
  36715. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36716. pi += 1;
  36717. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36718. p++;
  36719. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36720. shft = idx[0] - idx[p];
  36721. l1 = lg[p] - 1;
  36722. l2 = lg[0] - 1;
  36723. }
  36724. else {
  36725. shft = idx[p + 1] - idx[p];
  36726. l1 = lg[p] - 1;
  36727. l2 = lg[p + 1] - 1;
  36728. }
  36729. pi = idx[p];
  36730. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36731. }
  36732. }
  36733. // normals
  36734. VertexData.ComputeNormals(positions, indices, normals);
  36735. if (closePath) { // update both the first and last vertex normals to their average value
  36736. var indexFirst = 0;
  36737. var indexLast = 0;
  36738. for (p = 0; p < pathArray.length; p++) {
  36739. indexFirst = idx[p] * 3;
  36740. if (p + 1 < pathArray.length) {
  36741. indexLast = (idx[p + 1] - 1) * 3;
  36742. }
  36743. else {
  36744. indexLast = normals.length - 3;
  36745. }
  36746. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36747. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36748. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36749. normals[indexLast] = normals[indexFirst];
  36750. normals[indexLast + 1] = normals[indexFirst + 1];
  36751. normals[indexLast + 2] = normals[indexFirst + 2];
  36752. }
  36753. }
  36754. // sides
  36755. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36756. // Colors
  36757. var colors = null;
  36758. if (customColors) {
  36759. colors = new Float32Array(customColors.length * 4);
  36760. for (var c = 0; c < customColors.length; c++) {
  36761. colors[c * 4] = customColors[c].r;
  36762. colors[c * 4 + 1] = customColors[c].g;
  36763. colors[c * 4 + 2] = customColors[c].b;
  36764. colors[c * 4 + 3] = customColors[c].a;
  36765. }
  36766. }
  36767. // Result
  36768. var vertexData = new VertexData();
  36769. var positions32 = new Float32Array(positions);
  36770. var normals32 = new Float32Array(normals);
  36771. var uvs32 = new Float32Array(uvs);
  36772. vertexData.indices = indices;
  36773. vertexData.positions = positions32;
  36774. vertexData.normals = normals32;
  36775. vertexData.uvs = uvs32;
  36776. if (colors) {
  36777. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36778. }
  36779. if (closePath) {
  36780. vertexData._idx = idx;
  36781. }
  36782. return vertexData;
  36783. };
  36784. /**
  36785. * Creates the VertexData for a box
  36786. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36787. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36788. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36789. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36790. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36791. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36792. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36793. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36794. * * 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)
  36795. * * 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)
  36796. * @returns the VertexData of the box
  36797. */
  36798. VertexData.CreateBox = function (options) {
  36799. var normalsSource = [
  36800. new BABYLON.Vector3(0, 0, 1),
  36801. new BABYLON.Vector3(0, 0, -1),
  36802. new BABYLON.Vector3(1, 0, 0),
  36803. new BABYLON.Vector3(-1, 0, 0),
  36804. new BABYLON.Vector3(0, 1, 0),
  36805. new BABYLON.Vector3(0, -1, 0)
  36806. ];
  36807. var indices = [];
  36808. var positions = [];
  36809. var normals = [];
  36810. var uvs = [];
  36811. var width = options.width || options.size || 1;
  36812. var height = options.height || options.size || 1;
  36813. var depth = options.depth || options.size || 1;
  36814. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36815. var faceUV = options.faceUV || new Array(6);
  36816. var faceColors = options.faceColors;
  36817. var colors = [];
  36818. // default face colors and UV if undefined
  36819. for (var f = 0; f < 6; f++) {
  36820. if (faceUV[f] === undefined) {
  36821. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36822. }
  36823. if (faceColors && faceColors[f] === undefined) {
  36824. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36825. }
  36826. }
  36827. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36828. // Create each face in turn.
  36829. for (var index = 0; index < normalsSource.length; index++) {
  36830. var normal = normalsSource[index];
  36831. // Get two vectors perpendicular to the face normal and to each other.
  36832. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36833. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36834. // Six indices (two triangles) per face.
  36835. var verticesLength = positions.length / 3;
  36836. indices.push(verticesLength);
  36837. indices.push(verticesLength + 1);
  36838. indices.push(verticesLength + 2);
  36839. indices.push(verticesLength);
  36840. indices.push(verticesLength + 2);
  36841. indices.push(verticesLength + 3);
  36842. // Four vertices per face.
  36843. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36844. positions.push(vertex.x, vertex.y, vertex.z);
  36845. normals.push(normal.x, normal.y, normal.z);
  36846. uvs.push(faceUV[index].z, faceUV[index].w);
  36847. if (faceColors) {
  36848. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36849. }
  36850. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36851. positions.push(vertex.x, vertex.y, vertex.z);
  36852. normals.push(normal.x, normal.y, normal.z);
  36853. uvs.push(faceUV[index].x, faceUV[index].w);
  36854. if (faceColors) {
  36855. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36856. }
  36857. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36858. positions.push(vertex.x, vertex.y, vertex.z);
  36859. normals.push(normal.x, normal.y, normal.z);
  36860. uvs.push(faceUV[index].x, faceUV[index].y);
  36861. if (faceColors) {
  36862. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36863. }
  36864. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36865. positions.push(vertex.x, vertex.y, vertex.z);
  36866. normals.push(normal.x, normal.y, normal.z);
  36867. uvs.push(faceUV[index].z, faceUV[index].y);
  36868. if (faceColors) {
  36869. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36870. }
  36871. }
  36872. // sides
  36873. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36874. // Result
  36875. var vertexData = new VertexData();
  36876. vertexData.indices = indices;
  36877. vertexData.positions = positions;
  36878. vertexData.normals = normals;
  36879. vertexData.uvs = uvs;
  36880. if (faceColors) {
  36881. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36882. vertexData.colors = totalColors;
  36883. }
  36884. return vertexData;
  36885. };
  36886. /**
  36887. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36888. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36889. * * segments sets the number of horizontal strips optional, default 32
  36890. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36891. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36892. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36893. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36894. * * 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
  36895. * * 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
  36896. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36897. * * 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)
  36898. * * 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)
  36899. * @returns the VertexData of the ellipsoid
  36900. */
  36901. VertexData.CreateSphere = function (options) {
  36902. var segments = options.segments || 32;
  36903. var diameterX = options.diameterX || options.diameter || 1;
  36904. var diameterY = options.diameterY || options.diameter || 1;
  36905. var diameterZ = options.diameterZ || options.diameter || 1;
  36906. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36907. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36908. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36909. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36910. var totalZRotationSteps = 2 + segments;
  36911. var totalYRotationSteps = 2 * totalZRotationSteps;
  36912. var indices = [];
  36913. var positions = [];
  36914. var normals = [];
  36915. var uvs = [];
  36916. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36917. var normalizedZ = zRotationStep / totalZRotationSteps;
  36918. var angleZ = normalizedZ * Math.PI * slice;
  36919. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36920. var normalizedY = yRotationStep / totalYRotationSteps;
  36921. var angleY = normalizedY * Math.PI * 2 * arc;
  36922. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36923. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36924. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36925. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36926. var vertex = complete.multiply(radius);
  36927. var normal = complete.divide(radius).normalize();
  36928. positions.push(vertex.x, vertex.y, vertex.z);
  36929. normals.push(normal.x, normal.y, normal.z);
  36930. uvs.push(normalizedY, normalizedZ);
  36931. }
  36932. if (zRotationStep > 0) {
  36933. var verticesCount = positions.length / 3;
  36934. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36935. indices.push((firstIndex));
  36936. indices.push((firstIndex + 1));
  36937. indices.push(firstIndex + totalYRotationSteps + 1);
  36938. indices.push((firstIndex + totalYRotationSteps + 1));
  36939. indices.push((firstIndex + 1));
  36940. indices.push((firstIndex + totalYRotationSteps + 2));
  36941. }
  36942. }
  36943. }
  36944. // Sides
  36945. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36946. // Result
  36947. var vertexData = new VertexData();
  36948. vertexData.indices = indices;
  36949. vertexData.positions = positions;
  36950. vertexData.normals = normals;
  36951. vertexData.uvs = uvs;
  36952. return vertexData;
  36953. };
  36954. /**
  36955. * Creates the VertexData for a cylinder, cone or prism
  36956. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36957. * * height sets the height (y direction) of the cylinder, optional, default 2
  36958. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36959. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36960. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36961. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36962. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36963. * * 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
  36964. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36965. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36966. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36967. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36968. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36969. * * 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)
  36970. * * 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)
  36971. * @returns the VertexData of the cylinder, cone or prism
  36972. */
  36973. VertexData.CreateCylinder = function (options) {
  36974. var height = options.height || 2;
  36975. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36976. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36977. var tessellation = options.tessellation || 24;
  36978. var subdivisions = options.subdivisions || 1;
  36979. var hasRings = options.hasRings ? true : false;
  36980. var enclose = options.enclose ? true : false;
  36981. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36982. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36983. var faceUV = options.faceUV || new Array(3);
  36984. var faceColors = options.faceColors;
  36985. // default face colors and UV if undefined
  36986. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36987. var ringNb = (hasRings) ? subdivisions : 1;
  36988. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36989. var f;
  36990. for (f = 0; f < surfaceNb; f++) {
  36991. if (faceColors && faceColors[f] === undefined) {
  36992. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36993. }
  36994. }
  36995. for (f = 0; f < surfaceNb; f++) {
  36996. if (faceUV && faceUV[f] === undefined) {
  36997. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36998. }
  36999. }
  37000. var indices = new Array();
  37001. var positions = new Array();
  37002. var normals = new Array();
  37003. var uvs = new Array();
  37004. var colors = new Array();
  37005. var angle_step = Math.PI * 2 * arc / tessellation;
  37006. var angle;
  37007. var h;
  37008. var radius;
  37009. var tan = (diameterBottom - diameterTop) / 2 / height;
  37010. var ringVertex = BABYLON.Vector3.Zero();
  37011. var ringNormal = BABYLON.Vector3.Zero();
  37012. var ringFirstVertex = BABYLON.Vector3.Zero();
  37013. var ringFirstNormal = BABYLON.Vector3.Zero();
  37014. var quadNormal = BABYLON.Vector3.Zero();
  37015. var Y = BABYLON.Axis.Y;
  37016. // positions, normals, uvs
  37017. var i;
  37018. var j;
  37019. var r;
  37020. var ringIdx = 1;
  37021. var s = 1; // surface index
  37022. var cs = 0;
  37023. var v = 0;
  37024. for (i = 0; i <= subdivisions; i++) {
  37025. h = i / subdivisions;
  37026. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37027. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37028. for (r = 0; r < ringIdx; r++) {
  37029. if (hasRings) {
  37030. s += r;
  37031. }
  37032. if (enclose) {
  37033. s += 2 * r;
  37034. }
  37035. for (j = 0; j <= tessellation; j++) {
  37036. angle = j * angle_step;
  37037. // position
  37038. ringVertex.x = Math.cos(-angle) * radius;
  37039. ringVertex.y = -height / 2 + h * height;
  37040. ringVertex.z = Math.sin(-angle) * radius;
  37041. // normal
  37042. if (diameterTop === 0 && i === subdivisions) {
  37043. // if no top cap, reuse former normals
  37044. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37045. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37046. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37047. }
  37048. else {
  37049. ringNormal.x = ringVertex.x;
  37050. ringNormal.z = ringVertex.z;
  37051. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37052. ringNormal.normalize();
  37053. }
  37054. // keep first ring vertex values for enclose
  37055. if (j === 0) {
  37056. ringFirstVertex.copyFrom(ringVertex);
  37057. ringFirstNormal.copyFrom(ringNormal);
  37058. }
  37059. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37060. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37061. if (hasRings) {
  37062. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37063. }
  37064. else {
  37065. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37066. }
  37067. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37068. if (faceColors) {
  37069. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37070. }
  37071. }
  37072. // if enclose, add four vertices and their dedicated normals
  37073. if (arc !== 1 && enclose) {
  37074. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37075. positions.push(0, ringVertex.y, 0);
  37076. positions.push(0, ringVertex.y, 0);
  37077. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37078. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37079. quadNormal.normalize();
  37080. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37081. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37082. quadNormal.normalize();
  37083. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37084. if (hasRings) {
  37085. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37086. }
  37087. else {
  37088. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37089. }
  37090. uvs.push(faceUV[s + 1].x, v);
  37091. uvs.push(faceUV[s + 1].z, v);
  37092. if (hasRings) {
  37093. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37094. }
  37095. else {
  37096. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37097. }
  37098. uvs.push(faceUV[s + 2].x, v);
  37099. uvs.push(faceUV[s + 2].z, v);
  37100. if (faceColors) {
  37101. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37102. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37103. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37104. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37105. }
  37106. }
  37107. if (cs !== s) {
  37108. cs = s;
  37109. }
  37110. }
  37111. }
  37112. // indices
  37113. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37114. var s;
  37115. i = 0;
  37116. for (s = 0; s < subdivisions; s++) {
  37117. var i0 = 0;
  37118. var i1 = 0;
  37119. var i2 = 0;
  37120. var i3 = 0;
  37121. for (j = 0; j < tessellation; j++) {
  37122. i0 = i * (e + 1) + j;
  37123. i1 = (i + 1) * (e + 1) + j;
  37124. i2 = i * (e + 1) + (j + 1);
  37125. i3 = (i + 1) * (e + 1) + (j + 1);
  37126. indices.push(i0, i1, i2);
  37127. indices.push(i3, i2, i1);
  37128. }
  37129. if (arc !== 1 && enclose) { // if enclose, add two quads
  37130. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37131. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37132. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37133. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37134. }
  37135. i = (hasRings) ? (i + 2) : (i + 1);
  37136. }
  37137. // Caps
  37138. var createCylinderCap = function (isTop) {
  37139. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37140. if (radius === 0) {
  37141. return;
  37142. }
  37143. // Cap positions, normals & uvs
  37144. var angle;
  37145. var circleVector;
  37146. var i;
  37147. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37148. var c = null;
  37149. if (faceColors) {
  37150. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37151. }
  37152. // cap center
  37153. var vbase = positions.length / 3;
  37154. var offset = isTop ? height / 2 : -height / 2;
  37155. var center = new BABYLON.Vector3(0, offset, 0);
  37156. positions.push(center.x, center.y, center.z);
  37157. normals.push(0, isTop ? 1 : -1, 0);
  37158. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37159. if (c) {
  37160. colors.push(c.r, c.g, c.b, c.a);
  37161. }
  37162. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37163. for (i = 0; i <= tessellation; i++) {
  37164. angle = Math.PI * 2 * i * arc / tessellation;
  37165. var cos = Math.cos(-angle);
  37166. var sin = Math.sin(-angle);
  37167. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37168. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37169. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37170. normals.push(0, isTop ? 1 : -1, 0);
  37171. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37172. if (c) {
  37173. colors.push(c.r, c.g, c.b, c.a);
  37174. }
  37175. }
  37176. // Cap indices
  37177. for (i = 0; i < tessellation; i++) {
  37178. if (!isTop) {
  37179. indices.push(vbase);
  37180. indices.push(vbase + (i + 1));
  37181. indices.push(vbase + (i + 2));
  37182. }
  37183. else {
  37184. indices.push(vbase);
  37185. indices.push(vbase + (i + 2));
  37186. indices.push(vbase + (i + 1));
  37187. }
  37188. }
  37189. };
  37190. // add caps to geometry
  37191. createCylinderCap(false);
  37192. createCylinderCap(true);
  37193. // Sides
  37194. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37195. var vertexData = new VertexData();
  37196. vertexData.indices = indices;
  37197. vertexData.positions = positions;
  37198. vertexData.normals = normals;
  37199. vertexData.uvs = uvs;
  37200. if (faceColors) {
  37201. vertexData.colors = colors;
  37202. }
  37203. return vertexData;
  37204. };
  37205. /**
  37206. * Creates the VertexData for a torus
  37207. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37208. * * diameter the diameter of the torus, optional default 1
  37209. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37210. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37211. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37212. * * 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)
  37213. * * 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)
  37214. * @returns the VertexData of the torus
  37215. */
  37216. VertexData.CreateTorus = function (options) {
  37217. var indices = [];
  37218. var positions = [];
  37219. var normals = [];
  37220. var uvs = [];
  37221. var diameter = options.diameter || 1;
  37222. var thickness = options.thickness || 0.5;
  37223. var tessellation = options.tessellation || 16;
  37224. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37225. var stride = tessellation + 1;
  37226. for (var i = 0; i <= tessellation; i++) {
  37227. var u = i / tessellation;
  37228. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37229. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37230. for (var j = 0; j <= tessellation; j++) {
  37231. var v = 1 - j / tessellation;
  37232. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37233. var dx = Math.cos(innerAngle);
  37234. var dy = Math.sin(innerAngle);
  37235. // Create a vertex.
  37236. var normal = new BABYLON.Vector3(dx, dy, 0);
  37237. var position = normal.scale(thickness / 2);
  37238. var textureCoordinate = new BABYLON.Vector2(u, v);
  37239. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37240. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37241. positions.push(position.x, position.y, position.z);
  37242. normals.push(normal.x, normal.y, normal.z);
  37243. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37244. // And create indices for two triangles.
  37245. var nextI = (i + 1) % stride;
  37246. var nextJ = (j + 1) % stride;
  37247. indices.push(i * stride + j);
  37248. indices.push(i * stride + nextJ);
  37249. indices.push(nextI * stride + j);
  37250. indices.push(i * stride + nextJ);
  37251. indices.push(nextI * stride + nextJ);
  37252. indices.push(nextI * stride + j);
  37253. }
  37254. }
  37255. // Sides
  37256. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37257. // Result
  37258. var vertexData = new VertexData();
  37259. vertexData.indices = indices;
  37260. vertexData.positions = positions;
  37261. vertexData.normals = normals;
  37262. vertexData.uvs = uvs;
  37263. return vertexData;
  37264. };
  37265. /**
  37266. * Creates the VertexData of the LineSystem
  37267. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37268. * - lines an array of lines, each line being an array of successive Vector3
  37269. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37270. * @returns the VertexData of the LineSystem
  37271. */
  37272. VertexData.CreateLineSystem = function (options) {
  37273. var indices = [];
  37274. var positions = [];
  37275. var lines = options.lines;
  37276. var colors = options.colors;
  37277. var vertexColors = [];
  37278. var idx = 0;
  37279. for (var l = 0; l < lines.length; l++) {
  37280. var points = lines[l];
  37281. for (var index = 0; index < points.length; index++) {
  37282. positions.push(points[index].x, points[index].y, points[index].z);
  37283. if (colors) {
  37284. var color = colors[l];
  37285. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37286. }
  37287. if (index > 0) {
  37288. indices.push(idx - 1);
  37289. indices.push(idx);
  37290. }
  37291. idx++;
  37292. }
  37293. }
  37294. var vertexData = new VertexData();
  37295. vertexData.indices = indices;
  37296. vertexData.positions = positions;
  37297. if (colors) {
  37298. vertexData.colors = vertexColors;
  37299. }
  37300. return vertexData;
  37301. };
  37302. /**
  37303. * Create the VertexData for a DashedLines
  37304. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37305. * - points an array successive Vector3
  37306. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37307. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37308. * - dashNb the intended total number of dashes, optional, default 200
  37309. * @returns the VertexData for the DashedLines
  37310. */
  37311. VertexData.CreateDashedLines = function (options) {
  37312. var dashSize = options.dashSize || 3;
  37313. var gapSize = options.gapSize || 1;
  37314. var dashNb = options.dashNb || 200;
  37315. var points = options.points;
  37316. var positions = new Array();
  37317. var indices = new Array();
  37318. var curvect = BABYLON.Vector3.Zero();
  37319. var lg = 0;
  37320. var nb = 0;
  37321. var shft = 0;
  37322. var dashshft = 0;
  37323. var curshft = 0;
  37324. var idx = 0;
  37325. var i = 0;
  37326. for (i = 0; i < points.length - 1; i++) {
  37327. points[i + 1].subtractToRef(points[i], curvect);
  37328. lg += curvect.length();
  37329. }
  37330. shft = lg / dashNb;
  37331. dashshft = dashSize * shft / (dashSize + gapSize);
  37332. for (i = 0; i < points.length - 1; i++) {
  37333. points[i + 1].subtractToRef(points[i], curvect);
  37334. nb = Math.floor(curvect.length() / shft);
  37335. curvect.normalize();
  37336. for (var j = 0; j < nb; j++) {
  37337. curshft = shft * j;
  37338. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37339. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37340. indices.push(idx, idx + 1);
  37341. idx += 2;
  37342. }
  37343. }
  37344. // Result
  37345. var vertexData = new VertexData();
  37346. vertexData.positions = positions;
  37347. vertexData.indices = indices;
  37348. return vertexData;
  37349. };
  37350. /**
  37351. * Creates the VertexData for a Ground
  37352. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37353. * - width the width (x direction) of the ground, optional, default 1
  37354. * - height the height (z direction) of the ground, optional, default 1
  37355. * - subdivisions the number of subdivisions per side, optional, default 1
  37356. * @returns the VertexData of the Ground
  37357. */
  37358. VertexData.CreateGround = function (options) {
  37359. var indices = [];
  37360. var positions = [];
  37361. var normals = [];
  37362. var uvs = [];
  37363. var row, col;
  37364. var width = options.width || 1;
  37365. var height = options.height || 1;
  37366. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37367. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37368. for (row = 0; row <= subdivisionsY; row++) {
  37369. for (col = 0; col <= subdivisionsX; col++) {
  37370. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37371. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37372. positions.push(position.x, position.y, position.z);
  37373. normals.push(normal.x, normal.y, normal.z);
  37374. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37375. }
  37376. }
  37377. for (row = 0; row < subdivisionsY; row++) {
  37378. for (col = 0; col < subdivisionsX; col++) {
  37379. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37380. indices.push(col + 1 + row * (subdivisionsX + 1));
  37381. indices.push(col + row * (subdivisionsX + 1));
  37382. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37383. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37384. indices.push(col + row * (subdivisionsX + 1));
  37385. }
  37386. }
  37387. // Result
  37388. var vertexData = new VertexData();
  37389. vertexData.indices = indices;
  37390. vertexData.positions = positions;
  37391. vertexData.normals = normals;
  37392. vertexData.uvs = uvs;
  37393. return vertexData;
  37394. };
  37395. /**
  37396. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37397. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37398. * * xmin the ground minimum X coordinate, optional, default -1
  37399. * * zmin the ground minimum Z coordinate, optional, default -1
  37400. * * xmax the ground maximum X coordinate, optional, default 1
  37401. * * zmax the ground maximum Z coordinate, optional, default 1
  37402. * * 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}
  37403. * * 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}
  37404. * @returns the VertexData of the TiledGround
  37405. */
  37406. VertexData.CreateTiledGround = function (options) {
  37407. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37408. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37409. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37410. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37411. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37412. var precision = options.precision || { w: 1, h: 1 };
  37413. var indices = new Array();
  37414. var positions = new Array();
  37415. var normals = new Array();
  37416. var uvs = new Array();
  37417. var row, col, tileRow, tileCol;
  37418. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37419. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37420. precision.w = (precision.w < 1) ? 1 : precision.w;
  37421. precision.h = (precision.h < 1) ? 1 : precision.h;
  37422. var tileSize = {
  37423. 'w': (xmax - xmin) / subdivisions.w,
  37424. 'h': (zmax - zmin) / subdivisions.h
  37425. };
  37426. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37427. // Indices
  37428. var base = positions.length / 3;
  37429. var rowLength = precision.w + 1;
  37430. for (row = 0; row < precision.h; row++) {
  37431. for (col = 0; col < precision.w; col++) {
  37432. var square = [
  37433. base + col + row * rowLength,
  37434. base + (col + 1) + row * rowLength,
  37435. base + (col + 1) + (row + 1) * rowLength,
  37436. base + col + (row + 1) * rowLength
  37437. ];
  37438. indices.push(square[1]);
  37439. indices.push(square[2]);
  37440. indices.push(square[3]);
  37441. indices.push(square[0]);
  37442. indices.push(square[1]);
  37443. indices.push(square[3]);
  37444. }
  37445. }
  37446. // Position, normals and uvs
  37447. var position = BABYLON.Vector3.Zero();
  37448. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37449. for (row = 0; row <= precision.h; row++) {
  37450. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37451. for (col = 0; col <= precision.w; col++) {
  37452. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37453. position.y = 0;
  37454. positions.push(position.x, position.y, position.z);
  37455. normals.push(normal.x, normal.y, normal.z);
  37456. uvs.push(col / precision.w, row / precision.h);
  37457. }
  37458. }
  37459. }
  37460. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37461. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37462. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37463. }
  37464. }
  37465. // Result
  37466. var vertexData = new VertexData();
  37467. vertexData.indices = indices;
  37468. vertexData.positions = positions;
  37469. vertexData.normals = normals;
  37470. vertexData.uvs = uvs;
  37471. return vertexData;
  37472. };
  37473. /**
  37474. * Creates the VertexData of the Ground designed from a heightmap
  37475. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37476. * * width the width (x direction) of the ground
  37477. * * height the height (z direction) of the ground
  37478. * * subdivisions the number of subdivisions per side
  37479. * * minHeight the minimum altitude on the ground, optional, default 0
  37480. * * maxHeight the maximum altitude on the ground, optional default 1
  37481. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37482. * * buffer the array holding the image color data
  37483. * * bufferWidth the width of image
  37484. * * bufferHeight the height of image
  37485. * @returns the VertexData of the Ground designed from a heightmap
  37486. */
  37487. VertexData.CreateGroundFromHeightMap = function (options) {
  37488. var indices = [];
  37489. var positions = [];
  37490. var normals = [];
  37491. var uvs = [];
  37492. var row, col;
  37493. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37494. // Vertices
  37495. for (row = 0; row <= options.subdivisions; row++) {
  37496. for (col = 0; col <= options.subdivisions; col++) {
  37497. 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));
  37498. // Compute height
  37499. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37500. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37501. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37502. var r = options.buffer[pos] / 255.0;
  37503. var g = options.buffer[pos + 1] / 255.0;
  37504. var b = options.buffer[pos + 2] / 255.0;
  37505. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37506. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37507. // Add vertex
  37508. positions.push(position.x, position.y, position.z);
  37509. normals.push(0, 0, 0);
  37510. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37511. }
  37512. }
  37513. // Indices
  37514. for (row = 0; row < options.subdivisions; row++) {
  37515. for (col = 0; col < options.subdivisions; col++) {
  37516. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37517. indices.push(col + 1 + row * (options.subdivisions + 1));
  37518. indices.push(col + row * (options.subdivisions + 1));
  37519. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37520. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37521. indices.push(col + row * (options.subdivisions + 1));
  37522. }
  37523. }
  37524. // Normals
  37525. VertexData.ComputeNormals(positions, indices, normals);
  37526. // Result
  37527. var vertexData = new VertexData();
  37528. vertexData.indices = indices;
  37529. vertexData.positions = positions;
  37530. vertexData.normals = normals;
  37531. vertexData.uvs = uvs;
  37532. return vertexData;
  37533. };
  37534. /**
  37535. * Creates the VertexData for a Plane
  37536. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37537. * * size sets the width and height of the plane to the value of size, optional default 1
  37538. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37539. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37540. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37541. * * 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)
  37542. * * 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)
  37543. * @returns the VertexData of the box
  37544. */
  37545. VertexData.CreatePlane = function (options) {
  37546. var indices = [];
  37547. var positions = [];
  37548. var normals = [];
  37549. var uvs = [];
  37550. var width = options.width || options.size || 1;
  37551. var height = options.height || options.size || 1;
  37552. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37553. // Vertices
  37554. var halfWidth = width / 2.0;
  37555. var halfHeight = height / 2.0;
  37556. positions.push(-halfWidth, -halfHeight, 0);
  37557. normals.push(0, 0, -1.0);
  37558. uvs.push(0.0, 0.0);
  37559. positions.push(halfWidth, -halfHeight, 0);
  37560. normals.push(0, 0, -1.0);
  37561. uvs.push(1.0, 0.0);
  37562. positions.push(halfWidth, halfHeight, 0);
  37563. normals.push(0, 0, -1.0);
  37564. uvs.push(1.0, 1.0);
  37565. positions.push(-halfWidth, halfHeight, 0);
  37566. normals.push(0, 0, -1.0);
  37567. uvs.push(0.0, 1.0);
  37568. // Indices
  37569. indices.push(0);
  37570. indices.push(1);
  37571. indices.push(2);
  37572. indices.push(0);
  37573. indices.push(2);
  37574. indices.push(3);
  37575. // Sides
  37576. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37577. // Result
  37578. var vertexData = new VertexData();
  37579. vertexData.indices = indices;
  37580. vertexData.positions = positions;
  37581. vertexData.normals = normals;
  37582. vertexData.uvs = uvs;
  37583. return vertexData;
  37584. };
  37585. /**
  37586. * Creates the VertexData of the Disc or regular Polygon
  37587. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37588. * * radius the radius of the disc, optional default 0.5
  37589. * * tessellation the number of polygon sides, optional, default 64
  37590. * * 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
  37591. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37592. * * 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)
  37593. * * 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)
  37594. * @returns the VertexData of the box
  37595. */
  37596. VertexData.CreateDisc = function (options) {
  37597. var positions = new Array();
  37598. var indices = new Array();
  37599. var normals = new Array();
  37600. var uvs = new Array();
  37601. var radius = options.radius || 0.5;
  37602. var tessellation = options.tessellation || 64;
  37603. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37604. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37605. // positions and uvs
  37606. positions.push(0, 0, 0); // disc center first
  37607. uvs.push(0.5, 0.5);
  37608. var theta = Math.PI * 2 * arc;
  37609. var step = theta / tessellation;
  37610. for (var a = 0; a < theta; a += step) {
  37611. var x = Math.cos(a);
  37612. var y = Math.sin(a);
  37613. var u = (x + 1) / 2;
  37614. var v = (1 - y) / 2;
  37615. positions.push(radius * x, radius * y, 0);
  37616. uvs.push(u, v);
  37617. }
  37618. if (arc === 1) {
  37619. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37620. uvs.push(uvs[2], uvs[3]);
  37621. }
  37622. //indices
  37623. var vertexNb = positions.length / 3;
  37624. for (var i = 1; i < vertexNb - 1; i++) {
  37625. indices.push(i + 1, 0, i);
  37626. }
  37627. // result
  37628. VertexData.ComputeNormals(positions, indices, normals);
  37629. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37630. var vertexData = new VertexData();
  37631. vertexData.indices = indices;
  37632. vertexData.positions = positions;
  37633. vertexData.normals = normals;
  37634. vertexData.uvs = uvs;
  37635. return vertexData;
  37636. };
  37637. /**
  37638. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37639. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37640. * @param polygon a mesh built from polygonTriangulation.build()
  37641. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37642. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37643. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37644. * @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)
  37645. * @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)
  37646. * @returns the VertexData of the Polygon
  37647. */
  37648. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37649. var faceUV = fUV || new Array(3);
  37650. var faceColors = fColors;
  37651. var colors = [];
  37652. // default face colors and UV if undefined
  37653. for (var f = 0; f < 3; f++) {
  37654. if (faceUV[f] === undefined) {
  37655. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37656. }
  37657. if (faceColors && faceColors[f] === undefined) {
  37658. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37659. }
  37660. }
  37661. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37662. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37663. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37664. var indices = polygon.getIndices();
  37665. // set face colours and textures
  37666. var idx = 0;
  37667. var face = 0;
  37668. for (var index = 0; index < normals.length; index += 3) {
  37669. //Edge Face no. 1
  37670. if (Math.abs(normals[index + 1]) < 0.001) {
  37671. face = 1;
  37672. }
  37673. //Top Face no. 0
  37674. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37675. face = 0;
  37676. }
  37677. //Bottom Face no. 2
  37678. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37679. face = 2;
  37680. }
  37681. idx = index / 3;
  37682. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37683. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37684. if (faceColors) {
  37685. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37686. }
  37687. }
  37688. // sides
  37689. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37690. // Result
  37691. var vertexData = new VertexData();
  37692. vertexData.indices = indices;
  37693. vertexData.positions = positions;
  37694. vertexData.normals = normals;
  37695. vertexData.uvs = uvs;
  37696. if (faceColors) {
  37697. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37698. vertexData.colors = totalColors;
  37699. }
  37700. return vertexData;
  37701. };
  37702. /**
  37703. * Creates the VertexData of the IcoSphere
  37704. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37705. * * radius the radius of the IcoSphere, optional default 1
  37706. * * radiusX allows stretching in the x direction, optional, default radius
  37707. * * radiusY allows stretching in the y direction, optional, default radius
  37708. * * radiusZ allows stretching in the z direction, optional, default radius
  37709. * * flat when true creates a flat shaded mesh, optional, default true
  37710. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37711. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37712. * * 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)
  37713. * * 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)
  37714. * @returns the VertexData of the IcoSphere
  37715. */
  37716. VertexData.CreateIcoSphere = function (options) {
  37717. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37718. var radius = options.radius || 1;
  37719. var flat = (options.flat === undefined) ? true : options.flat;
  37720. var subdivisions = options.subdivisions || 4;
  37721. var radiusX = options.radiusX || radius;
  37722. var radiusY = options.radiusY || radius;
  37723. var radiusZ = options.radiusZ || radius;
  37724. var t = (1 + Math.sqrt(5)) / 2;
  37725. // 12 vertex x,y,z
  37726. var ico_vertices = [
  37727. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37728. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37729. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37730. ];
  37731. // index of 3 vertex makes a face of icopshere
  37732. var ico_indices = [
  37733. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37734. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37735. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37736. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37737. ];
  37738. // vertex for uv have aliased position, not for UV
  37739. var vertices_unalias_id = [
  37740. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37741. // vertex alias
  37742. 0,
  37743. 2,
  37744. 3,
  37745. 3,
  37746. 3,
  37747. 4,
  37748. 7,
  37749. 8,
  37750. 9,
  37751. 9,
  37752. 10,
  37753. 11 // 23: B + 12
  37754. ];
  37755. // uv as integer step (not pixels !)
  37756. var ico_vertexuv = [
  37757. 5, 1, 3, 1, 6, 4, 0, 0,
  37758. 5, 3, 4, 2, 2, 2, 4, 0,
  37759. 2, 0, 1, 1, 6, 0, 6, 2,
  37760. // vertex alias (for same vertex on different faces)
  37761. 0, 4,
  37762. 3, 3,
  37763. 4, 4,
  37764. 3, 1,
  37765. 4, 2,
  37766. 4, 4,
  37767. 0, 2,
  37768. 1, 1,
  37769. 2, 2,
  37770. 3, 3,
  37771. 1, 3,
  37772. 2, 4 // 23: B + 12
  37773. ];
  37774. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37775. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37776. // First island of uv mapping
  37777. // v = 4h 3+ 2
  37778. // v = 3h 9+ 4
  37779. // v = 2h 9+ 5 B
  37780. // v = 1h 9 1 0
  37781. // v = 0h 3 8 7 A
  37782. // u = 0 1 2 3 4 5 6 *a
  37783. // Second island of uv mapping
  37784. // v = 4h 0+ B+ 4+
  37785. // v = 3h A+ 2+
  37786. // v = 2h 7+ 6 3+
  37787. // v = 1h 8+ 3+
  37788. // v = 0h
  37789. // u = 0 1 2 3 4 5 6 *a
  37790. // Face layout on texture UV mapping
  37791. // ============
  37792. // \ 4 /\ 16 / ======
  37793. // \ / \ / /\ 11 /
  37794. // \/ 7 \/ / \ /
  37795. // ======= / 10 \/
  37796. // /\ 17 /\ =======
  37797. // / \ / \ \ 15 /\
  37798. // / 8 \/ 12 \ \ / \
  37799. // ============ \/ 6 \
  37800. // \ 18 /\ ============
  37801. // \ / \ \ 5 /\ 0 /
  37802. // \/ 13 \ \ / \ /
  37803. // ======= \/ 1 \/
  37804. // =============
  37805. // /\ 19 /\ 2 /\
  37806. // / \ / \ / \
  37807. // / 14 \/ 9 \/ 3 \
  37808. // ===================
  37809. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37810. var ustep = 138 / 1024;
  37811. var vstep = 239 / 1024;
  37812. var uoffset = 60 / 1024;
  37813. var voffset = 26 / 1024;
  37814. // Second island should have margin, not to touch the first island
  37815. // avoid any borderline artefact in pixel rounding
  37816. var island_u_offset = -40 / 1024;
  37817. var island_v_offset = +20 / 1024;
  37818. // face is either island 0 or 1 :
  37819. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37820. var island = [
  37821. 0, 0, 0, 0, 1,
  37822. 0, 0, 1, 1, 0,
  37823. 0, 0, 1, 1, 0,
  37824. 0, 1, 1, 1, 0 // 15 - 19
  37825. ];
  37826. var indices = new Array();
  37827. var positions = new Array();
  37828. var normals = new Array();
  37829. var uvs = new Array();
  37830. var current_indice = 0;
  37831. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37832. var face_vertex_pos = new Array(3);
  37833. var face_vertex_uv = new Array(3);
  37834. var v012;
  37835. for (v012 = 0; v012 < 3; v012++) {
  37836. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37837. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37838. }
  37839. // create all with normals
  37840. for (var face = 0; face < 20; face++) {
  37841. // 3 vertex per face
  37842. for (v012 = 0; v012 < 3; v012++) {
  37843. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37844. var v_id = ico_indices[3 * face + v012];
  37845. // vertex have 3D position (x,y,z)
  37846. 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]);
  37847. // Normalize to get normal, then scale to radius
  37848. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37849. // uv Coordinates from vertex ID
  37850. 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);
  37851. }
  37852. // Subdivide the face (interpolate pos, norm, uv)
  37853. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37854. // - norm is linear interpolation of vertex corner normal
  37855. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37856. // - uv is linear interpolation
  37857. //
  37858. // Topology is as below for sub-divide by 2
  37859. // vertex shown as v0,v1,v2
  37860. // interp index is i1 to progress in range [v0,v1[
  37861. // interp index is i2 to progress in range [v0,v2[
  37862. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37863. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37864. //
  37865. //
  37866. // i2 v2
  37867. // ^ ^
  37868. // / / \
  37869. // / / \
  37870. // / / \
  37871. // / / (0,1) \
  37872. // / #---------\
  37873. // / / \ (0,0)'/ \
  37874. // / / \ / \
  37875. // / / \ / \
  37876. // / / (0,0) \ / (1,0) \
  37877. // / #---------#---------\
  37878. // v0 v1
  37879. //
  37880. // --------------------> i1
  37881. //
  37882. // interp of (i1,i2):
  37883. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37884. // along i1 : lerp(x0,x1, i1/(S-i2))
  37885. //
  37886. // centroid of triangle is needed to get help normal computation
  37887. // (c1,c2) are used for centroid location
  37888. var interp_vertex = function (i1, i2, c1, c2) {
  37889. // vertex is interpolated from
  37890. // - face_vertex_pos[0..2]
  37891. // - face_vertex_uv[0..2]
  37892. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37893. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37894. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37895. pos_interp.normalize();
  37896. var vertex_normal;
  37897. if (flat) {
  37898. // in flat mode, recalculate normal as face centroid normal
  37899. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37900. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37901. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37902. }
  37903. else {
  37904. // in smooth mode, recalculate normal from each single vertex position
  37905. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37906. }
  37907. // Vertex normal need correction due to X,Y,Z radius scaling
  37908. vertex_normal.x /= radiusX;
  37909. vertex_normal.y /= radiusY;
  37910. vertex_normal.z /= radiusZ;
  37911. vertex_normal.normalize();
  37912. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37913. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37914. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37915. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37916. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37917. uvs.push(uv_interp.x, uv_interp.y);
  37918. // push each vertex has member of a face
  37919. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37920. indices.push(current_indice);
  37921. current_indice++;
  37922. };
  37923. for (var i2 = 0; i2 < subdivisions; i2++) {
  37924. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37925. // face : (i1,i2) for /\ :
  37926. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37927. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37928. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37929. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37930. if (i1 + i2 + 1 < subdivisions) {
  37931. // face : (i1,i2)' for \/ :
  37932. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37933. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37934. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37935. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37936. }
  37937. }
  37938. }
  37939. }
  37940. // Sides
  37941. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37942. // Result
  37943. var vertexData = new VertexData();
  37944. vertexData.indices = indices;
  37945. vertexData.positions = positions;
  37946. vertexData.normals = normals;
  37947. vertexData.uvs = uvs;
  37948. return vertexData;
  37949. };
  37950. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37951. /**
  37952. * Creates the VertexData for a Polyhedron
  37953. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37954. * * type provided types are:
  37955. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37956. * * 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)
  37957. * * size the size of the IcoSphere, optional default 1
  37958. * * sizeX allows stretching in the x direction, optional, default size
  37959. * * sizeY allows stretching in the y direction, optional, default size
  37960. * * sizeZ allows stretching in the z direction, optional, default size
  37961. * * 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
  37962. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37963. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37964. * * flat when true creates a flat shaded mesh, optional, default true
  37965. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37966. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37967. * * 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)
  37968. * * 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)
  37969. * @returns the VertexData of the Polyhedron
  37970. */
  37971. VertexData.CreatePolyhedron = function (options) {
  37972. // provided polyhedron types :
  37973. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37974. // 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)
  37975. var polyhedra = [];
  37976. 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]] };
  37977. 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]] };
  37978. polyhedra[2] = {
  37979. 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]],
  37980. 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]]
  37981. };
  37982. polyhedra[3] = {
  37983. 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]],
  37984. 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]]
  37985. };
  37986. polyhedra[4] = {
  37987. 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]],
  37988. 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]]
  37989. };
  37990. 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]] };
  37991. 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]] };
  37992. 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]] };
  37993. 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]] };
  37994. 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]] };
  37995. 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]] };
  37996. 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]] };
  37997. 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]] };
  37998. 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]] };
  37999. polyhedra[14] = {
  38000. 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]],
  38001. 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]]
  38002. };
  38003. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38004. var size = options.size;
  38005. var sizeX = options.sizeX || size || 1;
  38006. var sizeY = options.sizeY || size || 1;
  38007. var sizeZ = options.sizeZ || size || 1;
  38008. var data = options.custom || polyhedra[type];
  38009. var nbfaces = data.face.length;
  38010. var faceUV = options.faceUV || new Array(nbfaces);
  38011. var faceColors = options.faceColors;
  38012. var flat = (options.flat === undefined) ? true : options.flat;
  38013. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38014. var positions = new Array();
  38015. var indices = new Array();
  38016. var normals = new Array();
  38017. var uvs = new Array();
  38018. var colors = new Array();
  38019. var index = 0;
  38020. var faceIdx = 0; // face cursor in the array "indexes"
  38021. var indexes = new Array();
  38022. var i = 0;
  38023. var f = 0;
  38024. var u, v, ang, x, y, tmp;
  38025. // default face colors and UV if undefined
  38026. if (flat) {
  38027. for (f = 0; f < nbfaces; f++) {
  38028. if (faceColors && faceColors[f] === undefined) {
  38029. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38030. }
  38031. if (faceUV && faceUV[f] === undefined) {
  38032. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38033. }
  38034. }
  38035. }
  38036. if (!flat) {
  38037. for (i = 0; i < data.vertex.length; i++) {
  38038. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38039. uvs.push(0, 0);
  38040. }
  38041. for (f = 0; f < nbfaces; f++) {
  38042. for (i = 0; i < data.face[f].length - 2; i++) {
  38043. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38044. }
  38045. }
  38046. }
  38047. else {
  38048. for (f = 0; f < nbfaces; f++) {
  38049. var fl = data.face[f].length; // number of vertices of the current face
  38050. ang = 2 * Math.PI / fl;
  38051. x = 0.5 * Math.tan(ang / 2);
  38052. y = 0.5;
  38053. // positions, uvs, colors
  38054. for (i = 0; i < fl; i++) {
  38055. // positions
  38056. 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);
  38057. indexes.push(index);
  38058. index++;
  38059. // uvs
  38060. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38061. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38062. uvs.push(u, v);
  38063. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38064. y = x * Math.sin(ang) + y * Math.cos(ang);
  38065. x = tmp;
  38066. // colors
  38067. if (faceColors) {
  38068. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38069. }
  38070. }
  38071. // indices from indexes
  38072. for (i = 0; i < fl - 2; i++) {
  38073. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38074. }
  38075. faceIdx += fl;
  38076. }
  38077. }
  38078. VertexData.ComputeNormals(positions, indices, normals);
  38079. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38080. var vertexData = new VertexData();
  38081. vertexData.positions = positions;
  38082. vertexData.indices = indices;
  38083. vertexData.normals = normals;
  38084. vertexData.uvs = uvs;
  38085. if (faceColors && flat) {
  38086. vertexData.colors = colors;
  38087. }
  38088. return vertexData;
  38089. };
  38090. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38091. /**
  38092. * Creates the VertexData for a TorusKnot
  38093. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38094. * * radius the radius of the torus knot, optional, default 2
  38095. * * tube the thickness of the tube, optional, default 0.5
  38096. * * radialSegments the number of sides on each tube segments, optional, default 32
  38097. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38098. * * p the number of windings around the z axis, optional, default 2
  38099. * * q the number of windings around the x axis, optional, default 3
  38100. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38101. * * 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)
  38102. * * 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)
  38103. * @returns the VertexData of the Torus Knot
  38104. */
  38105. VertexData.CreateTorusKnot = function (options) {
  38106. var indices = new Array();
  38107. var positions = new Array();
  38108. var normals = new Array();
  38109. var uvs = new Array();
  38110. var radius = options.radius || 2;
  38111. var tube = options.tube || 0.5;
  38112. var radialSegments = options.radialSegments || 32;
  38113. var tubularSegments = options.tubularSegments || 32;
  38114. var p = options.p || 2;
  38115. var q = options.q || 3;
  38116. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38117. // Helper
  38118. var getPos = function (angle) {
  38119. var cu = Math.cos(angle);
  38120. var su = Math.sin(angle);
  38121. var quOverP = q / p * angle;
  38122. var cs = Math.cos(quOverP);
  38123. var tx = radius * (2 + cs) * 0.5 * cu;
  38124. var ty = radius * (2 + cs) * su * 0.5;
  38125. var tz = radius * Math.sin(quOverP) * 0.5;
  38126. return new BABYLON.Vector3(tx, ty, tz);
  38127. };
  38128. // Vertices
  38129. var i;
  38130. var j;
  38131. for (i = 0; i <= radialSegments; i++) {
  38132. var modI = i % radialSegments;
  38133. var u = modI / radialSegments * 2 * p * Math.PI;
  38134. var p1 = getPos(u);
  38135. var p2 = getPos(u + 0.01);
  38136. var tang = p2.subtract(p1);
  38137. var n = p2.add(p1);
  38138. var bitan = BABYLON.Vector3.Cross(tang, n);
  38139. n = BABYLON.Vector3.Cross(bitan, tang);
  38140. bitan.normalize();
  38141. n.normalize();
  38142. for (j = 0; j < tubularSegments; j++) {
  38143. var modJ = j % tubularSegments;
  38144. var v = modJ / tubularSegments * 2 * Math.PI;
  38145. var cx = -tube * Math.cos(v);
  38146. var cy = tube * Math.sin(v);
  38147. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38148. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38149. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38150. uvs.push(i / radialSegments);
  38151. uvs.push(j / tubularSegments);
  38152. }
  38153. }
  38154. for (i = 0; i < radialSegments; i++) {
  38155. for (j = 0; j < tubularSegments; j++) {
  38156. var jNext = (j + 1) % tubularSegments;
  38157. var a = i * tubularSegments + j;
  38158. var b = (i + 1) * tubularSegments + j;
  38159. var c = (i + 1) * tubularSegments + jNext;
  38160. var d = i * tubularSegments + jNext;
  38161. indices.push(d);
  38162. indices.push(b);
  38163. indices.push(a);
  38164. indices.push(d);
  38165. indices.push(c);
  38166. indices.push(b);
  38167. }
  38168. }
  38169. // Normals
  38170. VertexData.ComputeNormals(positions, indices, normals);
  38171. // Sides
  38172. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38173. // Result
  38174. var vertexData = new VertexData();
  38175. vertexData.indices = indices;
  38176. vertexData.positions = positions;
  38177. vertexData.normals = normals;
  38178. vertexData.uvs = uvs;
  38179. return vertexData;
  38180. };
  38181. // Tools
  38182. /**
  38183. * Compute normals for given positions and indices
  38184. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38185. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38186. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38187. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38188. * * facetNormals : optional array of facet normals (vector3)
  38189. * * facetPositions : optional array of facet positions (vector3)
  38190. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38191. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38192. * * bInfo : optional bounding info, required for facetPartitioning computation
  38193. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38194. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38195. * * useRightHandedSystem: optional boolean to for right handed system computation
  38196. * * depthSort : optional boolean to enable the facet depth sort computation
  38197. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38198. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38199. */
  38200. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38201. // temporary scalar variables
  38202. var index = 0; // facet index
  38203. var p1p2x = 0.0; // p1p2 vector x coordinate
  38204. var p1p2y = 0.0; // p1p2 vector y coordinate
  38205. var p1p2z = 0.0; // p1p2 vector z coordinate
  38206. var p3p2x = 0.0; // p3p2 vector x coordinate
  38207. var p3p2y = 0.0; // p3p2 vector y coordinate
  38208. var p3p2z = 0.0; // p3p2 vector z coordinate
  38209. var faceNormalx = 0.0; // facet normal x coordinate
  38210. var faceNormaly = 0.0; // facet normal y coordinate
  38211. var faceNormalz = 0.0; // facet normal z coordinate
  38212. var length = 0.0; // facet normal length before normalization
  38213. var v1x = 0; // vector1 x index in the positions array
  38214. var v1y = 0; // vector1 y index in the positions array
  38215. var v1z = 0; // vector1 z index in the positions array
  38216. var v2x = 0; // vector2 x index in the positions array
  38217. var v2y = 0; // vector2 y index in the positions array
  38218. var v2z = 0; // vector2 z index in the positions array
  38219. var v3x = 0; // vector3 x index in the positions array
  38220. var v3y = 0; // vector3 y index in the positions array
  38221. var v3z = 0; // vector3 z index in the positions array
  38222. var computeFacetNormals = false;
  38223. var computeFacetPositions = false;
  38224. var computeFacetPartitioning = false;
  38225. var computeDepthSort = false;
  38226. var faceNormalSign = 1;
  38227. var ratio = 0;
  38228. var distanceTo = null;
  38229. if (options) {
  38230. computeFacetNormals = (options.facetNormals) ? true : false;
  38231. computeFacetPositions = (options.facetPositions) ? true : false;
  38232. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38233. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38234. ratio = options.ratio || 0;
  38235. computeDepthSort = (options.depthSort) ? true : false;
  38236. distanceTo = (options.distanceTo);
  38237. if (computeDepthSort) {
  38238. if (distanceTo === undefined) {
  38239. distanceTo = BABYLON.Vector3.Zero();
  38240. }
  38241. var depthSortedFacets = options.depthSortedFacets;
  38242. }
  38243. }
  38244. // facetPartitioning reinit if needed
  38245. var xSubRatio = 0;
  38246. var ySubRatio = 0;
  38247. var zSubRatio = 0;
  38248. var subSq = 0;
  38249. if (computeFacetPartitioning && options && options.bbSize) {
  38250. var ox = 0; // X partitioning index for facet position
  38251. var oy = 0; // Y partinioning index for facet position
  38252. var oz = 0; // Z partinioning index for facet position
  38253. var b1x = 0; // X partitioning index for facet v1 vertex
  38254. var b1y = 0; // Y partitioning index for facet v1 vertex
  38255. var b1z = 0; // z partitioning index for facet v1 vertex
  38256. var b2x = 0; // X partitioning index for facet v2 vertex
  38257. var b2y = 0; // Y partitioning index for facet v2 vertex
  38258. var b2z = 0; // Z partitioning index for facet v2 vertex
  38259. var b3x = 0; // X partitioning index for facet v3 vertex
  38260. var b3y = 0; // Y partitioning index for facet v3 vertex
  38261. var b3z = 0; // Z partitioning index for facet v3 vertex
  38262. var block_idx_o = 0; // facet barycenter block index
  38263. var block_idx_v1 = 0; // v1 vertex block index
  38264. var block_idx_v2 = 0; // v2 vertex block index
  38265. var block_idx_v3 = 0; // v3 vertex block index
  38266. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38267. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38268. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38269. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38270. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38271. subSq = options.subDiv.max * options.subDiv.max;
  38272. options.facetPartitioning.length = 0;
  38273. }
  38274. // reset the normals
  38275. for (index = 0; index < positions.length; index++) {
  38276. normals[index] = 0.0;
  38277. }
  38278. // Loop : 1 indice triplet = 1 facet
  38279. var nbFaces = (indices.length / 3) | 0;
  38280. for (index = 0; index < nbFaces; index++) {
  38281. // get the indexes of the coordinates of each vertex of the facet
  38282. v1x = indices[index * 3] * 3;
  38283. v1y = v1x + 1;
  38284. v1z = v1x + 2;
  38285. v2x = indices[index * 3 + 1] * 3;
  38286. v2y = v2x + 1;
  38287. v2z = v2x + 2;
  38288. v3x = indices[index * 3 + 2] * 3;
  38289. v3y = v3x + 1;
  38290. v3z = v3x + 2;
  38291. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38292. p1p2y = positions[v1y] - positions[v2y];
  38293. p1p2z = positions[v1z] - positions[v2z];
  38294. p3p2x = positions[v3x] - positions[v2x];
  38295. p3p2y = positions[v3y] - positions[v2y];
  38296. p3p2z = positions[v3z] - positions[v2z];
  38297. // compute the face normal with the cross product
  38298. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38299. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38300. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38301. // normalize this normal and store it in the array facetData
  38302. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38303. length = (length === 0) ? 1.0 : length;
  38304. faceNormalx /= length;
  38305. faceNormaly /= length;
  38306. faceNormalz /= length;
  38307. if (computeFacetNormals && options) {
  38308. options.facetNormals[index].x = faceNormalx;
  38309. options.facetNormals[index].y = faceNormaly;
  38310. options.facetNormals[index].z = faceNormalz;
  38311. }
  38312. if (computeFacetPositions && options) {
  38313. // compute and the facet barycenter coordinates in the array facetPositions
  38314. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38315. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38316. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38317. }
  38318. if (computeFacetPartitioning && options) {
  38319. // store the facet indexes in arrays in the main facetPartitioning array :
  38320. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38321. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38322. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38323. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38324. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38325. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38326. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38327. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38328. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38329. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38330. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38331. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38332. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38333. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38334. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38335. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38336. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38337. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38338. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38339. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38340. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38341. // push each facet index in each block containing the vertex
  38342. options.facetPartitioning[block_idx_v1].push(index);
  38343. if (block_idx_v2 != block_idx_v1) {
  38344. options.facetPartitioning[block_idx_v2].push(index);
  38345. }
  38346. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38347. options.facetPartitioning[block_idx_v3].push(index);
  38348. }
  38349. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38350. options.facetPartitioning[block_idx_o].push(index);
  38351. }
  38352. }
  38353. if (computeDepthSort && options && options.facetPositions) {
  38354. var dsf = depthSortedFacets[index];
  38355. dsf.ind = index * 3;
  38356. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38357. }
  38358. // compute the normals anyway
  38359. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38360. normals[v1y] += faceNormaly;
  38361. normals[v1z] += faceNormalz;
  38362. normals[v2x] += faceNormalx;
  38363. normals[v2y] += faceNormaly;
  38364. normals[v2z] += faceNormalz;
  38365. normals[v3x] += faceNormalx;
  38366. normals[v3y] += faceNormaly;
  38367. normals[v3z] += faceNormalz;
  38368. }
  38369. // last normalization of each normal
  38370. for (index = 0; index < normals.length / 3; index++) {
  38371. faceNormalx = normals[index * 3];
  38372. faceNormaly = normals[index * 3 + 1];
  38373. faceNormalz = normals[index * 3 + 2];
  38374. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38375. length = (length === 0) ? 1.0 : length;
  38376. faceNormalx /= length;
  38377. faceNormaly /= length;
  38378. faceNormalz /= length;
  38379. normals[index * 3] = faceNormalx;
  38380. normals[index * 3 + 1] = faceNormaly;
  38381. normals[index * 3 + 2] = faceNormalz;
  38382. }
  38383. };
  38384. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38385. var li = indices.length;
  38386. var ln = normals.length;
  38387. var i;
  38388. var n;
  38389. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38390. switch (sideOrientation) {
  38391. case BABYLON.Mesh.FRONTSIDE:
  38392. // nothing changed
  38393. break;
  38394. case BABYLON.Mesh.BACKSIDE:
  38395. var tmp;
  38396. // indices
  38397. for (i = 0; i < li; i += 3) {
  38398. tmp = indices[i];
  38399. indices[i] = indices[i + 2];
  38400. indices[i + 2] = tmp;
  38401. }
  38402. // normals
  38403. for (n = 0; n < ln; n++) {
  38404. normals[n] = -normals[n];
  38405. }
  38406. break;
  38407. case BABYLON.Mesh.DOUBLESIDE:
  38408. // positions
  38409. var lp = positions.length;
  38410. var l = lp / 3;
  38411. for (var p = 0; p < lp; p++) {
  38412. positions[lp + p] = positions[p];
  38413. }
  38414. // indices
  38415. for (i = 0; i < li; i += 3) {
  38416. indices[i + li] = indices[i + 2] + l;
  38417. indices[i + 1 + li] = indices[i + 1] + l;
  38418. indices[i + 2 + li] = indices[i] + l;
  38419. }
  38420. // normals
  38421. for (n = 0; n < ln; n++) {
  38422. normals[ln + n] = -normals[n];
  38423. }
  38424. // uvs
  38425. var lu = uvs.length;
  38426. var u = 0;
  38427. for (u = 0; u < lu; u++) {
  38428. uvs[u + lu] = uvs[u];
  38429. }
  38430. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38431. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38432. u = 0;
  38433. for (i = 0; i < lu / 2; i++) {
  38434. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38435. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38436. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38437. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38438. u += 2;
  38439. }
  38440. break;
  38441. }
  38442. };
  38443. /**
  38444. * Applies VertexData created from the imported parameters to the geometry
  38445. * @param parsedVertexData the parsed data from an imported file
  38446. * @param geometry the geometry to apply the VertexData to
  38447. */
  38448. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38449. var vertexData = new VertexData();
  38450. // positions
  38451. var positions = parsedVertexData.positions;
  38452. if (positions) {
  38453. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38454. }
  38455. // normals
  38456. var normals = parsedVertexData.normals;
  38457. if (normals) {
  38458. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38459. }
  38460. // tangents
  38461. var tangents = parsedVertexData.tangents;
  38462. if (tangents) {
  38463. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38464. }
  38465. // uvs
  38466. var uvs = parsedVertexData.uvs;
  38467. if (uvs) {
  38468. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38469. }
  38470. // uv2s
  38471. var uv2s = parsedVertexData.uv2s;
  38472. if (uv2s) {
  38473. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38474. }
  38475. // uv3s
  38476. var uv3s = parsedVertexData.uv3s;
  38477. if (uv3s) {
  38478. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38479. }
  38480. // uv4s
  38481. var uv4s = parsedVertexData.uv4s;
  38482. if (uv4s) {
  38483. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38484. }
  38485. // uv5s
  38486. var uv5s = parsedVertexData.uv5s;
  38487. if (uv5s) {
  38488. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38489. }
  38490. // uv6s
  38491. var uv6s = parsedVertexData.uv6s;
  38492. if (uv6s) {
  38493. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38494. }
  38495. // colors
  38496. var colors = parsedVertexData.colors;
  38497. if (colors) {
  38498. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38499. }
  38500. // matricesIndices
  38501. var matricesIndices = parsedVertexData.matricesIndices;
  38502. if (matricesIndices) {
  38503. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38504. }
  38505. // matricesWeights
  38506. var matricesWeights = parsedVertexData.matricesWeights;
  38507. if (matricesWeights) {
  38508. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38509. }
  38510. // indices
  38511. var indices = parsedVertexData.indices;
  38512. if (indices) {
  38513. vertexData.indices = indices;
  38514. }
  38515. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38516. };
  38517. return VertexData;
  38518. }());
  38519. BABYLON.VertexData = VertexData;
  38520. })(BABYLON || (BABYLON = {}));
  38521. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38522. var BABYLON;
  38523. (function (BABYLON) {
  38524. /**
  38525. * Class used to store geometry data (vertex buffers + index buffer)
  38526. */
  38527. var Geometry = /** @class */ (function () {
  38528. /**
  38529. * Creates a new geometry
  38530. * @param id defines the unique ID
  38531. * @param scene defines the hosting scene
  38532. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38533. * @param updatable defines if geometry must be updatable (false by default)
  38534. * @param mesh defines the mesh that will be associated with the geometry
  38535. */
  38536. function Geometry(id, scene, vertexData, updatable, mesh) {
  38537. if (updatable === void 0) { updatable = false; }
  38538. if (mesh === void 0) { mesh = null; }
  38539. /**
  38540. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38541. */
  38542. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38543. this._totalVertices = 0;
  38544. this._isDisposed = false;
  38545. this._indexBufferIsUpdatable = false;
  38546. this.id = id;
  38547. this._engine = scene.getEngine();
  38548. this._meshes = [];
  38549. this._scene = scene;
  38550. //Init vertex buffer cache
  38551. this._vertexBuffers = {};
  38552. this._indices = [];
  38553. this._updatable = updatable;
  38554. // vertexData
  38555. if (vertexData) {
  38556. this.setAllVerticesData(vertexData, updatable);
  38557. }
  38558. else {
  38559. this._totalVertices = 0;
  38560. this._indices = [];
  38561. }
  38562. if (this._engine.getCaps().vertexArrayObject) {
  38563. this._vertexArrayObjects = {};
  38564. }
  38565. // applyToMesh
  38566. if (mesh) {
  38567. if (mesh.getClassName() === "LinesMesh") {
  38568. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38569. this._updateExtend();
  38570. }
  38571. this.applyToMesh(mesh);
  38572. mesh.computeWorldMatrix(true);
  38573. }
  38574. }
  38575. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38576. /**
  38577. * 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
  38578. */
  38579. get: function () {
  38580. return this._boundingBias;
  38581. },
  38582. /**
  38583. * 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
  38584. */
  38585. set: function (value) {
  38586. if (this._boundingBias && this._boundingBias.equals(value)) {
  38587. return;
  38588. }
  38589. this._boundingBias = value.clone();
  38590. this._updateBoundingInfo(true, null);
  38591. },
  38592. enumerable: true,
  38593. configurable: true
  38594. });
  38595. /**
  38596. * Static function used to attach a new empty geometry to a mesh
  38597. * @param mesh defines the mesh to attach the geometry to
  38598. * @returns the new {BABYLON.Geometry}
  38599. */
  38600. Geometry.CreateGeometryForMesh = function (mesh) {
  38601. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38602. geometry.applyToMesh(mesh);
  38603. return geometry;
  38604. };
  38605. Object.defineProperty(Geometry.prototype, "extend", {
  38606. /**
  38607. * Gets the current extend of the geometry
  38608. */
  38609. get: function () {
  38610. return this._extend;
  38611. },
  38612. enumerable: true,
  38613. configurable: true
  38614. });
  38615. /**
  38616. * Gets the hosting scene
  38617. * @returns the hosting {BABYLON.Scene}
  38618. */
  38619. Geometry.prototype.getScene = function () {
  38620. return this._scene;
  38621. };
  38622. /**
  38623. * Gets the hosting engine
  38624. * @returns the hosting {BABYLON.Engine}
  38625. */
  38626. Geometry.prototype.getEngine = function () {
  38627. return this._engine;
  38628. };
  38629. /**
  38630. * Defines if the geometry is ready to use
  38631. * @returns true if the geometry is ready to be used
  38632. */
  38633. Geometry.prototype.isReady = function () {
  38634. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38635. };
  38636. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38637. /**
  38638. * Gets a value indicating that the geometry should not be serialized
  38639. */
  38640. get: function () {
  38641. for (var index = 0; index < this._meshes.length; index++) {
  38642. if (!this._meshes[index].doNotSerialize) {
  38643. return false;
  38644. }
  38645. }
  38646. return true;
  38647. },
  38648. enumerable: true,
  38649. configurable: true
  38650. });
  38651. /** @hidden */
  38652. Geometry.prototype._rebuild = function () {
  38653. if (this._vertexArrayObjects) {
  38654. this._vertexArrayObjects = {};
  38655. }
  38656. // Index buffer
  38657. if (this._meshes.length !== 0 && this._indices) {
  38658. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38659. }
  38660. // Vertex buffers
  38661. for (var key in this._vertexBuffers) {
  38662. var vertexBuffer = this._vertexBuffers[key];
  38663. vertexBuffer._rebuild();
  38664. }
  38665. };
  38666. /**
  38667. * Affects all geometry data in one call
  38668. * @param vertexData defines the geometry data
  38669. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38670. */
  38671. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38672. vertexData.applyToGeometry(this, updatable);
  38673. this.notifyUpdate();
  38674. };
  38675. /**
  38676. * Set specific vertex data
  38677. * @param kind defines the data kind (Position, normal, etc...)
  38678. * @param data defines the vertex data to use
  38679. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38680. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38681. */
  38682. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38683. if (updatable === void 0) { updatable = false; }
  38684. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38685. this.setVerticesBuffer(buffer);
  38686. };
  38687. /**
  38688. * Removes a specific vertex data
  38689. * @param kind defines the data kind (Position, normal, etc...)
  38690. */
  38691. Geometry.prototype.removeVerticesData = function (kind) {
  38692. if (this._vertexBuffers[kind]) {
  38693. this._vertexBuffers[kind].dispose();
  38694. delete this._vertexBuffers[kind];
  38695. }
  38696. };
  38697. /**
  38698. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38699. * @param buffer defines the vertex buffer to use
  38700. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38701. */
  38702. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38703. if (totalVertices === void 0) { totalVertices = null; }
  38704. var kind = buffer.getKind();
  38705. if (this._vertexBuffers[kind]) {
  38706. this._vertexBuffers[kind].dispose();
  38707. }
  38708. this._vertexBuffers[kind] = buffer;
  38709. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38710. var data = buffer.getData();
  38711. if (totalVertices != null) {
  38712. this._totalVertices = totalVertices;
  38713. }
  38714. else {
  38715. if (data != null) {
  38716. this._totalVertices = data.length / (buffer.byteStride / 4);
  38717. }
  38718. }
  38719. this._updateExtend(data);
  38720. this._resetPointsArrayCache();
  38721. var meshes = this._meshes;
  38722. var numOfMeshes = meshes.length;
  38723. for (var index = 0; index < numOfMeshes; index++) {
  38724. var mesh = meshes[index];
  38725. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38726. mesh._createGlobalSubMesh(false);
  38727. mesh.computeWorldMatrix(true);
  38728. }
  38729. }
  38730. this.notifyUpdate(kind);
  38731. if (this._vertexArrayObjects) {
  38732. this._disposeVertexArrayObjects();
  38733. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38734. }
  38735. };
  38736. /**
  38737. * Update a specific vertex buffer
  38738. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38739. * It will do nothing if the buffer is not updatable
  38740. * @param kind defines the data kind (Position, normal, etc...)
  38741. * @param data defines the data to use
  38742. * @param offset defines the offset in the target buffer where to store the data
  38743. * @param useBytes set to true if the offset is in bytes
  38744. */
  38745. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38746. if (useBytes === void 0) { useBytes = false; }
  38747. var vertexBuffer = this.getVertexBuffer(kind);
  38748. if (!vertexBuffer) {
  38749. return;
  38750. }
  38751. vertexBuffer.updateDirectly(data, offset, useBytes);
  38752. this.notifyUpdate(kind);
  38753. };
  38754. /**
  38755. * Update a specific vertex buffer
  38756. * This function will create a new buffer if the current one is not updatable
  38757. * @param kind defines the data kind (Position, normal, etc...)
  38758. * @param data defines the data to use
  38759. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38760. */
  38761. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38762. if (updateExtends === void 0) { updateExtends = false; }
  38763. var vertexBuffer = this.getVertexBuffer(kind);
  38764. if (!vertexBuffer) {
  38765. return;
  38766. }
  38767. vertexBuffer.update(data);
  38768. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38769. this._updateBoundingInfo(updateExtends, data);
  38770. }
  38771. this.notifyUpdate(kind);
  38772. };
  38773. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38774. if (updateExtends) {
  38775. this._updateExtend(data);
  38776. }
  38777. var meshes = this._meshes;
  38778. var numOfMeshes = meshes.length;
  38779. this._resetPointsArrayCache();
  38780. for (var index = 0; index < numOfMeshes; index++) {
  38781. var mesh = meshes[index];
  38782. if (updateExtends) {
  38783. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38784. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38785. var subMesh = mesh.subMeshes[subIndex];
  38786. subMesh.refreshBoundingInfo();
  38787. }
  38788. }
  38789. }
  38790. };
  38791. /** @hidden */
  38792. Geometry.prototype._bind = function (effect, indexToBind) {
  38793. if (!effect) {
  38794. return;
  38795. }
  38796. if (indexToBind === undefined) {
  38797. indexToBind = this._indexBuffer;
  38798. }
  38799. var vbs = this.getVertexBuffers();
  38800. if (!vbs) {
  38801. return;
  38802. }
  38803. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38804. this._engine.bindBuffers(vbs, indexToBind, effect);
  38805. return;
  38806. }
  38807. // Using VAO
  38808. if (!this._vertexArrayObjects[effect.key]) {
  38809. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38810. }
  38811. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38812. };
  38813. /**
  38814. * Gets total number of vertices
  38815. * @returns the total number of vertices
  38816. */
  38817. Geometry.prototype.getTotalVertices = function () {
  38818. if (!this.isReady()) {
  38819. return 0;
  38820. }
  38821. return this._totalVertices;
  38822. };
  38823. /**
  38824. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38825. * @param kind defines the data kind (Position, normal, etc...)
  38826. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38827. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38828. * @returns a float array containing vertex data
  38829. */
  38830. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38831. var vertexBuffer = this.getVertexBuffer(kind);
  38832. if (!vertexBuffer) {
  38833. return null;
  38834. }
  38835. var data = vertexBuffer.getData();
  38836. if (!data) {
  38837. return null;
  38838. }
  38839. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38840. var count = this._totalVertices * vertexBuffer.getSize();
  38841. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38842. var copy_1 = new Array(count);
  38843. vertexBuffer.forEach(count, function (value, index) {
  38844. copy_1[index] = value;
  38845. });
  38846. return copy_1;
  38847. }
  38848. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38849. if (data instanceof Array) {
  38850. var offset = vertexBuffer.byteOffset / 4;
  38851. return BABYLON.Tools.Slice(data, offset, offset + count);
  38852. }
  38853. else if (data instanceof ArrayBuffer) {
  38854. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38855. }
  38856. else {
  38857. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38858. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38859. var result = new Float32Array(count);
  38860. var source = new Float32Array(data.buffer, offset, count);
  38861. result.set(source);
  38862. return result;
  38863. }
  38864. return new Float32Array(data.buffer, offset, count);
  38865. }
  38866. }
  38867. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38868. return BABYLON.Tools.Slice(data);
  38869. }
  38870. return data;
  38871. };
  38872. /**
  38873. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38874. * @param kind defines the data kind (Position, normal, etc...)
  38875. * @returns true if the vertex buffer with the specified kind is updatable
  38876. */
  38877. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38878. var vb = this._vertexBuffers[kind];
  38879. if (!vb) {
  38880. return false;
  38881. }
  38882. return vb.isUpdatable();
  38883. };
  38884. /**
  38885. * Gets a specific vertex buffer
  38886. * @param kind defines the data kind (Position, normal, etc...)
  38887. * @returns a {BABYLON.VertexBuffer}
  38888. */
  38889. Geometry.prototype.getVertexBuffer = function (kind) {
  38890. if (!this.isReady()) {
  38891. return null;
  38892. }
  38893. return this._vertexBuffers[kind];
  38894. };
  38895. /**
  38896. * Returns all vertex buffers
  38897. * @return an object holding all vertex buffers indexed by kind
  38898. */
  38899. Geometry.prototype.getVertexBuffers = function () {
  38900. if (!this.isReady()) {
  38901. return null;
  38902. }
  38903. return this._vertexBuffers;
  38904. };
  38905. /**
  38906. * Gets a boolean indicating if specific vertex buffer is present
  38907. * @param kind defines the data kind (Position, normal, etc...)
  38908. * @returns true if data is present
  38909. */
  38910. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38911. if (!this._vertexBuffers) {
  38912. if (this._delayInfo) {
  38913. return this._delayInfo.indexOf(kind) !== -1;
  38914. }
  38915. return false;
  38916. }
  38917. return this._vertexBuffers[kind] !== undefined;
  38918. };
  38919. /**
  38920. * Gets a list of all attached data kinds (Position, normal, etc...)
  38921. * @returns a list of string containing all kinds
  38922. */
  38923. Geometry.prototype.getVerticesDataKinds = function () {
  38924. var result = [];
  38925. var kind;
  38926. if (!this._vertexBuffers && this._delayInfo) {
  38927. for (kind in this._delayInfo) {
  38928. result.push(kind);
  38929. }
  38930. }
  38931. else {
  38932. for (kind in this._vertexBuffers) {
  38933. result.push(kind);
  38934. }
  38935. }
  38936. return result;
  38937. };
  38938. /**
  38939. * Update index buffer
  38940. * @param indices defines the indices to store in the index buffer
  38941. * @param offset defines the offset in the target buffer where to store the data
  38942. */
  38943. Geometry.prototype.updateIndices = function (indices, offset) {
  38944. if (!this._indexBuffer) {
  38945. return;
  38946. }
  38947. if (!this._indexBufferIsUpdatable) {
  38948. this.setIndices(indices, null, true);
  38949. }
  38950. else {
  38951. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38952. }
  38953. };
  38954. /**
  38955. * Creates a new index buffer
  38956. * @param indices defines the indices to store in the index buffer
  38957. * @param totalVertices defines the total number of vertices (could be null)
  38958. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38959. */
  38960. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38961. if (totalVertices === void 0) { totalVertices = null; }
  38962. if (updatable === void 0) { updatable = false; }
  38963. if (this._indexBuffer) {
  38964. this._engine._releaseBuffer(this._indexBuffer);
  38965. }
  38966. this._disposeVertexArrayObjects();
  38967. this._indices = indices;
  38968. this._indexBufferIsUpdatable = updatable;
  38969. if (this._meshes.length !== 0 && this._indices) {
  38970. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38971. }
  38972. if (totalVertices != undefined) { // including null and undefined
  38973. this._totalVertices = totalVertices;
  38974. }
  38975. var meshes = this._meshes;
  38976. var numOfMeshes = meshes.length;
  38977. for (var index = 0; index < numOfMeshes; index++) {
  38978. meshes[index]._createGlobalSubMesh(true);
  38979. }
  38980. this.notifyUpdate();
  38981. };
  38982. /**
  38983. * Return the total number of indices
  38984. * @returns the total number of indices
  38985. */
  38986. Geometry.prototype.getTotalIndices = function () {
  38987. if (!this.isReady()) {
  38988. return 0;
  38989. }
  38990. return this._indices.length;
  38991. };
  38992. /**
  38993. * Gets the index buffer array
  38994. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38995. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38996. * @returns the index buffer array
  38997. */
  38998. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  38999. if (!this.isReady()) {
  39000. return null;
  39001. }
  39002. var orig = this._indices;
  39003. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39004. return orig;
  39005. }
  39006. else {
  39007. var len = orig.length;
  39008. var copy = [];
  39009. for (var i = 0; i < len; i++) {
  39010. copy.push(orig[i]);
  39011. }
  39012. return copy;
  39013. }
  39014. };
  39015. /**
  39016. * Gets the index buffer
  39017. * @return the index buffer
  39018. */
  39019. Geometry.prototype.getIndexBuffer = function () {
  39020. if (!this.isReady()) {
  39021. return null;
  39022. }
  39023. return this._indexBuffer;
  39024. };
  39025. /** @hidden */
  39026. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39027. if (effect === void 0) { effect = null; }
  39028. if (!effect || !this._vertexArrayObjects) {
  39029. return;
  39030. }
  39031. if (this._vertexArrayObjects[effect.key]) {
  39032. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39033. delete this._vertexArrayObjects[effect.key];
  39034. }
  39035. };
  39036. /**
  39037. * Release the associated resources for a specific mesh
  39038. * @param mesh defines the source mesh
  39039. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39040. */
  39041. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39042. var meshes = this._meshes;
  39043. var index = meshes.indexOf(mesh);
  39044. if (index === -1) {
  39045. return;
  39046. }
  39047. meshes.splice(index, 1);
  39048. mesh._geometry = null;
  39049. if (meshes.length === 0 && shouldDispose) {
  39050. this.dispose();
  39051. }
  39052. };
  39053. /**
  39054. * Apply current geometry to a given mesh
  39055. * @param mesh defines the mesh to apply geometry to
  39056. */
  39057. Geometry.prototype.applyToMesh = function (mesh) {
  39058. if (mesh._geometry === this) {
  39059. return;
  39060. }
  39061. var previousGeometry = mesh._geometry;
  39062. if (previousGeometry) {
  39063. previousGeometry.releaseForMesh(mesh);
  39064. }
  39065. var meshes = this._meshes;
  39066. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39067. mesh._geometry = this;
  39068. this._scene.pushGeometry(this);
  39069. meshes.push(mesh);
  39070. if (this.isReady()) {
  39071. this._applyToMesh(mesh);
  39072. }
  39073. else {
  39074. mesh._boundingInfo = this._boundingInfo;
  39075. }
  39076. };
  39077. Geometry.prototype._updateExtend = function (data) {
  39078. if (data === void 0) { data = null; }
  39079. if (!data) {
  39080. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39081. }
  39082. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39083. };
  39084. Geometry.prototype._applyToMesh = function (mesh) {
  39085. var numOfMeshes = this._meshes.length;
  39086. // vertexBuffers
  39087. for (var kind in this._vertexBuffers) {
  39088. if (numOfMeshes === 1) {
  39089. this._vertexBuffers[kind].create();
  39090. }
  39091. var buffer = this._vertexBuffers[kind].getBuffer();
  39092. if (buffer)
  39093. buffer.references = numOfMeshes;
  39094. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39095. if (!this._extend) {
  39096. this._updateExtend();
  39097. }
  39098. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39099. mesh._createGlobalSubMesh(false);
  39100. //bounding info was just created again, world matrix should be applied again.
  39101. mesh._updateBoundingInfo();
  39102. }
  39103. }
  39104. // indexBuffer
  39105. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39106. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39107. }
  39108. if (this._indexBuffer) {
  39109. this._indexBuffer.references = numOfMeshes;
  39110. }
  39111. };
  39112. Geometry.prototype.notifyUpdate = function (kind) {
  39113. if (this.onGeometryUpdated) {
  39114. this.onGeometryUpdated(this, kind);
  39115. }
  39116. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39117. var mesh = _a[_i];
  39118. mesh._markSubMeshesAsAttributesDirty();
  39119. }
  39120. };
  39121. /**
  39122. * Load the geometry if it was flagged as delay loaded
  39123. * @param scene defines the hosting scene
  39124. * @param onLoaded defines a callback called when the geometry is loaded
  39125. */
  39126. Geometry.prototype.load = function (scene, onLoaded) {
  39127. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39128. return;
  39129. }
  39130. if (this.isReady()) {
  39131. if (onLoaded) {
  39132. onLoaded();
  39133. }
  39134. return;
  39135. }
  39136. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39137. this._queueLoad(scene, onLoaded);
  39138. };
  39139. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39140. var _this = this;
  39141. if (!this.delayLoadingFile) {
  39142. return;
  39143. }
  39144. scene._addPendingData(this);
  39145. scene._loadFile(this.delayLoadingFile, function (data) {
  39146. if (!_this._delayLoadingFunction) {
  39147. return;
  39148. }
  39149. _this._delayLoadingFunction(JSON.parse(data), _this);
  39150. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39151. _this._delayInfo = [];
  39152. scene._removePendingData(_this);
  39153. var meshes = _this._meshes;
  39154. var numOfMeshes = meshes.length;
  39155. for (var index = 0; index < numOfMeshes; index++) {
  39156. _this._applyToMesh(meshes[index]);
  39157. }
  39158. if (onLoaded) {
  39159. onLoaded();
  39160. }
  39161. }, undefined, true);
  39162. };
  39163. /**
  39164. * Invert the geometry to move from a right handed system to a left handed one.
  39165. */
  39166. Geometry.prototype.toLeftHanded = function () {
  39167. // Flip faces
  39168. var tIndices = this.getIndices(false);
  39169. if (tIndices != null && tIndices.length > 0) {
  39170. for (var i = 0; i < tIndices.length; i += 3) {
  39171. var tTemp = tIndices[i + 0];
  39172. tIndices[i + 0] = tIndices[i + 2];
  39173. tIndices[i + 2] = tTemp;
  39174. }
  39175. this.setIndices(tIndices);
  39176. }
  39177. // Negate position.z
  39178. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39179. if (tPositions != null && tPositions.length > 0) {
  39180. for (var i = 0; i < tPositions.length; i += 3) {
  39181. tPositions[i + 2] = -tPositions[i + 2];
  39182. }
  39183. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39184. }
  39185. // Negate normal.z
  39186. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39187. if (tNormals != null && tNormals.length > 0) {
  39188. for (var i = 0; i < tNormals.length; i += 3) {
  39189. tNormals[i + 2] = -tNormals[i + 2];
  39190. }
  39191. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39192. }
  39193. };
  39194. // Cache
  39195. /** @hidden */
  39196. Geometry.prototype._resetPointsArrayCache = function () {
  39197. this._positions = null;
  39198. };
  39199. /** @hidden */
  39200. Geometry.prototype._generatePointsArray = function () {
  39201. if (this._positions)
  39202. return true;
  39203. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39204. if (!data || data.length === 0) {
  39205. return false;
  39206. }
  39207. this._positions = [];
  39208. for (var index = 0; index < data.length; index += 3) {
  39209. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39210. }
  39211. return true;
  39212. };
  39213. /**
  39214. * Gets a value indicating if the geometry is disposed
  39215. * @returns true if the geometry was disposed
  39216. */
  39217. Geometry.prototype.isDisposed = function () {
  39218. return this._isDisposed;
  39219. };
  39220. Geometry.prototype._disposeVertexArrayObjects = function () {
  39221. if (this._vertexArrayObjects) {
  39222. for (var kind in this._vertexArrayObjects) {
  39223. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39224. }
  39225. this._vertexArrayObjects = {};
  39226. }
  39227. };
  39228. /**
  39229. * Free all associated resources
  39230. */
  39231. Geometry.prototype.dispose = function () {
  39232. var meshes = this._meshes;
  39233. var numOfMeshes = meshes.length;
  39234. var index;
  39235. for (index = 0; index < numOfMeshes; index++) {
  39236. this.releaseForMesh(meshes[index]);
  39237. }
  39238. this._meshes = [];
  39239. this._disposeVertexArrayObjects();
  39240. for (var kind in this._vertexBuffers) {
  39241. this._vertexBuffers[kind].dispose();
  39242. }
  39243. this._vertexBuffers = {};
  39244. this._totalVertices = 0;
  39245. if (this._indexBuffer) {
  39246. this._engine._releaseBuffer(this._indexBuffer);
  39247. }
  39248. this._indexBuffer = null;
  39249. this._indices = [];
  39250. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39251. this.delayLoadingFile = null;
  39252. this._delayLoadingFunction = null;
  39253. this._delayInfo = [];
  39254. this._boundingInfo = null;
  39255. this._scene.removeGeometry(this);
  39256. this._isDisposed = true;
  39257. };
  39258. /**
  39259. * Clone the current geometry into a new geometry
  39260. * @param id defines the unique ID of the new geometry
  39261. * @returns a new geometry object
  39262. */
  39263. Geometry.prototype.copy = function (id) {
  39264. var vertexData = new BABYLON.VertexData();
  39265. vertexData.indices = [];
  39266. var indices = this.getIndices();
  39267. if (indices) {
  39268. for (var index = 0; index < indices.length; index++) {
  39269. vertexData.indices.push(indices[index]);
  39270. }
  39271. }
  39272. var updatable = false;
  39273. var stopChecking = false;
  39274. var kind;
  39275. for (kind in this._vertexBuffers) {
  39276. // using slice() to make a copy of the array and not just reference it
  39277. var data = this.getVerticesData(kind);
  39278. if (data instanceof Float32Array) {
  39279. vertexData.set(new Float32Array(data), kind);
  39280. }
  39281. else {
  39282. vertexData.set(data.slice(0), kind);
  39283. }
  39284. if (!stopChecking) {
  39285. var vb = this.getVertexBuffer(kind);
  39286. if (vb) {
  39287. updatable = vb.isUpdatable();
  39288. stopChecking = !updatable;
  39289. }
  39290. }
  39291. }
  39292. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39293. geometry.delayLoadState = this.delayLoadState;
  39294. geometry.delayLoadingFile = this.delayLoadingFile;
  39295. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39296. for (kind in this._delayInfo) {
  39297. geometry._delayInfo = geometry._delayInfo || [];
  39298. geometry._delayInfo.push(kind);
  39299. }
  39300. // Bounding info
  39301. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39302. return geometry;
  39303. };
  39304. /**
  39305. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39306. * @return a JSON representation of the current geometry data (without the vertices data)
  39307. */
  39308. Geometry.prototype.serialize = function () {
  39309. var serializationObject = {};
  39310. serializationObject.id = this.id;
  39311. serializationObject.updatable = this._updatable;
  39312. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39313. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39314. }
  39315. return serializationObject;
  39316. };
  39317. Geometry.prototype.toNumberArray = function (origin) {
  39318. if (Array.isArray(origin)) {
  39319. return origin;
  39320. }
  39321. else {
  39322. return Array.prototype.slice.call(origin);
  39323. }
  39324. };
  39325. /**
  39326. * Serialize all vertices data into a JSON oject
  39327. * @returns a JSON representation of the current geometry data
  39328. */
  39329. Geometry.prototype.serializeVerticeData = function () {
  39330. var serializationObject = this.serialize();
  39331. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39332. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39333. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39334. serializationObject.positions._updatable = true;
  39335. }
  39336. }
  39337. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39338. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39339. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39340. serializationObject.normals._updatable = true;
  39341. }
  39342. }
  39343. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39344. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39345. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39346. serializationObject.tangets._updatable = true;
  39347. }
  39348. }
  39349. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39350. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39351. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39352. serializationObject.uvs._updatable = true;
  39353. }
  39354. }
  39355. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39356. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39357. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39358. serializationObject.uv2s._updatable = true;
  39359. }
  39360. }
  39361. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39362. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39363. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39364. serializationObject.uv3s._updatable = true;
  39365. }
  39366. }
  39367. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39368. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39369. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39370. serializationObject.uv4s._updatable = true;
  39371. }
  39372. }
  39373. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39374. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39375. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39376. serializationObject.uv5s._updatable = true;
  39377. }
  39378. }
  39379. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39380. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39381. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39382. serializationObject.uv6s._updatable = true;
  39383. }
  39384. }
  39385. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39386. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39387. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39388. serializationObject.colors._updatable = true;
  39389. }
  39390. }
  39391. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39392. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39393. serializationObject.matricesIndices._isExpanded = true;
  39394. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39395. serializationObject.matricesIndices._updatable = true;
  39396. }
  39397. }
  39398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39399. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39400. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39401. serializationObject.matricesWeights._updatable = true;
  39402. }
  39403. }
  39404. serializationObject.indices = this.toNumberArray(this.getIndices());
  39405. return serializationObject;
  39406. };
  39407. // Statics
  39408. /**
  39409. * Extracts a clone of a mesh geometry
  39410. * @param mesh defines the source mesh
  39411. * @param id defines the unique ID of the new geometry object
  39412. * @returns the new geometry object
  39413. */
  39414. Geometry.ExtractFromMesh = function (mesh, id) {
  39415. var geometry = mesh._geometry;
  39416. if (!geometry) {
  39417. return null;
  39418. }
  39419. return geometry.copy(id);
  39420. };
  39421. /**
  39422. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39423. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39424. * Be aware Math.random() could cause collisions, but:
  39425. * "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"
  39426. * @returns a string containing a new GUID
  39427. */
  39428. Geometry.RandomId = function () {
  39429. return BABYLON.Tools.RandomId();
  39430. };
  39431. /** @hidden */
  39432. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39433. var scene = mesh.getScene();
  39434. // Geometry
  39435. var geometryId = parsedGeometry.geometryId;
  39436. if (geometryId) {
  39437. var geometry = scene.getGeometryByID(geometryId);
  39438. if (geometry) {
  39439. geometry.applyToMesh(mesh);
  39440. }
  39441. }
  39442. else if (parsedGeometry instanceof ArrayBuffer) {
  39443. var binaryInfo = mesh._binaryInfo;
  39444. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39445. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39446. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39447. }
  39448. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39449. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39450. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39451. }
  39452. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39453. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39454. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39455. }
  39456. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39457. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39458. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39459. }
  39460. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39461. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39462. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39463. }
  39464. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39465. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39466. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39467. }
  39468. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39469. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39470. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39471. }
  39472. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39473. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39474. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39475. }
  39476. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39477. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39478. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39479. }
  39480. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39481. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39482. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39483. }
  39484. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39485. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39486. var floatIndices = [];
  39487. for (var i = 0; i < matricesIndicesData.length; i++) {
  39488. var index = matricesIndicesData[i];
  39489. floatIndices.push(index & 0x000000FF);
  39490. floatIndices.push((index & 0x0000FF00) >> 8);
  39491. floatIndices.push((index & 0x00FF0000) >> 16);
  39492. floatIndices.push(index >> 24);
  39493. }
  39494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39495. }
  39496. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39497. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39498. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39499. }
  39500. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39501. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39502. mesh.setIndices(indicesData, null);
  39503. }
  39504. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39505. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39506. mesh.subMeshes = [];
  39507. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39508. var materialIndex = subMeshesData[(i * 5) + 0];
  39509. var verticesStart = subMeshesData[(i * 5) + 1];
  39510. var verticesCount = subMeshesData[(i * 5) + 2];
  39511. var indexStart = subMeshesData[(i * 5) + 3];
  39512. var indexCount = subMeshesData[(i * 5) + 4];
  39513. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39514. }
  39515. }
  39516. }
  39517. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39518. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39519. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39520. if (parsedGeometry.tangents) {
  39521. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39522. }
  39523. if (parsedGeometry.uvs) {
  39524. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39525. }
  39526. if (parsedGeometry.uvs2) {
  39527. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39528. }
  39529. if (parsedGeometry.uvs3) {
  39530. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39531. }
  39532. if (parsedGeometry.uvs4) {
  39533. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39534. }
  39535. if (parsedGeometry.uvs5) {
  39536. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39537. }
  39538. if (parsedGeometry.uvs6) {
  39539. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39540. }
  39541. if (parsedGeometry.colors) {
  39542. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39543. }
  39544. if (parsedGeometry.matricesIndices) {
  39545. if (!parsedGeometry.matricesIndices._isExpanded) {
  39546. var floatIndices = [];
  39547. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39548. var matricesIndex = parsedGeometry.matricesIndices[i];
  39549. floatIndices.push(matricesIndex & 0x000000FF);
  39550. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39551. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39552. floatIndices.push(matricesIndex >> 24);
  39553. }
  39554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39555. }
  39556. else {
  39557. delete parsedGeometry.matricesIndices._isExpanded;
  39558. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39559. }
  39560. }
  39561. if (parsedGeometry.matricesIndicesExtra) {
  39562. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39563. var floatIndices = [];
  39564. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39565. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39566. floatIndices.push(matricesIndex & 0x000000FF);
  39567. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39568. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39569. floatIndices.push(matricesIndex >> 24);
  39570. }
  39571. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39572. }
  39573. else {
  39574. delete parsedGeometry.matricesIndices._isExpanded;
  39575. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39576. }
  39577. }
  39578. if (parsedGeometry.matricesWeights) {
  39579. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39580. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39581. }
  39582. if (parsedGeometry.matricesWeightsExtra) {
  39583. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39584. }
  39585. mesh.setIndices(parsedGeometry.indices, null);
  39586. }
  39587. // SubMeshes
  39588. if (parsedGeometry.subMeshes) {
  39589. mesh.subMeshes = [];
  39590. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39591. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39592. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39593. }
  39594. }
  39595. // Flat shading
  39596. if (mesh._shouldGenerateFlatShading) {
  39597. mesh.convertToFlatShadedMesh();
  39598. delete mesh._shouldGenerateFlatShading;
  39599. }
  39600. // Update
  39601. mesh.computeWorldMatrix(true);
  39602. scene.onMeshImportedObservable.notifyObservers(mesh);
  39603. };
  39604. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39605. var epsilon = 1e-3;
  39606. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39607. return;
  39608. }
  39609. var noInfluenceBoneIndex = 0.0;
  39610. if (parsedGeometry.skeletonId > -1) {
  39611. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39612. if (!skeleton) {
  39613. return;
  39614. }
  39615. noInfluenceBoneIndex = skeleton.bones.length;
  39616. }
  39617. else {
  39618. return;
  39619. }
  39620. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39621. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39622. var matricesWeights = parsedGeometry.matricesWeights;
  39623. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39624. var influencers = parsedGeometry.numBoneInfluencer;
  39625. var size = matricesWeights.length;
  39626. for (var i = 0; i < size; i += 4) {
  39627. var weight = 0.0;
  39628. var firstZeroWeight = -1;
  39629. for (var j = 0; j < 4; j++) {
  39630. var w = matricesWeights[i + j];
  39631. weight += w;
  39632. if (w < epsilon && firstZeroWeight < 0) {
  39633. firstZeroWeight = j;
  39634. }
  39635. }
  39636. if (matricesWeightsExtra) {
  39637. for (var j = 0; j < 4; j++) {
  39638. var w = matricesWeightsExtra[i + j];
  39639. weight += w;
  39640. if (w < epsilon && firstZeroWeight < 0) {
  39641. firstZeroWeight = j + 4;
  39642. }
  39643. }
  39644. }
  39645. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39646. firstZeroWeight = influencers - 1;
  39647. }
  39648. if (weight > epsilon) {
  39649. var mweight = 1.0 / weight;
  39650. for (var j = 0; j < 4; j++) {
  39651. matricesWeights[i + j] *= mweight;
  39652. }
  39653. if (matricesWeightsExtra) {
  39654. for (var j = 0; j < 4; j++) {
  39655. matricesWeightsExtra[i + j] *= mweight;
  39656. }
  39657. }
  39658. }
  39659. else {
  39660. if (firstZeroWeight >= 4) {
  39661. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39662. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39663. }
  39664. else {
  39665. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39666. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39667. }
  39668. }
  39669. }
  39670. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39671. if (parsedGeometry.matricesWeightsExtra) {
  39672. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39673. }
  39674. };
  39675. /**
  39676. * Create a new geometry from persisted data (Using .babylon file format)
  39677. * @param parsedVertexData defines the persisted data
  39678. * @param scene defines the hosting scene
  39679. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39680. * @returns the new geometry object
  39681. */
  39682. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39683. if (scene.getGeometryByID(parsedVertexData.id)) {
  39684. return null; // null since geometry could be something else than a box...
  39685. }
  39686. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39687. if (BABYLON.Tags) {
  39688. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39689. }
  39690. if (parsedVertexData.delayLoadingFile) {
  39691. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39692. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39693. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39694. geometry._delayInfo = [];
  39695. if (parsedVertexData.hasUVs) {
  39696. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39697. }
  39698. if (parsedVertexData.hasUVs2) {
  39699. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39700. }
  39701. if (parsedVertexData.hasUVs3) {
  39702. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39703. }
  39704. if (parsedVertexData.hasUVs4) {
  39705. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39706. }
  39707. if (parsedVertexData.hasUVs5) {
  39708. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39709. }
  39710. if (parsedVertexData.hasUVs6) {
  39711. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39712. }
  39713. if (parsedVertexData.hasColors) {
  39714. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39715. }
  39716. if (parsedVertexData.hasMatricesIndices) {
  39717. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39718. }
  39719. if (parsedVertexData.hasMatricesWeights) {
  39720. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39721. }
  39722. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39723. }
  39724. else {
  39725. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39726. }
  39727. scene.pushGeometry(geometry, true);
  39728. return geometry;
  39729. };
  39730. return Geometry;
  39731. }());
  39732. BABYLON.Geometry = Geometry;
  39733. // Primitives
  39734. /// Abstract class
  39735. /**
  39736. * Abstract class used to provide common services for all typed geometries
  39737. * @hidden
  39738. */
  39739. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39740. __extends(_PrimitiveGeometry, _super);
  39741. /**
  39742. * Creates a new typed geometry
  39743. * @param id defines the unique ID of the geometry
  39744. * @param scene defines the hosting scene
  39745. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39746. * @param mesh defines the hosting mesh (can be null)
  39747. */
  39748. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39749. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39750. if (mesh === void 0) { mesh = null; }
  39751. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39752. _this._canBeRegenerated = _canBeRegenerated;
  39753. _this._beingRegenerated = true;
  39754. _this.regenerate();
  39755. _this._beingRegenerated = false;
  39756. return _this;
  39757. }
  39758. /**
  39759. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39760. * @returns true if the geometry can be regenerated
  39761. */
  39762. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39763. return this._canBeRegenerated;
  39764. };
  39765. /**
  39766. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39767. */
  39768. _PrimitiveGeometry.prototype.regenerate = function () {
  39769. if (!this._canBeRegenerated) {
  39770. return;
  39771. }
  39772. this._beingRegenerated = true;
  39773. this.setAllVerticesData(this._regenerateVertexData(), false);
  39774. this._beingRegenerated = false;
  39775. };
  39776. /**
  39777. * Clone the geometry
  39778. * @param id defines the unique ID of the new geometry
  39779. * @returns the new geometry
  39780. */
  39781. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39782. return _super.prototype.copy.call(this, id);
  39783. };
  39784. // overrides
  39785. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39786. if (!this._beingRegenerated) {
  39787. return;
  39788. }
  39789. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39790. };
  39791. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39792. if (!this._beingRegenerated) {
  39793. return;
  39794. }
  39795. _super.prototype.setVerticesData.call(this, kind, data, false);
  39796. };
  39797. // to override
  39798. /** @hidden */
  39799. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39800. throw new Error("Abstract method");
  39801. };
  39802. _PrimitiveGeometry.prototype.copy = function (id) {
  39803. throw new Error("Must be overriden in sub-classes.");
  39804. };
  39805. _PrimitiveGeometry.prototype.serialize = function () {
  39806. var serializationObject = _super.prototype.serialize.call(this);
  39807. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39808. return serializationObject;
  39809. };
  39810. return _PrimitiveGeometry;
  39811. }(Geometry));
  39812. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39813. /**
  39814. * Creates a ribbon geometry
  39815. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39816. */
  39817. var RibbonGeometry = /** @class */ (function (_super) {
  39818. __extends(RibbonGeometry, _super);
  39819. /**
  39820. * Creates a ribbon geometry
  39821. * @param id defines the unique ID of the geometry
  39822. * @param scene defines the hosting scene
  39823. * @param pathArray defines the array of paths to use
  39824. * @param closeArray defines if the last path and the first path must be joined
  39825. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39826. * @param offset defines the offset between points
  39827. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39828. * @param mesh defines the hosting mesh (can be null)
  39829. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39830. */
  39831. function RibbonGeometry(id, scene,
  39832. /**
  39833. * Defines the array of paths to use
  39834. */
  39835. pathArray,
  39836. /**
  39837. * Defines if the last and first points of each path in your pathArray must be joined
  39838. */
  39839. closeArray,
  39840. /**
  39841. * Defines if the last and first points of each path in your pathArray must be joined
  39842. */
  39843. closePath,
  39844. /**
  39845. * Defines the offset between points
  39846. */
  39847. offset, canBeRegenerated, mesh,
  39848. /**
  39849. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39850. */
  39851. side) {
  39852. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39853. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39854. _this.pathArray = pathArray;
  39855. _this.closeArray = closeArray;
  39856. _this.closePath = closePath;
  39857. _this.offset = offset;
  39858. _this.side = side;
  39859. return _this;
  39860. }
  39861. /** @hidden */
  39862. RibbonGeometry.prototype._regenerateVertexData = function () {
  39863. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39864. };
  39865. RibbonGeometry.prototype.copy = function (id) {
  39866. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39867. };
  39868. return RibbonGeometry;
  39869. }(_PrimitiveGeometry));
  39870. BABYLON.RibbonGeometry = RibbonGeometry;
  39871. /**
  39872. * Creates a box geometry
  39873. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39874. */
  39875. var BoxGeometry = /** @class */ (function (_super) {
  39876. __extends(BoxGeometry, _super);
  39877. /**
  39878. * Creates a box geometry
  39879. * @param id defines the unique ID of the geometry
  39880. * @param scene defines the hosting scene
  39881. * @param size defines the zise of the box (width, height and depth are the same)
  39882. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39883. * @param mesh defines the hosting mesh (can be null)
  39884. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39885. */
  39886. function BoxGeometry(id, scene,
  39887. /**
  39888. * Defines the zise of the box (width, height and depth are the same)
  39889. */
  39890. size, canBeRegenerated, mesh,
  39891. /**
  39892. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39893. */
  39894. side) {
  39895. if (mesh === void 0) { mesh = null; }
  39896. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39897. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39898. _this.size = size;
  39899. _this.side = side;
  39900. return _this;
  39901. }
  39902. /** @hidden */
  39903. BoxGeometry.prototype._regenerateVertexData = function () {
  39904. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39905. };
  39906. BoxGeometry.prototype.copy = function (id) {
  39907. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39908. };
  39909. BoxGeometry.prototype.serialize = function () {
  39910. var serializationObject = _super.prototype.serialize.call(this);
  39911. serializationObject.size = this.size;
  39912. return serializationObject;
  39913. };
  39914. BoxGeometry.Parse = function (parsedBox, scene) {
  39915. if (scene.getGeometryByID(parsedBox.id)) {
  39916. return null; // null since geometry could be something else than a box...
  39917. }
  39918. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39919. if (BABYLON.Tags) {
  39920. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39921. }
  39922. scene.pushGeometry(box, true);
  39923. return box;
  39924. };
  39925. return BoxGeometry;
  39926. }(_PrimitiveGeometry));
  39927. BABYLON.BoxGeometry = BoxGeometry;
  39928. /**
  39929. * Creates a sphere geometry
  39930. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39931. */
  39932. var SphereGeometry = /** @class */ (function (_super) {
  39933. __extends(SphereGeometry, _super);
  39934. /**
  39935. * Create a new sphere geometry
  39936. * @param id defines the unique ID of the geometry
  39937. * @param scene defines the hosting scene
  39938. * @param segments defines the number of segments to use to create the sphere
  39939. * @param diameter defines the diameter of the sphere
  39940. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39941. * @param mesh defines the hosting mesh (can be null)
  39942. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39943. */
  39944. function SphereGeometry(id, scene,
  39945. /**
  39946. * Defines the number of segments to use to create the sphere
  39947. */
  39948. segments,
  39949. /**
  39950. * Defines the diameter of the sphere
  39951. */
  39952. diameter, canBeRegenerated, mesh,
  39953. /**
  39954. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39955. */
  39956. side) {
  39957. if (mesh === void 0) { mesh = null; }
  39958. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39959. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39960. _this.segments = segments;
  39961. _this.diameter = diameter;
  39962. _this.side = side;
  39963. return _this;
  39964. }
  39965. /** @hidden */
  39966. SphereGeometry.prototype._regenerateVertexData = function () {
  39967. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39968. };
  39969. SphereGeometry.prototype.copy = function (id) {
  39970. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39971. };
  39972. SphereGeometry.prototype.serialize = function () {
  39973. var serializationObject = _super.prototype.serialize.call(this);
  39974. serializationObject.segments = this.segments;
  39975. serializationObject.diameter = this.diameter;
  39976. return serializationObject;
  39977. };
  39978. SphereGeometry.Parse = function (parsedSphere, scene) {
  39979. if (scene.getGeometryByID(parsedSphere.id)) {
  39980. return null; // null since geometry could be something else than a sphere...
  39981. }
  39982. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39983. if (BABYLON.Tags) {
  39984. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39985. }
  39986. scene.pushGeometry(sphere, true);
  39987. return sphere;
  39988. };
  39989. return SphereGeometry;
  39990. }(_PrimitiveGeometry));
  39991. BABYLON.SphereGeometry = SphereGeometry;
  39992. /**
  39993. * Creates a disc geometry
  39994. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39995. */
  39996. var DiscGeometry = /** @class */ (function (_super) {
  39997. __extends(DiscGeometry, _super);
  39998. /**
  39999. * Creates a new disc geometry
  40000. * @param id defines the unique ID of the geometry
  40001. * @param scene defines the hosting scene
  40002. * @param radius defines the radius of the disc
  40003. * @param tessellation defines the tesselation factor to apply to the disc
  40004. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40005. * @param mesh defines the hosting mesh (can be null)
  40006. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40007. */
  40008. function DiscGeometry(id, scene,
  40009. /**
  40010. * Defines the radius of the disc
  40011. */
  40012. radius,
  40013. /**
  40014. * Defines the tesselation factor to apply to the disc
  40015. */
  40016. tessellation, canBeRegenerated, mesh,
  40017. /**
  40018. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40019. */
  40020. side) {
  40021. if (mesh === void 0) { mesh = null; }
  40022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40023. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40024. _this.radius = radius;
  40025. _this.tessellation = tessellation;
  40026. _this.side = side;
  40027. return _this;
  40028. }
  40029. /** @hidden */
  40030. DiscGeometry.prototype._regenerateVertexData = function () {
  40031. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40032. };
  40033. DiscGeometry.prototype.copy = function (id) {
  40034. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40035. };
  40036. return DiscGeometry;
  40037. }(_PrimitiveGeometry));
  40038. BABYLON.DiscGeometry = DiscGeometry;
  40039. /**
  40040. * Creates a new cylinder geometry
  40041. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40042. */
  40043. var CylinderGeometry = /** @class */ (function (_super) {
  40044. __extends(CylinderGeometry, _super);
  40045. /**
  40046. * Creates a new cylinder geometry
  40047. * @param id defines the unique ID of the geometry
  40048. * @param scene defines the hosting scene
  40049. * @param height defines the height of the cylinder
  40050. * @param diameterTop defines the diameter of the cylinder's top cap
  40051. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40052. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40053. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40054. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40055. * @param mesh defines the hosting mesh (can be null)
  40056. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40057. */
  40058. function CylinderGeometry(id, scene,
  40059. /**
  40060. * Defines the height of the cylinder
  40061. */
  40062. height,
  40063. /**
  40064. * Defines the diameter of the cylinder's top cap
  40065. */
  40066. diameterTop,
  40067. /**
  40068. * Defines the diameter of the cylinder's bottom cap
  40069. */
  40070. diameterBottom,
  40071. /**
  40072. * Defines the tessellation factor to apply to the cylinder
  40073. */
  40074. tessellation,
  40075. /**
  40076. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40077. */
  40078. subdivisions, canBeRegenerated, mesh,
  40079. /**
  40080. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40081. */
  40082. side) {
  40083. if (subdivisions === void 0) { subdivisions = 1; }
  40084. if (mesh === void 0) { mesh = null; }
  40085. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40086. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40087. _this.height = height;
  40088. _this.diameterTop = diameterTop;
  40089. _this.diameterBottom = diameterBottom;
  40090. _this.tessellation = tessellation;
  40091. _this.subdivisions = subdivisions;
  40092. _this.side = side;
  40093. return _this;
  40094. }
  40095. /** @hidden */
  40096. CylinderGeometry.prototype._regenerateVertexData = function () {
  40097. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40098. };
  40099. CylinderGeometry.prototype.copy = function (id) {
  40100. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40101. };
  40102. CylinderGeometry.prototype.serialize = function () {
  40103. var serializationObject = _super.prototype.serialize.call(this);
  40104. serializationObject.height = this.height;
  40105. serializationObject.diameterTop = this.diameterTop;
  40106. serializationObject.diameterBottom = this.diameterBottom;
  40107. serializationObject.tessellation = this.tessellation;
  40108. return serializationObject;
  40109. };
  40110. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40111. if (scene.getGeometryByID(parsedCylinder.id)) {
  40112. return null; // null since geometry could be something else than a cylinder...
  40113. }
  40114. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40115. if (BABYLON.Tags) {
  40116. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40117. }
  40118. scene.pushGeometry(cylinder, true);
  40119. return cylinder;
  40120. };
  40121. return CylinderGeometry;
  40122. }(_PrimitiveGeometry));
  40123. BABYLON.CylinderGeometry = CylinderGeometry;
  40124. /**
  40125. * Creates a new torus geometry
  40126. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40127. */
  40128. var TorusGeometry = /** @class */ (function (_super) {
  40129. __extends(TorusGeometry, _super);
  40130. /**
  40131. * Creates a new torus geometry
  40132. * @param id defines the unique ID of the geometry
  40133. * @param scene defines the hosting scene
  40134. * @param diameter defines the diameter of the torus
  40135. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40136. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40137. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40138. * @param mesh defines the hosting mesh (can be null)
  40139. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40140. */
  40141. function TorusGeometry(id, scene,
  40142. /**
  40143. * Defines the diameter of the torus
  40144. */
  40145. diameter,
  40146. /**
  40147. * Defines the thickness of the torus (ie. internal diameter)
  40148. */
  40149. thickness,
  40150. /**
  40151. * Defines the tesselation factor to apply to the torus
  40152. */
  40153. tessellation, canBeRegenerated, mesh,
  40154. /**
  40155. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40156. */
  40157. side) {
  40158. if (mesh === void 0) { mesh = null; }
  40159. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40160. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40161. _this.diameter = diameter;
  40162. _this.thickness = thickness;
  40163. _this.tessellation = tessellation;
  40164. _this.side = side;
  40165. return _this;
  40166. }
  40167. /** @hidden */
  40168. TorusGeometry.prototype._regenerateVertexData = function () {
  40169. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40170. };
  40171. TorusGeometry.prototype.copy = function (id) {
  40172. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40173. };
  40174. TorusGeometry.prototype.serialize = function () {
  40175. var serializationObject = _super.prototype.serialize.call(this);
  40176. serializationObject.diameter = this.diameter;
  40177. serializationObject.thickness = this.thickness;
  40178. serializationObject.tessellation = this.tessellation;
  40179. return serializationObject;
  40180. };
  40181. TorusGeometry.Parse = function (parsedTorus, scene) {
  40182. if (scene.getGeometryByID(parsedTorus.id)) {
  40183. return null; // null since geometry could be something else than a torus...
  40184. }
  40185. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40186. if (BABYLON.Tags) {
  40187. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40188. }
  40189. scene.pushGeometry(torus, true);
  40190. return torus;
  40191. };
  40192. return TorusGeometry;
  40193. }(_PrimitiveGeometry));
  40194. BABYLON.TorusGeometry = TorusGeometry;
  40195. /**
  40196. * Creates a new ground geometry
  40197. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40198. */
  40199. var GroundGeometry = /** @class */ (function (_super) {
  40200. __extends(GroundGeometry, _super);
  40201. /**
  40202. * Creates a new ground geometry
  40203. * @param id defines the unique ID of the geometry
  40204. * @param scene defines the hosting scene
  40205. * @param width defines the width of the ground
  40206. * @param height defines the height of the ground
  40207. * @param subdivisions defines the subdivisions to apply to the ground
  40208. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40209. * @param mesh defines the hosting mesh (can be null)
  40210. */
  40211. function GroundGeometry(id, scene,
  40212. /**
  40213. * Defines the width of the ground
  40214. */
  40215. width,
  40216. /**
  40217. * Defines the height of the ground
  40218. */
  40219. height,
  40220. /**
  40221. * Defines the subdivisions to apply to the ground
  40222. */
  40223. subdivisions, canBeRegenerated, mesh) {
  40224. if (mesh === void 0) { mesh = null; }
  40225. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40226. _this.width = width;
  40227. _this.height = height;
  40228. _this.subdivisions = subdivisions;
  40229. return _this;
  40230. }
  40231. /** @hidden */
  40232. GroundGeometry.prototype._regenerateVertexData = function () {
  40233. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40234. };
  40235. GroundGeometry.prototype.copy = function (id) {
  40236. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40237. };
  40238. GroundGeometry.prototype.serialize = function () {
  40239. var serializationObject = _super.prototype.serialize.call(this);
  40240. serializationObject.width = this.width;
  40241. serializationObject.height = this.height;
  40242. serializationObject.subdivisions = this.subdivisions;
  40243. return serializationObject;
  40244. };
  40245. GroundGeometry.Parse = function (parsedGround, scene) {
  40246. if (scene.getGeometryByID(parsedGround.id)) {
  40247. return null; // null since geometry could be something else than a ground...
  40248. }
  40249. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40250. if (BABYLON.Tags) {
  40251. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40252. }
  40253. scene.pushGeometry(ground, true);
  40254. return ground;
  40255. };
  40256. return GroundGeometry;
  40257. }(_PrimitiveGeometry));
  40258. BABYLON.GroundGeometry = GroundGeometry;
  40259. /**
  40260. * Creates a tiled ground geometry
  40261. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40262. */
  40263. var TiledGroundGeometry = /** @class */ (function (_super) {
  40264. __extends(TiledGroundGeometry, _super);
  40265. /**
  40266. * Creates a tiled ground geometry
  40267. * @param id defines the unique ID of the geometry
  40268. * @param scene defines the hosting scene
  40269. * @param xmin defines the minimum value on X axis
  40270. * @param zmin defines the minimum value on Z axis
  40271. * @param xmax defines the maximum value on X axis
  40272. * @param zmax defines the maximum value on Z axis
  40273. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40274. * @param precision defines the precision to use when computing the tiles
  40275. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40276. * @param mesh defines the hosting mesh (can be null)
  40277. */
  40278. function TiledGroundGeometry(id, scene,
  40279. /**
  40280. * Defines the minimum value on X axis
  40281. */
  40282. xmin,
  40283. /**
  40284. * Defines the minimum value on Z axis
  40285. */
  40286. zmin,
  40287. /**
  40288. * Defines the maximum value on X axis
  40289. */
  40290. xmax,
  40291. /**
  40292. * Defines the maximum value on Z axis
  40293. */
  40294. zmax,
  40295. /**
  40296. * Defines the subdivisions to apply to the ground
  40297. */
  40298. subdivisions,
  40299. /**
  40300. * Defines the precision to use when computing the tiles
  40301. */
  40302. precision, canBeRegenerated, mesh) {
  40303. if (mesh === void 0) { mesh = null; }
  40304. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40305. _this.xmin = xmin;
  40306. _this.zmin = zmin;
  40307. _this.xmax = xmax;
  40308. _this.zmax = zmax;
  40309. _this.subdivisions = subdivisions;
  40310. _this.precision = precision;
  40311. return _this;
  40312. }
  40313. /** @hidden */
  40314. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40315. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40316. };
  40317. TiledGroundGeometry.prototype.copy = function (id) {
  40318. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40319. };
  40320. return TiledGroundGeometry;
  40321. }(_PrimitiveGeometry));
  40322. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40323. /**
  40324. * Creates a plane geometry
  40325. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40326. */
  40327. var PlaneGeometry = /** @class */ (function (_super) {
  40328. __extends(PlaneGeometry, _super);
  40329. /**
  40330. * Creates a plane geometry
  40331. * @param id defines the unique ID of the geometry
  40332. * @param scene defines the hosting scene
  40333. * @param size defines the size of the plane (width === height)
  40334. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40335. * @param mesh defines the hosting mesh (can be null)
  40336. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40337. */
  40338. function PlaneGeometry(id, scene,
  40339. /**
  40340. * Defines the size of the plane (width === height)
  40341. */
  40342. size, canBeRegenerated, mesh,
  40343. /**
  40344. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40345. */
  40346. side) {
  40347. if (mesh === void 0) { mesh = null; }
  40348. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40349. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40350. _this.size = size;
  40351. _this.side = side;
  40352. return _this;
  40353. }
  40354. /** @hidden */
  40355. PlaneGeometry.prototype._regenerateVertexData = function () {
  40356. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40357. };
  40358. PlaneGeometry.prototype.copy = function (id) {
  40359. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40360. };
  40361. PlaneGeometry.prototype.serialize = function () {
  40362. var serializationObject = _super.prototype.serialize.call(this);
  40363. serializationObject.size = this.size;
  40364. return serializationObject;
  40365. };
  40366. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40367. if (scene.getGeometryByID(parsedPlane.id)) {
  40368. return null; // null since geometry could be something else than a ground...
  40369. }
  40370. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40371. if (BABYLON.Tags) {
  40372. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40373. }
  40374. scene.pushGeometry(plane, true);
  40375. return plane;
  40376. };
  40377. return PlaneGeometry;
  40378. }(_PrimitiveGeometry));
  40379. BABYLON.PlaneGeometry = PlaneGeometry;
  40380. /**
  40381. * Creates a torus knot geometry
  40382. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40383. */
  40384. var TorusKnotGeometry = /** @class */ (function (_super) {
  40385. __extends(TorusKnotGeometry, _super);
  40386. /**
  40387. * Creates a torus knot geometry
  40388. * @param id defines the unique ID of the geometry
  40389. * @param scene defines the hosting scene
  40390. * @param radius defines the radius of the torus knot
  40391. * @param tube defines the thickness of the torus knot tube
  40392. * @param radialSegments defines the number of radial segments
  40393. * @param tubularSegments defines the number of tubular segments
  40394. * @param p defines the first number of windings
  40395. * @param q defines the second number of windings
  40396. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40397. * @param mesh defines the hosting mesh (can be null)
  40398. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40399. */
  40400. function TorusKnotGeometry(id, scene,
  40401. /**
  40402. * Defines the radius of the torus knot
  40403. */
  40404. radius,
  40405. /**
  40406. * Defines the thickness of the torus knot tube
  40407. */
  40408. tube,
  40409. /**
  40410. * Defines the number of radial segments
  40411. */
  40412. radialSegments,
  40413. /**
  40414. * Defines the number of tubular segments
  40415. */
  40416. tubularSegments,
  40417. /**
  40418. * Defines the first number of windings
  40419. */
  40420. p,
  40421. /**
  40422. * Defines the second number of windings
  40423. */
  40424. q, canBeRegenerated, mesh,
  40425. /**
  40426. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40427. */
  40428. side) {
  40429. if (mesh === void 0) { mesh = null; }
  40430. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40431. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40432. _this.radius = radius;
  40433. _this.tube = tube;
  40434. _this.radialSegments = radialSegments;
  40435. _this.tubularSegments = tubularSegments;
  40436. _this.p = p;
  40437. _this.q = q;
  40438. _this.side = side;
  40439. return _this;
  40440. }
  40441. /** @hidden */
  40442. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40443. 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 });
  40444. };
  40445. TorusKnotGeometry.prototype.copy = function (id) {
  40446. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40447. };
  40448. TorusKnotGeometry.prototype.serialize = function () {
  40449. var serializationObject = _super.prototype.serialize.call(this);
  40450. serializationObject.radius = this.radius;
  40451. serializationObject.tube = this.tube;
  40452. serializationObject.radialSegments = this.radialSegments;
  40453. serializationObject.tubularSegments = this.tubularSegments;
  40454. serializationObject.p = this.p;
  40455. serializationObject.q = this.q;
  40456. return serializationObject;
  40457. };
  40458. ;
  40459. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40460. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40461. return null; // null since geometry could be something else than a ground...
  40462. }
  40463. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40464. if (BABYLON.Tags) {
  40465. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40466. }
  40467. scene.pushGeometry(torusKnot, true);
  40468. return torusKnot;
  40469. };
  40470. return TorusKnotGeometry;
  40471. }(_PrimitiveGeometry));
  40472. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40473. //}
  40474. })(BABYLON || (BABYLON = {}));
  40475. //# sourceMappingURL=babylon.geometry.js.map
  40476. var BABYLON;
  40477. (function (BABYLON) {
  40478. /**
  40479. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40480. */
  40481. var PerformanceMonitor = /** @class */ (function () {
  40482. /**
  40483. * constructor
  40484. * @param frameSampleSize The number of samples required to saturate the sliding window
  40485. */
  40486. function PerformanceMonitor(frameSampleSize) {
  40487. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40488. this._enabled = true;
  40489. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40490. }
  40491. /**
  40492. * Samples current frame
  40493. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40494. */
  40495. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40496. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40497. if (!this._enabled)
  40498. return;
  40499. if (this._lastFrameTimeMs != null) {
  40500. var dt = timeMs - this._lastFrameTimeMs;
  40501. this._rollingFrameTime.add(dt);
  40502. }
  40503. this._lastFrameTimeMs = timeMs;
  40504. };
  40505. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40506. /**
  40507. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40508. * @return Average frame time in milliseconds
  40509. */
  40510. get: function () {
  40511. return this._rollingFrameTime.average;
  40512. },
  40513. enumerable: true,
  40514. configurable: true
  40515. });
  40516. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40517. /**
  40518. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40519. * @return Frame time variance in milliseconds squared
  40520. */
  40521. get: function () {
  40522. return this._rollingFrameTime.variance;
  40523. },
  40524. enumerable: true,
  40525. configurable: true
  40526. });
  40527. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40528. /**
  40529. * Returns the frame time of the most recent frame
  40530. * @return Frame time in milliseconds
  40531. */
  40532. get: function () {
  40533. return this._rollingFrameTime.history(0);
  40534. },
  40535. enumerable: true,
  40536. configurable: true
  40537. });
  40538. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40539. /**
  40540. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40541. * @return Framerate in frames per second
  40542. */
  40543. get: function () {
  40544. return 1000.0 / this._rollingFrameTime.average;
  40545. },
  40546. enumerable: true,
  40547. configurable: true
  40548. });
  40549. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40550. /**
  40551. * Returns the average framerate in frames per second using the most recent frame time
  40552. * @return Framerate in frames per second
  40553. */
  40554. get: function () {
  40555. var history = this._rollingFrameTime.history(0);
  40556. if (history === 0) {
  40557. return 0;
  40558. }
  40559. return 1000.0 / history;
  40560. },
  40561. enumerable: true,
  40562. configurable: true
  40563. });
  40564. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40565. /**
  40566. * Returns true if enough samples have been taken to completely fill the sliding window
  40567. * @return true if saturated
  40568. */
  40569. get: function () {
  40570. return this._rollingFrameTime.isSaturated();
  40571. },
  40572. enumerable: true,
  40573. configurable: true
  40574. });
  40575. /**
  40576. * Enables contributions to the sliding window sample set
  40577. */
  40578. PerformanceMonitor.prototype.enable = function () {
  40579. this._enabled = true;
  40580. };
  40581. /**
  40582. * Disables contributions to the sliding window sample set
  40583. * Samples will not be interpolated over the disabled period
  40584. */
  40585. PerformanceMonitor.prototype.disable = function () {
  40586. this._enabled = false;
  40587. //clear last sample to avoid interpolating over the disabled period when next enabled
  40588. this._lastFrameTimeMs = null;
  40589. };
  40590. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40591. /**
  40592. * Returns true if sampling is enabled
  40593. * @return true if enabled
  40594. */
  40595. get: function () {
  40596. return this._enabled;
  40597. },
  40598. enumerable: true,
  40599. configurable: true
  40600. });
  40601. /**
  40602. * Resets performance monitor
  40603. */
  40604. PerformanceMonitor.prototype.reset = function () {
  40605. //clear last sample to avoid interpolating over the disabled period when next enabled
  40606. this._lastFrameTimeMs = null;
  40607. //wipe record
  40608. this._rollingFrameTime.reset();
  40609. };
  40610. return PerformanceMonitor;
  40611. }());
  40612. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40613. /**
  40614. * RollingAverage
  40615. *
  40616. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40617. */
  40618. var RollingAverage = /** @class */ (function () {
  40619. /**
  40620. * constructor
  40621. * @param length The number of samples required to saturate the sliding window
  40622. */
  40623. function RollingAverage(length) {
  40624. this._samples = new Array(length);
  40625. this.reset();
  40626. }
  40627. /**
  40628. * Adds a sample to the sample set
  40629. * @param v The sample value
  40630. */
  40631. RollingAverage.prototype.add = function (v) {
  40632. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40633. var delta;
  40634. //we need to check if we've already wrapped round
  40635. if (this.isSaturated()) {
  40636. //remove bottom of stack from mean
  40637. var bottomValue = this._samples[this._pos];
  40638. delta = bottomValue - this.average;
  40639. this.average -= delta / (this._sampleCount - 1);
  40640. this._m2 -= delta * (bottomValue - this.average);
  40641. }
  40642. else {
  40643. this._sampleCount++;
  40644. }
  40645. //add new value to mean
  40646. delta = v - this.average;
  40647. this.average += delta / (this._sampleCount);
  40648. this._m2 += delta * (v - this.average);
  40649. //set the new variance
  40650. this.variance = this._m2 / (this._sampleCount - 1);
  40651. this._samples[this._pos] = v;
  40652. this._pos++;
  40653. this._pos %= this._samples.length; //positive wrap around
  40654. };
  40655. /**
  40656. * Returns previously added values or null if outside of history or outside the sliding window domain
  40657. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40658. * @return Value previously recorded with add() or null if outside of range
  40659. */
  40660. RollingAverage.prototype.history = function (i) {
  40661. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40662. return 0;
  40663. }
  40664. var i0 = this._wrapPosition(this._pos - 1.0);
  40665. return this._samples[this._wrapPosition(i0 - i)];
  40666. };
  40667. /**
  40668. * Returns true if enough samples have been taken to completely fill the sliding window
  40669. * @return true if sample-set saturated
  40670. */
  40671. RollingAverage.prototype.isSaturated = function () {
  40672. return this._sampleCount >= this._samples.length;
  40673. };
  40674. /**
  40675. * Resets the rolling average (equivalent to 0 samples taken so far)
  40676. */
  40677. RollingAverage.prototype.reset = function () {
  40678. this.average = 0;
  40679. this.variance = 0;
  40680. this._sampleCount = 0;
  40681. this._pos = 0;
  40682. this._m2 = 0;
  40683. };
  40684. /**
  40685. * Wraps a value around the sample range boundaries
  40686. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40687. * @return Wrapped position in sample range
  40688. */
  40689. RollingAverage.prototype._wrapPosition = function (i) {
  40690. var max = this._samples.length;
  40691. return ((i % max) + max) % max;
  40692. };
  40693. return RollingAverage;
  40694. }());
  40695. BABYLON.RollingAverage = RollingAverage;
  40696. })(BABYLON || (BABYLON = {}));
  40697. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40698. var BABYLON;
  40699. (function (BABYLON) {
  40700. /**
  40701. * "Static Class" containing the most commonly used helper while dealing with material for
  40702. * rendering purpose.
  40703. *
  40704. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40705. *
  40706. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40707. */
  40708. var MaterialHelper = /** @class */ (function () {
  40709. function MaterialHelper() {
  40710. }
  40711. /**
  40712. * Bind the current view position to an effect.
  40713. * @param effect The effect to be bound
  40714. * @param scene The scene the eyes position is used from
  40715. */
  40716. MaterialHelper.BindEyePosition = function (effect, scene) {
  40717. if (scene._forcedViewPosition) {
  40718. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40719. return;
  40720. }
  40721. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40722. };
  40723. /**
  40724. * Helps preparing the defines values about the UVs in used in the effect.
  40725. * UVs are shared as much as we can accross chanels in the shaders.
  40726. * @param texture The texture we are preparing the UVs for
  40727. * @param defines The defines to update
  40728. * @param key The chanel key "diffuse", "specular"... used in the shader
  40729. */
  40730. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40731. defines._needUVs = true;
  40732. defines[key] = true;
  40733. if (texture.getTextureMatrix().isIdentity(true)) {
  40734. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40735. if (texture.coordinatesIndex === 0) {
  40736. defines["MAINUV1"] = true;
  40737. }
  40738. else {
  40739. defines["MAINUV2"] = true;
  40740. }
  40741. }
  40742. else {
  40743. defines[key + "DIRECTUV"] = 0;
  40744. }
  40745. };
  40746. /**
  40747. * Binds a texture matrix value to its corrsponding uniform
  40748. * @param texture The texture to bind the matrix for
  40749. * @param uniformBuffer The uniform buffer receivin the data
  40750. * @param key The chanel key "diffuse", "specular"... used in the shader
  40751. */
  40752. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40753. var matrix = texture.getTextureMatrix();
  40754. if (!matrix.isIdentity(true)) {
  40755. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40756. }
  40757. };
  40758. /**
  40759. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40760. * @param mesh defines the current mesh
  40761. * @param scene defines the current scene
  40762. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40763. * @param pointsCloud defines if point cloud rendering has to be turned on
  40764. * @param fogEnabled defines if fog has to be turned on
  40765. * @param alphaTest defines if alpha testing has to be turned on
  40766. * @param defines defines the current list of defines
  40767. */
  40768. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40769. if (defines._areMiscDirty) {
  40770. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40771. defines["POINTSIZE"] = pointsCloud;
  40772. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40773. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40774. defines["ALPHATEST"] = alphaTest;
  40775. }
  40776. };
  40777. /**
  40778. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40779. * @param scene defines the current scene
  40780. * @param engine defines the current engine
  40781. * @param defines specifies the list of active defines
  40782. * @param useInstances defines if instances have to be turned on
  40783. * @param useClipPlane defines if clip plane have to be turned on
  40784. */
  40785. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40786. if (useClipPlane === void 0) { useClipPlane = null; }
  40787. var changed = false;
  40788. var useClipPlane1 = false;
  40789. var useClipPlane2 = false;
  40790. var useClipPlane3 = false;
  40791. var useClipPlane4 = false;
  40792. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40793. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40794. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40795. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40796. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40797. defines["CLIPPLANE"] = useClipPlane1;
  40798. changed = true;
  40799. }
  40800. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40801. defines["CLIPPLANE2"] = useClipPlane2;
  40802. changed = true;
  40803. }
  40804. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40805. defines["CLIPPLANE3"] = useClipPlane3;
  40806. changed = true;
  40807. }
  40808. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40809. defines["CLIPPLANE4"] = useClipPlane4;
  40810. changed = true;
  40811. }
  40812. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40813. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40814. changed = true;
  40815. }
  40816. if (defines["INSTANCES"] !== useInstances) {
  40817. defines["INSTANCES"] = useInstances;
  40818. changed = true;
  40819. }
  40820. if (changed) {
  40821. defines.markAsUnprocessed();
  40822. }
  40823. };
  40824. /**
  40825. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40826. * @param mesh The mesh containing the geometry data we will draw
  40827. * @param defines The defines to update
  40828. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40829. * @param useBones Precise whether bones should be used or not (override mesh info)
  40830. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40831. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40832. * @returns false if defines are considered not dirty and have not been checked
  40833. */
  40834. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40835. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40836. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40837. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40838. return false;
  40839. }
  40840. defines._normals = defines._needNormals;
  40841. defines._uvs = defines._needUVs;
  40842. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40843. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40844. defines["TANGENT"] = true;
  40845. }
  40846. if (defines._needUVs) {
  40847. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40848. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40849. }
  40850. else {
  40851. defines["UV1"] = false;
  40852. defines["UV2"] = false;
  40853. }
  40854. if (useVertexColor) {
  40855. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40856. defines["VERTEXCOLOR"] = hasVertexColors;
  40857. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40858. }
  40859. if (useBones) {
  40860. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40861. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40862. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40863. }
  40864. else {
  40865. defines["NUM_BONE_INFLUENCERS"] = 0;
  40866. defines["BonesPerMesh"] = 0;
  40867. }
  40868. }
  40869. if (useMorphTargets) {
  40870. var manager = mesh.morphTargetManager;
  40871. if (manager) {
  40872. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40873. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40874. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40875. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40876. }
  40877. else {
  40878. defines["MORPHTARGETS_TANGENT"] = false;
  40879. defines["MORPHTARGETS_NORMAL"] = false;
  40880. defines["MORPHTARGETS"] = false;
  40881. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40882. }
  40883. }
  40884. return true;
  40885. };
  40886. /**
  40887. * Prepares the defines related to the light information passed in parameter
  40888. * @param scene The scene we are intending to draw
  40889. * @param mesh The mesh the effect is compiling for
  40890. * @param defines The defines to update
  40891. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40892. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40893. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40894. * @returns true if normals will be required for the rest of the effect
  40895. */
  40896. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40897. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40898. if (disableLighting === void 0) { disableLighting = false; }
  40899. if (!defines._areLightsDirty) {
  40900. return defines._needNormals;
  40901. }
  40902. var lightIndex = 0;
  40903. var needNormals = false;
  40904. var needRebuild = false;
  40905. var lightmapMode = false;
  40906. var shadowEnabled = false;
  40907. var specularEnabled = false;
  40908. if (scene.lightsEnabled && !disableLighting) {
  40909. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40910. var light = _a[_i];
  40911. needNormals = true;
  40912. if (defines["LIGHT" + lightIndex] === undefined) {
  40913. needRebuild = true;
  40914. }
  40915. defines["LIGHT" + lightIndex] = true;
  40916. defines["SPOTLIGHT" + lightIndex] = false;
  40917. defines["HEMILIGHT" + lightIndex] = false;
  40918. defines["POINTLIGHT" + lightIndex] = false;
  40919. defines["DIRLIGHT" + lightIndex] = false;
  40920. light.prepareLightSpecificDefines(defines, lightIndex);
  40921. // FallOff.
  40922. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40923. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40924. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40925. switch (light.falloffType) {
  40926. case BABYLON.Light.FALLOFF_GLTF:
  40927. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40928. break;
  40929. case BABYLON.Light.FALLOFF_PHYSICAL:
  40930. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40931. break;
  40932. case BABYLON.Light.FALLOFF_STANDARD:
  40933. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40934. break;
  40935. }
  40936. // Specular
  40937. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40938. specularEnabled = true;
  40939. }
  40940. // Shadows
  40941. defines["SHADOW" + lightIndex] = false;
  40942. defines["SHADOWPCF" + lightIndex] = false;
  40943. defines["SHADOWPCSS" + lightIndex] = false;
  40944. defines["SHADOWPOISSON" + lightIndex] = false;
  40945. defines["SHADOWESM" + lightIndex] = false;
  40946. defines["SHADOWCUBE" + lightIndex] = false;
  40947. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40948. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40949. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40950. var shadowGenerator = light.getShadowGenerator();
  40951. if (shadowGenerator) {
  40952. var shadowMap = shadowGenerator.getShadowMap();
  40953. if (shadowMap) {
  40954. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40955. shadowEnabled = true;
  40956. shadowGenerator.prepareDefines(defines, lightIndex);
  40957. }
  40958. }
  40959. }
  40960. }
  40961. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40962. lightmapMode = true;
  40963. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40964. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40965. }
  40966. else {
  40967. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40968. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40969. }
  40970. lightIndex++;
  40971. if (lightIndex === maxSimultaneousLights)
  40972. break;
  40973. }
  40974. }
  40975. defines["SPECULARTERM"] = specularEnabled;
  40976. defines["SHADOWS"] = shadowEnabled;
  40977. // Resetting all other lights if any
  40978. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40979. if (defines["LIGHT" + index] !== undefined) {
  40980. defines["LIGHT" + index] = false;
  40981. defines["HEMILIGHT" + lightIndex] = false;
  40982. defines["POINTLIGHT" + lightIndex] = false;
  40983. defines["DIRLIGHT" + lightIndex] = false;
  40984. defines["SPOTLIGHT" + lightIndex] = false;
  40985. defines["SHADOW" + lightIndex] = false;
  40986. }
  40987. }
  40988. var caps = scene.getEngine().getCaps();
  40989. if (defines["SHADOWFLOAT"] === undefined) {
  40990. needRebuild = true;
  40991. }
  40992. defines["SHADOWFLOAT"] = shadowEnabled &&
  40993. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40994. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40995. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40996. if (needRebuild) {
  40997. defines.rebuild();
  40998. }
  40999. return needNormals;
  41000. };
  41001. /**
  41002. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41003. * that won t be acctive due to defines being turned off.
  41004. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41005. * @param samplersList The samplers list
  41006. * @param defines The defines helping in the list generation
  41007. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41008. */
  41009. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41010. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41011. var uniformsList;
  41012. var uniformBuffersList = null;
  41013. if (uniformsListOrOptions.uniformsNames) {
  41014. var options = uniformsListOrOptions;
  41015. uniformsList = options.uniformsNames;
  41016. uniformBuffersList = options.uniformBuffersNames;
  41017. samplersList = options.samplers;
  41018. defines = options.defines;
  41019. maxSimultaneousLights = options.maxSimultaneousLights;
  41020. }
  41021. else {
  41022. uniformsList = uniformsListOrOptions;
  41023. if (!samplersList) {
  41024. samplersList = [];
  41025. }
  41026. }
  41027. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41028. if (!defines["LIGHT" + lightIndex]) {
  41029. break;
  41030. }
  41031. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41032. if (uniformBuffersList) {
  41033. uniformBuffersList.push("Light" + lightIndex);
  41034. }
  41035. samplersList.push("shadowSampler" + lightIndex);
  41036. samplersList.push("depthSampler" + lightIndex);
  41037. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41038. samplersList.push("projectionLightSampler" + lightIndex);
  41039. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41040. }
  41041. }
  41042. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41043. uniformsList.push("morphTargetInfluences");
  41044. }
  41045. };
  41046. /**
  41047. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41048. * @param defines The defines to update while falling back
  41049. * @param fallbacks The authorized effect fallbacks
  41050. * @param maxSimultaneousLights The maximum number of lights allowed
  41051. * @param rank the current rank of the Effect
  41052. * @returns The newly affected rank
  41053. */
  41054. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41055. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41056. if (rank === void 0) { rank = 0; }
  41057. var lightFallbackRank = 0;
  41058. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41059. if (!defines["LIGHT" + lightIndex]) {
  41060. break;
  41061. }
  41062. if (lightIndex > 0) {
  41063. lightFallbackRank = rank + lightIndex;
  41064. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41065. }
  41066. if (!defines["SHADOWS"]) {
  41067. if (defines["SHADOW" + lightIndex]) {
  41068. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41069. }
  41070. if (defines["SHADOWPCF" + lightIndex]) {
  41071. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41072. }
  41073. if (defines["SHADOWPCSS" + lightIndex]) {
  41074. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41075. }
  41076. if (defines["SHADOWPOISSON" + lightIndex]) {
  41077. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41078. }
  41079. if (defines["SHADOWESM" + lightIndex]) {
  41080. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41081. }
  41082. }
  41083. }
  41084. return lightFallbackRank++;
  41085. };
  41086. /**
  41087. * Prepares the list of attributes required for morph targets according to the effect defines.
  41088. * @param attribs The current list of supported attribs
  41089. * @param mesh The mesh to prepare the morph targets attributes for
  41090. * @param defines The current Defines of the effect
  41091. */
  41092. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41093. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41094. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41095. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41096. var manager = mesh.morphTargetManager;
  41097. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41098. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41099. for (var index = 0; index < influencers; index++) {
  41100. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41101. if (normal) {
  41102. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41103. }
  41104. if (tangent) {
  41105. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41106. }
  41107. if (attribs.length > maxAttributesCount) {
  41108. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41109. }
  41110. }
  41111. }
  41112. };
  41113. /**
  41114. * Prepares the list of attributes required for bones according to the effect defines.
  41115. * @param attribs The current list of supported attribs
  41116. * @param mesh The mesh to prepare the bones attributes for
  41117. * @param defines The current Defines of the effect
  41118. * @param fallbacks The current efffect fallback strategy
  41119. */
  41120. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41121. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41122. fallbacks.addCPUSkinningFallback(0, mesh);
  41123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41125. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41126. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41127. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41128. }
  41129. }
  41130. };
  41131. /**
  41132. * Prepares the list of attributes required for instances according to the effect defines.
  41133. * @param attribs The current list of supported attribs
  41134. * @param defines The current Defines of the effect
  41135. */
  41136. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41137. if (defines["INSTANCES"]) {
  41138. attribs.push("world0");
  41139. attribs.push("world1");
  41140. attribs.push("world2");
  41141. attribs.push("world3");
  41142. }
  41143. };
  41144. /**
  41145. * Binds the light shadow information to the effect for the given mesh.
  41146. * @param light The light containing the generator
  41147. * @param scene The scene the lights belongs to
  41148. * @param mesh The mesh we are binding the information to render
  41149. * @param lightIndex The light index in the effect used to render the mesh
  41150. * @param effect The effect we are binding the data to
  41151. */
  41152. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41153. if (light.shadowEnabled && mesh.receiveShadows) {
  41154. var shadowGenerator = light.getShadowGenerator();
  41155. if (shadowGenerator) {
  41156. shadowGenerator.bindShadowLight(lightIndex, effect);
  41157. }
  41158. }
  41159. };
  41160. /**
  41161. * Binds the light information to the effect.
  41162. * @param light The light containing the generator
  41163. * @param effect The effect we are binding the data to
  41164. * @param lightIndex The light index in the effect used to render
  41165. */
  41166. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41167. light.transferToEffect(effect, lightIndex + "");
  41168. };
  41169. /**
  41170. * Binds the lights information from the scene to the effect for the given mesh.
  41171. * @param scene The scene the lights belongs to
  41172. * @param mesh The mesh we are binding the information to render
  41173. * @param effect The effect we are binding the data to
  41174. * @param defines The generated defines for the effect
  41175. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41176. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41177. */
  41178. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41179. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41180. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41181. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41182. for (var i = 0; i < len; i++) {
  41183. var light = mesh._lightSources[i];
  41184. var iAsString = i.toString();
  41185. var scaledIntensity = light.getScaledIntensity();
  41186. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41187. MaterialHelper.BindLightProperties(light, effect, i);
  41188. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41189. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41190. if (defines["SPECULARTERM"]) {
  41191. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41192. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41193. }
  41194. // Shadows
  41195. if (scene.shadowsEnabled) {
  41196. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41197. }
  41198. light._uniformBuffer.update();
  41199. }
  41200. };
  41201. /**
  41202. * Binds the fog information from the scene to the effect for the given mesh.
  41203. * @param scene The scene the lights belongs to
  41204. * @param mesh The mesh we are binding the information to render
  41205. * @param effect The effect we are binding the data to
  41206. */
  41207. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41208. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41209. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41210. effect.setColor3("vFogColor", scene.fogColor);
  41211. }
  41212. };
  41213. /**
  41214. * Binds the bones information from the mesh to the effect.
  41215. * @param mesh The mesh we are binding the information to render
  41216. * @param effect The effect we are binding the data to
  41217. */
  41218. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41219. if (!effect || !mesh) {
  41220. return;
  41221. }
  41222. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41223. mesh.computeBonesUsingShaders = false;
  41224. }
  41225. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41226. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41227. if (matrices) {
  41228. effect.setMatrices("mBones", matrices);
  41229. }
  41230. }
  41231. };
  41232. /**
  41233. * Binds the morph targets information from the mesh to the effect.
  41234. * @param abstractMesh The mesh we are binding the information to render
  41235. * @param effect The effect we are binding the data to
  41236. */
  41237. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41238. var manager = abstractMesh.morphTargetManager;
  41239. if (!abstractMesh || !manager) {
  41240. return;
  41241. }
  41242. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41243. };
  41244. /**
  41245. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41246. * @param defines The generated defines used in the effect
  41247. * @param effect The effect we are binding the data to
  41248. * @param scene The scene we are willing to render with logarithmic scale for
  41249. */
  41250. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41251. if (defines["LOGARITHMICDEPTH"]) {
  41252. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41253. }
  41254. };
  41255. /**
  41256. * Binds the clip plane information from the scene to the effect.
  41257. * @param scene The scene the clip plane information are extracted from
  41258. * @param effect The effect we are binding the data to
  41259. */
  41260. MaterialHelper.BindClipPlane = function (effect, scene) {
  41261. if (scene.clipPlane) {
  41262. var clipPlane = scene.clipPlane;
  41263. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41264. }
  41265. if (scene.clipPlane2) {
  41266. var clipPlane = scene.clipPlane2;
  41267. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41268. }
  41269. if (scene.clipPlane3) {
  41270. var clipPlane = scene.clipPlane3;
  41271. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41272. }
  41273. if (scene.clipPlane4) {
  41274. var clipPlane = scene.clipPlane4;
  41275. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41276. }
  41277. };
  41278. return MaterialHelper;
  41279. }());
  41280. BABYLON.MaterialHelper = MaterialHelper;
  41281. })(BABYLON || (BABYLON = {}));
  41282. //# sourceMappingURL=babylon.materialHelper.js.map
  41283. var BABYLON;
  41284. (function (BABYLON) {
  41285. var PushMaterial = /** @class */ (function (_super) {
  41286. __extends(PushMaterial, _super);
  41287. function PushMaterial(name, scene) {
  41288. var _this = _super.call(this, name, scene) || this;
  41289. _this._normalMatrix = new BABYLON.Matrix();
  41290. _this.storeEffectOnSubMeshes = true;
  41291. return _this;
  41292. }
  41293. PushMaterial.prototype.getEffect = function () {
  41294. return this._activeEffect;
  41295. };
  41296. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41297. if (!mesh) {
  41298. return false;
  41299. }
  41300. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41301. return true;
  41302. }
  41303. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41304. };
  41305. /**
  41306. * Binds the given world matrix to the active effect
  41307. *
  41308. * @param world the matrix to bind
  41309. */
  41310. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41311. this._activeEffect.setMatrix("world", world);
  41312. };
  41313. /**
  41314. * Binds the given normal matrix to the active effect
  41315. *
  41316. * @param normalMatrix the matrix to bind
  41317. */
  41318. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41319. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41320. };
  41321. PushMaterial.prototype.bind = function (world, mesh) {
  41322. if (!mesh) {
  41323. return;
  41324. }
  41325. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41326. };
  41327. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41328. if (effect === void 0) { effect = null; }
  41329. _super.prototype._afterBind.call(this, mesh);
  41330. this.getScene()._cachedEffect = effect;
  41331. };
  41332. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41333. if (visibility === void 0) { visibility = 1; }
  41334. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41335. };
  41336. return PushMaterial;
  41337. }(BABYLON.Material));
  41338. BABYLON.PushMaterial = PushMaterial;
  41339. })(BABYLON || (BABYLON = {}));
  41340. //# sourceMappingURL=babylon.pushMaterial.js.map
  41341. var BABYLON;
  41342. (function (BABYLON) {
  41343. /** @hidden */
  41344. var StandardMaterialDefines = /** @class */ (function (_super) {
  41345. __extends(StandardMaterialDefines, _super);
  41346. function StandardMaterialDefines() {
  41347. var _this = _super.call(this) || this;
  41348. _this.MAINUV1 = false;
  41349. _this.MAINUV2 = false;
  41350. _this.DIFFUSE = false;
  41351. _this.DIFFUSEDIRECTUV = 0;
  41352. _this.AMBIENT = false;
  41353. _this.AMBIENTDIRECTUV = 0;
  41354. _this.OPACITY = false;
  41355. _this.OPACITYDIRECTUV = 0;
  41356. _this.OPACITYRGB = false;
  41357. _this.REFLECTION = false;
  41358. _this.EMISSIVE = false;
  41359. _this.EMISSIVEDIRECTUV = 0;
  41360. _this.SPECULAR = false;
  41361. _this.SPECULARDIRECTUV = 0;
  41362. _this.BUMP = false;
  41363. _this.BUMPDIRECTUV = 0;
  41364. _this.PARALLAX = false;
  41365. _this.PARALLAXOCCLUSION = false;
  41366. _this.SPECULAROVERALPHA = false;
  41367. _this.CLIPPLANE = false;
  41368. _this.CLIPPLANE2 = false;
  41369. _this.CLIPPLANE3 = false;
  41370. _this.CLIPPLANE4 = false;
  41371. _this.ALPHATEST = false;
  41372. _this.DEPTHPREPASS = false;
  41373. _this.ALPHAFROMDIFFUSE = false;
  41374. _this.POINTSIZE = false;
  41375. _this.FOG = false;
  41376. _this.SPECULARTERM = false;
  41377. _this.DIFFUSEFRESNEL = false;
  41378. _this.OPACITYFRESNEL = false;
  41379. _this.REFLECTIONFRESNEL = false;
  41380. _this.REFRACTIONFRESNEL = false;
  41381. _this.EMISSIVEFRESNEL = false;
  41382. _this.FRESNEL = false;
  41383. _this.NORMAL = false;
  41384. _this.UV1 = false;
  41385. _this.UV2 = false;
  41386. _this.VERTEXCOLOR = false;
  41387. _this.VERTEXALPHA = false;
  41388. _this.NUM_BONE_INFLUENCERS = 0;
  41389. _this.BonesPerMesh = 0;
  41390. _this.INSTANCES = false;
  41391. _this.GLOSSINESS = false;
  41392. _this.ROUGHNESS = false;
  41393. _this.EMISSIVEASILLUMINATION = false;
  41394. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41395. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41396. _this.LIGHTMAP = false;
  41397. _this.LIGHTMAPDIRECTUV = 0;
  41398. _this.OBJECTSPACE_NORMALMAP = false;
  41399. _this.USELIGHTMAPASSHADOWMAP = false;
  41400. _this.REFLECTIONMAP_3D = false;
  41401. _this.REFLECTIONMAP_SPHERICAL = false;
  41402. _this.REFLECTIONMAP_PLANAR = false;
  41403. _this.REFLECTIONMAP_CUBIC = false;
  41404. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41405. _this.REFLECTIONMAP_PROJECTION = false;
  41406. _this.REFLECTIONMAP_SKYBOX = false;
  41407. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41408. _this.REFLECTIONMAP_EXPLICIT = false;
  41409. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41410. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41411. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41412. _this.INVERTCUBICMAP = false;
  41413. _this.LOGARITHMICDEPTH = false;
  41414. _this.REFRACTION = false;
  41415. _this.REFRACTIONMAP_3D = false;
  41416. _this.REFLECTIONOVERALPHA = false;
  41417. _this.TWOSIDEDLIGHTING = false;
  41418. _this.SHADOWFLOAT = false;
  41419. _this.MORPHTARGETS = false;
  41420. _this.MORPHTARGETS_NORMAL = false;
  41421. _this.MORPHTARGETS_TANGENT = false;
  41422. _this.NUM_MORPH_INFLUENCERS = 0;
  41423. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41424. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41425. _this.IMAGEPROCESSING = false;
  41426. _this.VIGNETTE = false;
  41427. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41428. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41429. _this.TONEMAPPING = false;
  41430. _this.TONEMAPPING_ACES = false;
  41431. _this.CONTRAST = false;
  41432. _this.COLORCURVES = false;
  41433. _this.COLORGRADING = false;
  41434. _this.COLORGRADING3D = false;
  41435. _this.SAMPLER3DGREENDEPTH = false;
  41436. _this.SAMPLER3DBGRMAP = false;
  41437. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41438. /**
  41439. * If the reflection texture on this material is in linear color space
  41440. * @hidden
  41441. */
  41442. _this.IS_REFLECTION_LINEAR = false;
  41443. /**
  41444. * If the refraction texture on this material is in linear color space
  41445. * @hidden
  41446. */
  41447. _this.IS_REFRACTION_LINEAR = false;
  41448. _this.EXPOSURE = false;
  41449. _this.rebuild();
  41450. return _this;
  41451. }
  41452. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41453. var modes = [
  41454. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41455. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41456. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41457. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41458. ];
  41459. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41460. var mode = modes_1[_i];
  41461. this[mode] = (mode === modeToEnable);
  41462. }
  41463. };
  41464. return StandardMaterialDefines;
  41465. }(BABYLON.MaterialDefines));
  41466. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41467. var StandardMaterial = /** @class */ (function (_super) {
  41468. __extends(StandardMaterial, _super);
  41469. function StandardMaterial(name, scene) {
  41470. var _this = _super.call(this, name, scene) || this;
  41471. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41472. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41473. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41474. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41475. _this.specularPower = 64;
  41476. _this._useAlphaFromDiffuseTexture = false;
  41477. _this._useEmissiveAsIllumination = false;
  41478. _this._linkEmissiveWithDiffuse = false;
  41479. _this._useSpecularOverAlpha = false;
  41480. _this._useReflectionOverAlpha = false;
  41481. _this._disableLighting = false;
  41482. _this._useObjectSpaceNormalMap = false;
  41483. _this._useParallax = false;
  41484. _this._useParallaxOcclusion = false;
  41485. _this.parallaxScaleBias = 0.05;
  41486. _this._roughness = 0;
  41487. _this.indexOfRefraction = 0.98;
  41488. _this.invertRefractionY = true;
  41489. /**
  41490. * Defines the alpha limits in alpha test mode
  41491. */
  41492. _this.alphaCutOff = 0.4;
  41493. _this._useLightmapAsShadowmap = false;
  41494. _this._useReflectionFresnelFromSpecular = false;
  41495. _this._useGlossinessFromSpecularMapAlpha = false;
  41496. _this._maxSimultaneousLights = 4;
  41497. /**
  41498. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41499. */
  41500. _this._invertNormalMapX = false;
  41501. /**
  41502. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41503. */
  41504. _this._invertNormalMapY = false;
  41505. /**
  41506. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41507. */
  41508. _this._twoSidedLighting = false;
  41509. _this._renderTargets = new BABYLON.SmartArray(16);
  41510. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41511. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41512. // Setup the default processing configuration to the scene.
  41513. _this._attachImageProcessingConfiguration(null);
  41514. _this.getRenderTargetTextures = function () {
  41515. _this._renderTargets.reset();
  41516. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41517. _this._renderTargets.push(_this._reflectionTexture);
  41518. }
  41519. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41520. _this._renderTargets.push(_this._refractionTexture);
  41521. }
  41522. return _this._renderTargets;
  41523. };
  41524. return _this;
  41525. }
  41526. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41527. /**
  41528. * Gets the image processing configuration used either in this material.
  41529. */
  41530. get: function () {
  41531. return this._imageProcessingConfiguration;
  41532. },
  41533. /**
  41534. * Sets the Default image processing configuration used either in the this material.
  41535. *
  41536. * If sets to null, the scene one is in use.
  41537. */
  41538. set: function (value) {
  41539. this._attachImageProcessingConfiguration(value);
  41540. // Ensure the effect will be rebuilt.
  41541. this._markAllSubMeshesAsTexturesDirty();
  41542. },
  41543. enumerable: true,
  41544. configurable: true
  41545. });
  41546. /**
  41547. * Attaches a new image processing configuration to the Standard Material.
  41548. * @param configuration
  41549. */
  41550. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41551. var _this = this;
  41552. if (configuration === this._imageProcessingConfiguration) {
  41553. return;
  41554. }
  41555. // Detaches observer.
  41556. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41557. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41558. }
  41559. // Pick the scene configuration if needed.
  41560. if (!configuration) {
  41561. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41562. }
  41563. else {
  41564. this._imageProcessingConfiguration = configuration;
  41565. }
  41566. // Attaches observer.
  41567. if (this._imageProcessingConfiguration) {
  41568. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41569. _this._markAllSubMeshesAsImageProcessingDirty();
  41570. });
  41571. }
  41572. };
  41573. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41574. /**
  41575. * Gets wether the color curves effect is enabled.
  41576. */
  41577. get: function () {
  41578. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41579. },
  41580. /**
  41581. * Sets wether the color curves effect is enabled.
  41582. */
  41583. set: function (value) {
  41584. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41585. },
  41586. enumerable: true,
  41587. configurable: true
  41588. });
  41589. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41590. /**
  41591. * Gets wether the color grading effect is enabled.
  41592. */
  41593. get: function () {
  41594. return this.imageProcessingConfiguration.colorGradingEnabled;
  41595. },
  41596. /**
  41597. * Gets wether the color grading effect is enabled.
  41598. */
  41599. set: function (value) {
  41600. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41601. },
  41602. enumerable: true,
  41603. configurable: true
  41604. });
  41605. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41606. /**
  41607. * Gets wether tonemapping is enabled or not.
  41608. */
  41609. get: function () {
  41610. return this._imageProcessingConfiguration.toneMappingEnabled;
  41611. },
  41612. /**
  41613. * Sets wether tonemapping is enabled or not
  41614. */
  41615. set: function (value) {
  41616. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41617. },
  41618. enumerable: true,
  41619. configurable: true
  41620. });
  41621. ;
  41622. ;
  41623. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41624. /**
  41625. * The camera exposure used on this material.
  41626. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41627. * This corresponds to a photographic exposure.
  41628. */
  41629. get: function () {
  41630. return this._imageProcessingConfiguration.exposure;
  41631. },
  41632. /**
  41633. * The camera exposure used on this material.
  41634. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41635. * This corresponds to a photographic exposure.
  41636. */
  41637. set: function (value) {
  41638. this._imageProcessingConfiguration.exposure = value;
  41639. },
  41640. enumerable: true,
  41641. configurable: true
  41642. });
  41643. ;
  41644. ;
  41645. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41646. /**
  41647. * Gets The camera contrast used on this material.
  41648. */
  41649. get: function () {
  41650. return this._imageProcessingConfiguration.contrast;
  41651. },
  41652. /**
  41653. * Sets The camera contrast used on this material.
  41654. */
  41655. set: function (value) {
  41656. this._imageProcessingConfiguration.contrast = value;
  41657. },
  41658. enumerable: true,
  41659. configurable: true
  41660. });
  41661. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41662. /**
  41663. * Gets the Color Grading 2D Lookup Texture.
  41664. */
  41665. get: function () {
  41666. return this._imageProcessingConfiguration.colorGradingTexture;
  41667. },
  41668. /**
  41669. * Sets the Color Grading 2D Lookup Texture.
  41670. */
  41671. set: function (value) {
  41672. this._imageProcessingConfiguration.colorGradingTexture = value;
  41673. },
  41674. enumerable: true,
  41675. configurable: true
  41676. });
  41677. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41678. /**
  41679. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41680. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41681. * 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;
  41682. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41683. */
  41684. get: function () {
  41685. return this._imageProcessingConfiguration.colorCurves;
  41686. },
  41687. /**
  41688. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41689. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41690. * 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;
  41691. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41692. */
  41693. set: function (value) {
  41694. this._imageProcessingConfiguration.colorCurves = value;
  41695. },
  41696. enumerable: true,
  41697. configurable: true
  41698. });
  41699. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41700. /**
  41701. * Gets a boolean indicating that current material needs to register RTT
  41702. */
  41703. get: function () {
  41704. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41705. return true;
  41706. }
  41707. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41708. return true;
  41709. }
  41710. return false;
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. StandardMaterial.prototype.getClassName = function () {
  41716. return "StandardMaterial";
  41717. };
  41718. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41719. get: function () {
  41720. return this._useLogarithmicDepth;
  41721. },
  41722. set: function (value) {
  41723. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41724. this._markAllSubMeshesAsMiscDirty();
  41725. },
  41726. enumerable: true,
  41727. configurable: true
  41728. });
  41729. StandardMaterial.prototype.needAlphaBlending = function () {
  41730. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41731. };
  41732. StandardMaterial.prototype.needAlphaTesting = function () {
  41733. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41734. };
  41735. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41736. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41737. };
  41738. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41739. return this._diffuseTexture;
  41740. };
  41741. /**
  41742. * Child classes can use it to update shaders
  41743. */
  41744. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41745. if (useInstances === void 0) { useInstances = false; }
  41746. if (subMesh.effect && this.isFrozen) {
  41747. if (this._wasPreviouslyReady) {
  41748. return true;
  41749. }
  41750. }
  41751. if (!subMesh._materialDefines) {
  41752. subMesh._materialDefines = new StandardMaterialDefines();
  41753. }
  41754. var scene = this.getScene();
  41755. var defines = subMesh._materialDefines;
  41756. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41757. if (defines._renderId === scene.getRenderId()) {
  41758. return true;
  41759. }
  41760. }
  41761. var engine = scene.getEngine();
  41762. // Lights
  41763. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41764. // Textures
  41765. if (defines._areTexturesDirty) {
  41766. defines._needUVs = false;
  41767. defines.MAINUV1 = false;
  41768. defines.MAINUV2 = false;
  41769. if (scene.texturesEnabled) {
  41770. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41771. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41772. return false;
  41773. }
  41774. else {
  41775. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41776. }
  41777. }
  41778. else {
  41779. defines.DIFFUSE = false;
  41780. }
  41781. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41782. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41783. return false;
  41784. }
  41785. else {
  41786. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41787. }
  41788. }
  41789. else {
  41790. defines.AMBIENT = false;
  41791. }
  41792. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41793. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41794. return false;
  41795. }
  41796. else {
  41797. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41798. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41799. }
  41800. }
  41801. else {
  41802. defines.OPACITY = false;
  41803. }
  41804. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41805. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41806. return false;
  41807. }
  41808. else {
  41809. defines._needNormals = true;
  41810. defines.REFLECTION = true;
  41811. defines.ROUGHNESS = (this._roughness > 0);
  41812. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41813. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41814. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41815. switch (this._reflectionTexture.coordinatesMode) {
  41816. case BABYLON.Texture.EXPLICIT_MODE:
  41817. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41818. break;
  41819. case BABYLON.Texture.PLANAR_MODE:
  41820. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41821. break;
  41822. case BABYLON.Texture.PROJECTION_MODE:
  41823. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41824. break;
  41825. case BABYLON.Texture.SKYBOX_MODE:
  41826. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41827. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41828. break;
  41829. case BABYLON.Texture.SPHERICAL_MODE:
  41830. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41831. break;
  41832. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41833. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41834. break;
  41835. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41836. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41837. break;
  41838. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41839. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41840. break;
  41841. case BABYLON.Texture.CUBIC_MODE:
  41842. case BABYLON.Texture.INVCUBIC_MODE:
  41843. default:
  41844. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41845. break;
  41846. }
  41847. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41848. }
  41849. }
  41850. else {
  41851. defines.REFLECTION = false;
  41852. }
  41853. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41854. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41855. return false;
  41856. }
  41857. else {
  41858. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41859. }
  41860. }
  41861. else {
  41862. defines.EMISSIVE = false;
  41863. }
  41864. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41865. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41866. return false;
  41867. }
  41868. else {
  41869. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41870. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41871. }
  41872. }
  41873. else {
  41874. defines.LIGHTMAP = false;
  41875. }
  41876. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41877. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41878. return false;
  41879. }
  41880. else {
  41881. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41882. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41883. }
  41884. }
  41885. else {
  41886. defines.SPECULAR = false;
  41887. }
  41888. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41889. // Bump texure can not be not blocking.
  41890. if (!this._bumpTexture.isReady()) {
  41891. return false;
  41892. }
  41893. else {
  41894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41895. defines.PARALLAX = this._useParallax;
  41896. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41897. }
  41898. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41899. }
  41900. else {
  41901. defines.BUMP = false;
  41902. }
  41903. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41904. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41905. return false;
  41906. }
  41907. else {
  41908. defines._needUVs = true;
  41909. defines.REFRACTION = true;
  41910. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41911. }
  41912. }
  41913. else {
  41914. defines.REFRACTION = false;
  41915. }
  41916. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41917. }
  41918. else {
  41919. defines.DIFFUSE = false;
  41920. defines.AMBIENT = false;
  41921. defines.OPACITY = false;
  41922. defines.REFLECTION = false;
  41923. defines.EMISSIVE = false;
  41924. defines.LIGHTMAP = false;
  41925. defines.BUMP = false;
  41926. defines.REFRACTION = false;
  41927. }
  41928. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41929. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41930. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41931. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41932. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41933. }
  41934. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41935. if (!this._imageProcessingConfiguration.isReady()) {
  41936. return false;
  41937. }
  41938. this._imageProcessingConfiguration.prepareDefines(defines);
  41939. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41940. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41941. }
  41942. if (defines._areFresnelDirty) {
  41943. if (StandardMaterial.FresnelEnabled) {
  41944. // Fresnel
  41945. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41946. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41947. this._reflectionFresnelParameters) {
  41948. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41949. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41950. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41951. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41952. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41953. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41954. defines._needNormals = true;
  41955. defines.FRESNEL = true;
  41956. }
  41957. }
  41958. else {
  41959. defines.FRESNEL = false;
  41960. }
  41961. }
  41962. // Misc.
  41963. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41964. // Attribs
  41965. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41966. // Values that need to be evaluated on every frame
  41967. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41968. // Get correct effect
  41969. if (defines.isDirty) {
  41970. defines.markAsProcessed();
  41971. scene.resetCachedMaterial();
  41972. // Fallbacks
  41973. var fallbacks = new BABYLON.EffectFallbacks();
  41974. if (defines.REFLECTION) {
  41975. fallbacks.addFallback(0, "REFLECTION");
  41976. }
  41977. if (defines.SPECULAR) {
  41978. fallbacks.addFallback(0, "SPECULAR");
  41979. }
  41980. if (defines.BUMP) {
  41981. fallbacks.addFallback(0, "BUMP");
  41982. }
  41983. if (defines.PARALLAX) {
  41984. fallbacks.addFallback(1, "PARALLAX");
  41985. }
  41986. if (defines.PARALLAXOCCLUSION) {
  41987. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41988. }
  41989. if (defines.SPECULAROVERALPHA) {
  41990. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41991. }
  41992. if (defines.FOG) {
  41993. fallbacks.addFallback(1, "FOG");
  41994. }
  41995. if (defines.POINTSIZE) {
  41996. fallbacks.addFallback(0, "POINTSIZE");
  41997. }
  41998. if (defines.LOGARITHMICDEPTH) {
  41999. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42000. }
  42001. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42002. if (defines.SPECULARTERM) {
  42003. fallbacks.addFallback(0, "SPECULARTERM");
  42004. }
  42005. if (defines.DIFFUSEFRESNEL) {
  42006. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42007. }
  42008. if (defines.OPACITYFRESNEL) {
  42009. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42010. }
  42011. if (defines.REFLECTIONFRESNEL) {
  42012. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42013. }
  42014. if (defines.EMISSIVEFRESNEL) {
  42015. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42016. }
  42017. if (defines.FRESNEL) {
  42018. fallbacks.addFallback(4, "FRESNEL");
  42019. }
  42020. //Attributes
  42021. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42022. if (defines.NORMAL) {
  42023. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42024. }
  42025. if (defines.UV1) {
  42026. attribs.push(BABYLON.VertexBuffer.UVKind);
  42027. }
  42028. if (defines.UV2) {
  42029. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42030. }
  42031. if (defines.VERTEXCOLOR) {
  42032. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42033. }
  42034. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42035. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42036. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42037. var shaderName = "default";
  42038. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42039. "vFogInfos", "vFogColor", "pointSize",
  42040. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42041. "mBones",
  42042. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42043. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42044. "vReflectionPosition", "vReflectionSize",
  42045. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42046. ];
  42047. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42048. var uniformBuffers = ["Material", "Scene"];
  42049. if (BABYLON.ImageProcessingConfiguration) {
  42050. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42051. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42052. }
  42053. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42054. uniformsNames: uniforms,
  42055. uniformBuffersNames: uniformBuffers,
  42056. samplers: samplers,
  42057. defines: defines,
  42058. maxSimultaneousLights: this._maxSimultaneousLights
  42059. });
  42060. if (this.customShaderNameResolve) {
  42061. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42062. }
  42063. var join = defines.toString();
  42064. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42065. attributes: attribs,
  42066. uniformsNames: uniforms,
  42067. uniformBuffersNames: uniformBuffers,
  42068. samplers: samplers,
  42069. defines: join,
  42070. fallbacks: fallbacks,
  42071. onCompiled: this.onCompiled,
  42072. onError: this.onError,
  42073. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42074. }, engine), defines);
  42075. this.buildUniformLayout();
  42076. }
  42077. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42078. return false;
  42079. }
  42080. defines._renderId = scene.getRenderId();
  42081. this._wasPreviouslyReady = true;
  42082. return true;
  42083. };
  42084. StandardMaterial.prototype.buildUniformLayout = function () {
  42085. // Order is important !
  42086. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42087. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42088. this._uniformBuffer.addUniform("opacityParts", 4);
  42089. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42090. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42091. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42092. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42093. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42094. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42095. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42096. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42097. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42098. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42099. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42100. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42101. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42102. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42103. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42104. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42105. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42106. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42107. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42108. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42109. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42110. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42111. this._uniformBuffer.addUniform("specularMatrix", 16);
  42112. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42113. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42114. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42115. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42116. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42117. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42118. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42119. this._uniformBuffer.addUniform("pointSize", 1);
  42120. this._uniformBuffer.create();
  42121. };
  42122. StandardMaterial.prototype.unbind = function () {
  42123. if (this._activeEffect) {
  42124. var needFlag = false;
  42125. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42126. this._activeEffect.setTexture("reflection2DSampler", null);
  42127. needFlag = true;
  42128. }
  42129. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42130. this._activeEffect.setTexture("refraction2DSampler", null);
  42131. needFlag = true;
  42132. }
  42133. if (needFlag) {
  42134. this._markAllSubMeshesAsTexturesDirty();
  42135. }
  42136. }
  42137. _super.prototype.unbind.call(this);
  42138. };
  42139. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42140. var scene = this.getScene();
  42141. var defines = subMesh._materialDefines;
  42142. if (!defines) {
  42143. return;
  42144. }
  42145. var effect = subMesh.effect;
  42146. if (!effect) {
  42147. return;
  42148. }
  42149. this._activeEffect = effect;
  42150. // Matrices
  42151. this.bindOnlyWorldMatrix(world);
  42152. // Normal Matrix
  42153. if (defines.OBJECTSPACE_NORMALMAP) {
  42154. world.toNormalMatrix(this._normalMatrix);
  42155. this.bindOnlyNormalMatrix(this._normalMatrix);
  42156. }
  42157. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42158. // Bones
  42159. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42160. if (mustRebind) {
  42161. this._uniformBuffer.bindToEffect(effect, "Material");
  42162. this.bindViewProjection(effect);
  42163. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42164. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42165. // Fresnel
  42166. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42167. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42168. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42169. }
  42170. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42171. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42172. }
  42173. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42174. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42175. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42176. }
  42177. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42178. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42179. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42180. }
  42181. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42182. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42183. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42184. }
  42185. }
  42186. // Textures
  42187. if (scene.texturesEnabled) {
  42188. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42189. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42190. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42191. if (this._diffuseTexture.hasAlpha) {
  42192. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42193. }
  42194. }
  42195. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42196. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42197. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42198. }
  42199. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42200. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42201. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42202. }
  42203. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42204. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42205. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42206. if (this._reflectionTexture.boundingBoxSize) {
  42207. var cubeTexture = this._reflectionTexture;
  42208. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42209. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42210. }
  42211. }
  42212. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42213. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42214. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42215. }
  42216. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42217. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42218. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42219. }
  42220. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42221. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42222. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42223. }
  42224. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42225. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42226. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42227. if (scene._mirroredCameraPosition) {
  42228. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42229. }
  42230. else {
  42231. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42232. }
  42233. }
  42234. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42235. var depth = 1.0;
  42236. if (!this._refractionTexture.isCube) {
  42237. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42238. if (this._refractionTexture.depth) {
  42239. depth = this._refractionTexture.depth;
  42240. }
  42241. }
  42242. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42243. }
  42244. }
  42245. // Point size
  42246. if (this.pointsCloud) {
  42247. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42248. }
  42249. if (defines.SPECULARTERM) {
  42250. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42251. }
  42252. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42253. // Diffuse
  42254. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42255. }
  42256. // Textures
  42257. if (scene.texturesEnabled) {
  42258. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42259. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42260. }
  42261. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42262. effect.setTexture("ambientSampler", this._ambientTexture);
  42263. }
  42264. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42265. effect.setTexture("opacitySampler", this._opacityTexture);
  42266. }
  42267. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42268. if (this._reflectionTexture.isCube) {
  42269. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42270. }
  42271. else {
  42272. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42273. }
  42274. }
  42275. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42276. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42277. }
  42278. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42279. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42280. }
  42281. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42282. effect.setTexture("specularSampler", this._specularTexture);
  42283. }
  42284. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42285. effect.setTexture("bumpSampler", this._bumpTexture);
  42286. }
  42287. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42288. var depth = 1.0;
  42289. if (this._refractionTexture.isCube) {
  42290. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42291. }
  42292. else {
  42293. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42294. }
  42295. }
  42296. }
  42297. // Clip plane
  42298. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42299. // Colors
  42300. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42301. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42302. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42303. }
  42304. if (mustRebind || !this.isFrozen) {
  42305. // Lights
  42306. if (scene.lightsEnabled && !this._disableLighting) {
  42307. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42308. }
  42309. // View
  42310. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42311. this.bindView(effect);
  42312. }
  42313. // Fog
  42314. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42315. // Morph targets
  42316. if (defines.NUM_MORPH_INFLUENCERS) {
  42317. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42318. }
  42319. // Log. depth
  42320. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42321. // image processing
  42322. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42323. this._imageProcessingConfiguration.bind(this._activeEffect);
  42324. }
  42325. }
  42326. this._uniformBuffer.update();
  42327. this._afterBind(mesh, this._activeEffect);
  42328. };
  42329. StandardMaterial.prototype.getAnimatables = function () {
  42330. var results = [];
  42331. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42332. results.push(this._diffuseTexture);
  42333. }
  42334. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42335. results.push(this._ambientTexture);
  42336. }
  42337. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42338. results.push(this._opacityTexture);
  42339. }
  42340. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42341. results.push(this._reflectionTexture);
  42342. }
  42343. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42344. results.push(this._emissiveTexture);
  42345. }
  42346. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42347. results.push(this._specularTexture);
  42348. }
  42349. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42350. results.push(this._bumpTexture);
  42351. }
  42352. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42353. results.push(this._lightmapTexture);
  42354. }
  42355. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42356. results.push(this._refractionTexture);
  42357. }
  42358. return results;
  42359. };
  42360. StandardMaterial.prototype.getActiveTextures = function () {
  42361. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42362. if (this._diffuseTexture) {
  42363. activeTextures.push(this._diffuseTexture);
  42364. }
  42365. if (this._ambientTexture) {
  42366. activeTextures.push(this._ambientTexture);
  42367. }
  42368. if (this._opacityTexture) {
  42369. activeTextures.push(this._opacityTexture);
  42370. }
  42371. if (this._reflectionTexture) {
  42372. activeTextures.push(this._reflectionTexture);
  42373. }
  42374. if (this._emissiveTexture) {
  42375. activeTextures.push(this._emissiveTexture);
  42376. }
  42377. if (this._specularTexture) {
  42378. activeTextures.push(this._specularTexture);
  42379. }
  42380. if (this._bumpTexture) {
  42381. activeTextures.push(this._bumpTexture);
  42382. }
  42383. if (this._lightmapTexture) {
  42384. activeTextures.push(this._lightmapTexture);
  42385. }
  42386. if (this._refractionTexture) {
  42387. activeTextures.push(this._refractionTexture);
  42388. }
  42389. return activeTextures;
  42390. };
  42391. StandardMaterial.prototype.hasTexture = function (texture) {
  42392. if (_super.prototype.hasTexture.call(this, texture)) {
  42393. return true;
  42394. }
  42395. if (this._diffuseTexture === texture) {
  42396. return true;
  42397. }
  42398. if (this._ambientTexture === texture) {
  42399. return true;
  42400. }
  42401. if (this._opacityTexture === texture) {
  42402. return true;
  42403. }
  42404. if (this._reflectionTexture === texture) {
  42405. return true;
  42406. }
  42407. if (this._emissiveTexture === texture) {
  42408. return true;
  42409. }
  42410. if (this._specularTexture === texture) {
  42411. return true;
  42412. }
  42413. if (this._bumpTexture === texture) {
  42414. return true;
  42415. }
  42416. if (this._lightmapTexture === texture) {
  42417. return true;
  42418. }
  42419. if (this._refractionTexture === texture) {
  42420. return true;
  42421. }
  42422. return false;
  42423. };
  42424. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42425. if (forceDisposeTextures) {
  42426. if (this._diffuseTexture) {
  42427. this._diffuseTexture.dispose();
  42428. }
  42429. if (this._ambientTexture) {
  42430. this._ambientTexture.dispose();
  42431. }
  42432. if (this._opacityTexture) {
  42433. this._opacityTexture.dispose();
  42434. }
  42435. if (this._reflectionTexture) {
  42436. this._reflectionTexture.dispose();
  42437. }
  42438. if (this._emissiveTexture) {
  42439. this._emissiveTexture.dispose();
  42440. }
  42441. if (this._specularTexture) {
  42442. this._specularTexture.dispose();
  42443. }
  42444. if (this._bumpTexture) {
  42445. this._bumpTexture.dispose();
  42446. }
  42447. if (this._lightmapTexture) {
  42448. this._lightmapTexture.dispose();
  42449. }
  42450. if (this._refractionTexture) {
  42451. this._refractionTexture.dispose();
  42452. }
  42453. }
  42454. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42455. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42456. }
  42457. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42458. };
  42459. StandardMaterial.prototype.clone = function (name) {
  42460. var _this = this;
  42461. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42462. result.name = name;
  42463. result.id = name;
  42464. return result;
  42465. };
  42466. StandardMaterial.prototype.serialize = function () {
  42467. return BABYLON.SerializationHelper.Serialize(this);
  42468. };
  42469. // Statics
  42470. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42471. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42472. };
  42473. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42474. get: function () {
  42475. return StandardMaterial._DiffuseTextureEnabled;
  42476. },
  42477. set: function (value) {
  42478. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42479. return;
  42480. }
  42481. StandardMaterial._DiffuseTextureEnabled = value;
  42482. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42483. },
  42484. enumerable: true,
  42485. configurable: true
  42486. });
  42487. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42488. get: function () {
  42489. return StandardMaterial._AmbientTextureEnabled;
  42490. },
  42491. set: function (value) {
  42492. if (StandardMaterial._AmbientTextureEnabled === value) {
  42493. return;
  42494. }
  42495. StandardMaterial._AmbientTextureEnabled = value;
  42496. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42497. },
  42498. enumerable: true,
  42499. configurable: true
  42500. });
  42501. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42502. get: function () {
  42503. return StandardMaterial._OpacityTextureEnabled;
  42504. },
  42505. set: function (value) {
  42506. if (StandardMaterial._OpacityTextureEnabled === value) {
  42507. return;
  42508. }
  42509. StandardMaterial._OpacityTextureEnabled = value;
  42510. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42511. },
  42512. enumerable: true,
  42513. configurable: true
  42514. });
  42515. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42516. get: function () {
  42517. return StandardMaterial._ReflectionTextureEnabled;
  42518. },
  42519. set: function (value) {
  42520. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42521. return;
  42522. }
  42523. StandardMaterial._ReflectionTextureEnabled = value;
  42524. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42525. },
  42526. enumerable: true,
  42527. configurable: true
  42528. });
  42529. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42530. get: function () {
  42531. return StandardMaterial._EmissiveTextureEnabled;
  42532. },
  42533. set: function (value) {
  42534. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42535. return;
  42536. }
  42537. StandardMaterial._EmissiveTextureEnabled = value;
  42538. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42539. },
  42540. enumerable: true,
  42541. configurable: true
  42542. });
  42543. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42544. get: function () {
  42545. return StandardMaterial._SpecularTextureEnabled;
  42546. },
  42547. set: function (value) {
  42548. if (StandardMaterial._SpecularTextureEnabled === value) {
  42549. return;
  42550. }
  42551. StandardMaterial._SpecularTextureEnabled = value;
  42552. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42553. },
  42554. enumerable: true,
  42555. configurable: true
  42556. });
  42557. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42558. get: function () {
  42559. return StandardMaterial._BumpTextureEnabled;
  42560. },
  42561. set: function (value) {
  42562. if (StandardMaterial._BumpTextureEnabled === value) {
  42563. return;
  42564. }
  42565. StandardMaterial._BumpTextureEnabled = value;
  42566. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42567. },
  42568. enumerable: true,
  42569. configurable: true
  42570. });
  42571. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42572. get: function () {
  42573. return StandardMaterial._LightmapTextureEnabled;
  42574. },
  42575. set: function (value) {
  42576. if (StandardMaterial._LightmapTextureEnabled === value) {
  42577. return;
  42578. }
  42579. StandardMaterial._LightmapTextureEnabled = value;
  42580. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42581. },
  42582. enumerable: true,
  42583. configurable: true
  42584. });
  42585. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42586. get: function () {
  42587. return StandardMaterial._RefractionTextureEnabled;
  42588. },
  42589. set: function (value) {
  42590. if (StandardMaterial._RefractionTextureEnabled === value) {
  42591. return;
  42592. }
  42593. StandardMaterial._RefractionTextureEnabled = value;
  42594. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42595. },
  42596. enumerable: true,
  42597. configurable: true
  42598. });
  42599. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42600. get: function () {
  42601. return StandardMaterial._ColorGradingTextureEnabled;
  42602. },
  42603. set: function (value) {
  42604. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42605. return;
  42606. }
  42607. StandardMaterial._ColorGradingTextureEnabled = value;
  42608. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42609. },
  42610. enumerable: true,
  42611. configurable: true
  42612. });
  42613. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42614. get: function () {
  42615. return StandardMaterial._FresnelEnabled;
  42616. },
  42617. set: function (value) {
  42618. if (StandardMaterial._FresnelEnabled === value) {
  42619. return;
  42620. }
  42621. StandardMaterial._FresnelEnabled = value;
  42622. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42623. },
  42624. enumerable: true,
  42625. configurable: true
  42626. });
  42627. // Flags used to enable or disable a type of texture for all Standard Materials
  42628. StandardMaterial._DiffuseTextureEnabled = true;
  42629. StandardMaterial._AmbientTextureEnabled = true;
  42630. StandardMaterial._OpacityTextureEnabled = true;
  42631. StandardMaterial._ReflectionTextureEnabled = true;
  42632. StandardMaterial._EmissiveTextureEnabled = true;
  42633. StandardMaterial._SpecularTextureEnabled = true;
  42634. StandardMaterial._BumpTextureEnabled = true;
  42635. StandardMaterial._LightmapTextureEnabled = true;
  42636. StandardMaterial._RefractionTextureEnabled = true;
  42637. StandardMaterial._ColorGradingTextureEnabled = true;
  42638. StandardMaterial._FresnelEnabled = true;
  42639. __decorate([
  42640. BABYLON.serializeAsTexture("diffuseTexture")
  42641. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42642. __decorate([
  42643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42644. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42645. __decorate([
  42646. BABYLON.serializeAsTexture("ambientTexture")
  42647. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42648. __decorate([
  42649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42650. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42651. __decorate([
  42652. BABYLON.serializeAsTexture("opacityTexture")
  42653. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42654. __decorate([
  42655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42656. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42657. __decorate([
  42658. BABYLON.serializeAsTexture("reflectionTexture")
  42659. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42660. __decorate([
  42661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42662. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42663. __decorate([
  42664. BABYLON.serializeAsTexture("emissiveTexture")
  42665. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42666. __decorate([
  42667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42668. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42669. __decorate([
  42670. BABYLON.serializeAsTexture("specularTexture")
  42671. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42672. __decorate([
  42673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42674. ], StandardMaterial.prototype, "specularTexture", void 0);
  42675. __decorate([
  42676. BABYLON.serializeAsTexture("bumpTexture")
  42677. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42678. __decorate([
  42679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42680. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42681. __decorate([
  42682. BABYLON.serializeAsTexture("lightmapTexture")
  42683. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42684. __decorate([
  42685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42686. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42687. __decorate([
  42688. BABYLON.serializeAsTexture("refractionTexture")
  42689. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42690. __decorate([
  42691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42692. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42693. __decorate([
  42694. BABYLON.serializeAsColor3("ambient")
  42695. ], StandardMaterial.prototype, "ambientColor", void 0);
  42696. __decorate([
  42697. BABYLON.serializeAsColor3("diffuse")
  42698. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42699. __decorate([
  42700. BABYLON.serializeAsColor3("specular")
  42701. ], StandardMaterial.prototype, "specularColor", void 0);
  42702. __decorate([
  42703. BABYLON.serializeAsColor3("emissive")
  42704. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42705. __decorate([
  42706. BABYLON.serialize()
  42707. ], StandardMaterial.prototype, "specularPower", void 0);
  42708. __decorate([
  42709. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42710. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42711. __decorate([
  42712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42713. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42714. __decorate([
  42715. BABYLON.serialize("useEmissiveAsIllumination")
  42716. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42717. __decorate([
  42718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42719. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42720. __decorate([
  42721. BABYLON.serialize("linkEmissiveWithDiffuse")
  42722. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42723. __decorate([
  42724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42725. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42726. __decorate([
  42727. BABYLON.serialize("useSpecularOverAlpha")
  42728. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42729. __decorate([
  42730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42731. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42732. __decorate([
  42733. BABYLON.serialize("useReflectionOverAlpha")
  42734. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42735. __decorate([
  42736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42737. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42738. __decorate([
  42739. BABYLON.serialize("disableLighting")
  42740. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42741. __decorate([
  42742. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42743. ], StandardMaterial.prototype, "disableLighting", void 0);
  42744. __decorate([
  42745. BABYLON.serialize("useObjectSpaceNormalMap")
  42746. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42747. __decorate([
  42748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42749. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42750. __decorate([
  42751. BABYLON.serialize("useParallax")
  42752. ], StandardMaterial.prototype, "_useParallax", void 0);
  42753. __decorate([
  42754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42755. ], StandardMaterial.prototype, "useParallax", void 0);
  42756. __decorate([
  42757. BABYLON.serialize("useParallaxOcclusion")
  42758. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42759. __decorate([
  42760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42761. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42762. __decorate([
  42763. BABYLON.serialize()
  42764. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42765. __decorate([
  42766. BABYLON.serialize("roughness")
  42767. ], StandardMaterial.prototype, "_roughness", void 0);
  42768. __decorate([
  42769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42770. ], StandardMaterial.prototype, "roughness", void 0);
  42771. __decorate([
  42772. BABYLON.serialize()
  42773. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42774. __decorate([
  42775. BABYLON.serialize()
  42776. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42777. __decorate([
  42778. BABYLON.serialize()
  42779. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42780. __decorate([
  42781. BABYLON.serialize("useLightmapAsShadowmap")
  42782. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42783. __decorate([
  42784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42785. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42786. __decorate([
  42787. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42788. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42789. __decorate([
  42790. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42791. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42792. __decorate([
  42793. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42794. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42795. __decorate([
  42796. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42797. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42798. __decorate([
  42799. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42800. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42801. __decorate([
  42802. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42803. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42804. __decorate([
  42805. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42806. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42807. __decorate([
  42808. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42809. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42810. __decorate([
  42811. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42812. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42813. __decorate([
  42814. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42815. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42816. __decorate([
  42817. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42818. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42819. __decorate([
  42820. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42821. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42822. __decorate([
  42823. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42824. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42825. __decorate([
  42826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42827. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42828. __decorate([
  42829. BABYLON.serialize("maxSimultaneousLights")
  42830. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42831. __decorate([
  42832. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42833. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42834. __decorate([
  42835. BABYLON.serialize("invertNormalMapX")
  42836. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42837. __decorate([
  42838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42839. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42840. __decorate([
  42841. BABYLON.serialize("invertNormalMapY")
  42842. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42843. __decorate([
  42844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42845. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42846. __decorate([
  42847. BABYLON.serialize("twoSidedLighting")
  42848. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42849. __decorate([
  42850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42851. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42852. __decorate([
  42853. BABYLON.serialize()
  42854. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42855. return StandardMaterial;
  42856. }(BABYLON.PushMaterial));
  42857. BABYLON.StandardMaterial = StandardMaterial;
  42858. })(BABYLON || (BABYLON = {}));
  42859. //# sourceMappingURL=babylon.standardMaterial.js.map
  42860. var BABYLON;
  42861. (function (BABYLON) {
  42862. /**
  42863. * Class representing spherical polynomial coefficients to the 3rd degree
  42864. */
  42865. var SphericalPolynomial = /** @class */ (function () {
  42866. function SphericalPolynomial() {
  42867. /**
  42868. * The x coefficients of the spherical polynomial
  42869. */
  42870. this.x = BABYLON.Vector3.Zero();
  42871. /**
  42872. * The y coefficients of the spherical polynomial
  42873. */
  42874. this.y = BABYLON.Vector3.Zero();
  42875. /**
  42876. * The z coefficients of the spherical polynomial
  42877. */
  42878. this.z = BABYLON.Vector3.Zero();
  42879. /**
  42880. * The xx coefficients of the spherical polynomial
  42881. */
  42882. this.xx = BABYLON.Vector3.Zero();
  42883. /**
  42884. * The yy coefficients of the spherical polynomial
  42885. */
  42886. this.yy = BABYLON.Vector3.Zero();
  42887. /**
  42888. * The zz coefficients of the spherical polynomial
  42889. */
  42890. this.zz = BABYLON.Vector3.Zero();
  42891. /**
  42892. * The xy coefficients of the spherical polynomial
  42893. */
  42894. this.xy = BABYLON.Vector3.Zero();
  42895. /**
  42896. * The yz coefficients of the spherical polynomial
  42897. */
  42898. this.yz = BABYLON.Vector3.Zero();
  42899. /**
  42900. * The zx coefficients of the spherical polynomial
  42901. */
  42902. this.zx = BABYLON.Vector3.Zero();
  42903. }
  42904. /**
  42905. * Adds an ambient color to the spherical polynomial
  42906. * @param color the color to add
  42907. */
  42908. SphericalPolynomial.prototype.addAmbient = function (color) {
  42909. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42910. this.xx = this.xx.add(colorVector);
  42911. this.yy = this.yy.add(colorVector);
  42912. this.zz = this.zz.add(colorVector);
  42913. };
  42914. /**
  42915. * Scales the spherical polynomial by the given amount
  42916. * @param scale the amount to scale
  42917. */
  42918. SphericalPolynomial.prototype.scale = function (scale) {
  42919. this.x = this.x.scale(scale);
  42920. this.y = this.y.scale(scale);
  42921. this.z = this.z.scale(scale);
  42922. this.xx = this.xx.scale(scale);
  42923. this.yy = this.yy.scale(scale);
  42924. this.zz = this.zz.scale(scale);
  42925. this.yz = this.yz.scale(scale);
  42926. this.zx = this.zx.scale(scale);
  42927. this.xy = this.xy.scale(scale);
  42928. };
  42929. /**
  42930. * Gets the spherical polynomial from harmonics
  42931. * @param harmonics the spherical harmonics
  42932. * @returns the spherical polynomial
  42933. */
  42934. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42935. var result = new SphericalPolynomial();
  42936. result.x = harmonics.l11.scale(1.02333);
  42937. result.y = harmonics.l1_1.scale(1.02333);
  42938. result.z = harmonics.l10.scale(1.02333);
  42939. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42940. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42941. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42942. result.yz = harmonics.l2_1.scale(0.858086);
  42943. result.zx = harmonics.l21.scale(0.858086);
  42944. result.xy = harmonics.l2_2.scale(0.858086);
  42945. result.scale(1.0 / Math.PI);
  42946. return result;
  42947. };
  42948. /**
  42949. * Constructs a spherical polynomial from an array.
  42950. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42951. * @returns the spherical polynomial
  42952. */
  42953. SphericalPolynomial.FromArray = function (data) {
  42954. var sp = new SphericalPolynomial();
  42955. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42956. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42957. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42958. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42959. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42960. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42961. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42962. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42963. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42964. return sp;
  42965. };
  42966. return SphericalPolynomial;
  42967. }());
  42968. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42969. /**
  42970. * Class representing spherical harmonics coefficients to the 3rd degree
  42971. */
  42972. var SphericalHarmonics = /** @class */ (function () {
  42973. function SphericalHarmonics() {
  42974. /**
  42975. * The l0,0 coefficients of the spherical harmonics
  42976. */
  42977. this.l00 = BABYLON.Vector3.Zero();
  42978. /**
  42979. * The l1,-1 coefficients of the spherical harmonics
  42980. */
  42981. this.l1_1 = BABYLON.Vector3.Zero();
  42982. /**
  42983. * The l1,0 coefficients of the spherical harmonics
  42984. */
  42985. this.l10 = BABYLON.Vector3.Zero();
  42986. /**
  42987. * The l1,1 coefficients of the spherical harmonics
  42988. */
  42989. this.l11 = BABYLON.Vector3.Zero();
  42990. /**
  42991. * The l2,-2 coefficients of the spherical harmonics
  42992. */
  42993. this.l2_2 = BABYLON.Vector3.Zero();
  42994. /**
  42995. * The l2,-1 coefficients of the spherical harmonics
  42996. */
  42997. this.l2_1 = BABYLON.Vector3.Zero();
  42998. /**
  42999. * The l2,0 coefficients of the spherical harmonics
  43000. */
  43001. this.l20 = BABYLON.Vector3.Zero();
  43002. /**
  43003. * The l2,1 coefficients of the spherical harmonics
  43004. */
  43005. this.l21 = BABYLON.Vector3.Zero();
  43006. /**
  43007. * The l2,2 coefficients of the spherical harmonics
  43008. */
  43009. this.lL22 = BABYLON.Vector3.Zero();
  43010. }
  43011. /**
  43012. * Adds a light to the spherical harmonics
  43013. * @param direction the direction of the light
  43014. * @param color the color of the light
  43015. * @param deltaSolidAngle the delta solid angle of the light
  43016. */
  43017. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43018. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43019. var c = colorVector.scale(deltaSolidAngle);
  43020. this.l00 = this.l00.add(c.scale(0.282095));
  43021. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43022. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43023. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43024. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43025. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43026. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43027. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43028. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43029. };
  43030. /**
  43031. * Scales the spherical harmonics by the given amount
  43032. * @param scale the amount to scale
  43033. */
  43034. SphericalHarmonics.prototype.scale = function (scale) {
  43035. this.l00 = this.l00.scale(scale);
  43036. this.l1_1 = this.l1_1.scale(scale);
  43037. this.l10 = this.l10.scale(scale);
  43038. this.l11 = this.l11.scale(scale);
  43039. this.l2_2 = this.l2_2.scale(scale);
  43040. this.l2_1 = this.l2_1.scale(scale);
  43041. this.l20 = this.l20.scale(scale);
  43042. this.l21 = this.l21.scale(scale);
  43043. this.lL22 = this.lL22.scale(scale);
  43044. };
  43045. /**
  43046. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43047. *
  43048. * ```
  43049. * E_lm = A_l * L_lm
  43050. * ```
  43051. *
  43052. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43053. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43054. * the scaling factors are given in equation 9.
  43055. */
  43056. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43057. // Constant (Band 0)
  43058. this.l00 = this.l00.scale(3.141593);
  43059. // Linear (Band 1)
  43060. this.l1_1 = this.l1_1.scale(2.094395);
  43061. this.l10 = this.l10.scale(2.094395);
  43062. this.l11 = this.l11.scale(2.094395);
  43063. // Quadratic (Band 2)
  43064. this.l2_2 = this.l2_2.scale(0.785398);
  43065. this.l2_1 = this.l2_1.scale(0.785398);
  43066. this.l20 = this.l20.scale(0.785398);
  43067. this.l21 = this.l21.scale(0.785398);
  43068. this.lL22 = this.lL22.scale(0.785398);
  43069. };
  43070. /**
  43071. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43072. *
  43073. * ```
  43074. * L = (1/pi) * E * rho
  43075. * ```
  43076. *
  43077. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43078. */
  43079. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43080. this.scale(1.0 / Math.PI);
  43081. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43082. // (The pixel shader must apply albedo after texture fetches, etc).
  43083. };
  43084. /**
  43085. * Gets the spherical harmonics from polynomial
  43086. * @param polynomial the spherical polynomial
  43087. * @returns the spherical harmonics
  43088. */
  43089. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43090. var result = new SphericalHarmonics();
  43091. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43092. result.l1_1 = polynomial.y.scale(0.977204);
  43093. result.l10 = polynomial.z.scale(0.977204);
  43094. result.l11 = polynomial.x.scale(0.977204);
  43095. result.l2_2 = polynomial.xy.scale(1.16538);
  43096. result.l2_1 = polynomial.yz.scale(1.16538);
  43097. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43098. result.l21 = polynomial.zx.scale(1.16538);
  43099. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43100. result.scale(Math.PI);
  43101. return result;
  43102. };
  43103. /**
  43104. * Constructs a spherical harmonics from an array.
  43105. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43106. * @returns the spherical harmonics
  43107. */
  43108. SphericalHarmonics.FromArray = function (data) {
  43109. var sh = new SphericalHarmonics();
  43110. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43111. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43112. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43113. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43114. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43115. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43116. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43117. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43118. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43119. return sh;
  43120. };
  43121. return SphericalHarmonics;
  43122. }());
  43123. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43124. })(BABYLON || (BABYLON = {}));
  43125. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43126. var BABYLON;
  43127. (function (BABYLON) {
  43128. var FileFaceOrientation = /** @class */ (function () {
  43129. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43130. this.name = name;
  43131. this.worldAxisForNormal = worldAxisForNormal;
  43132. this.worldAxisForFileX = worldAxisForFileX;
  43133. this.worldAxisForFileY = worldAxisForFileY;
  43134. }
  43135. return FileFaceOrientation;
  43136. }());
  43137. ;
  43138. /**
  43139. * Helper class dealing with the extraction of spherical polynomial dataArray
  43140. * from a cube map.
  43141. */
  43142. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43143. function CubeMapToSphericalPolynomialTools() {
  43144. }
  43145. /**
  43146. * Converts a texture to the according Spherical Polynomial data.
  43147. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43148. *
  43149. * @param texture The texture to extract the information from.
  43150. * @return The Spherical Polynomial data.
  43151. */
  43152. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43153. if (!texture.isCube) {
  43154. // Only supports cube Textures currently.
  43155. return null;
  43156. }
  43157. var size = texture.getSize().width;
  43158. var right = texture.readPixels(0);
  43159. var left = texture.readPixels(1);
  43160. var up;
  43161. var down;
  43162. if (texture.isRenderTarget) {
  43163. up = texture.readPixels(3);
  43164. down = texture.readPixels(2);
  43165. }
  43166. else {
  43167. up = texture.readPixels(2);
  43168. down = texture.readPixels(3);
  43169. }
  43170. var front = texture.readPixels(4);
  43171. var back = texture.readPixels(5);
  43172. var gammaSpace = texture.gammaSpace;
  43173. // Always read as RGBA.
  43174. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43175. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43176. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43177. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43178. }
  43179. var cubeInfo = {
  43180. size: size,
  43181. right: right,
  43182. left: left,
  43183. up: up,
  43184. down: down,
  43185. front: front,
  43186. back: back,
  43187. format: format,
  43188. type: type,
  43189. gammaSpace: gammaSpace,
  43190. };
  43191. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43192. };
  43193. /**
  43194. * Converts a cubemap to the according Spherical Polynomial data.
  43195. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43196. *
  43197. * @param cubeInfo The Cube map to extract the information from.
  43198. * @return The Spherical Polynomial data.
  43199. */
  43200. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43201. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43202. var totalSolidAngle = 0.0;
  43203. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43204. var du = 2.0 / cubeInfo.size;
  43205. var dv = du;
  43206. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43207. var minUV = du * 0.5 - 1.0;
  43208. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43209. var fileFace = this.FileFaces[faceIndex];
  43210. var dataArray = cubeInfo[fileFace.name];
  43211. var v = minUV;
  43212. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43213. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43214. // Because SP is still linear, so summation is fine in that basis.
  43215. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43216. for (var y = 0; y < cubeInfo.size; y++) {
  43217. var u = minUV;
  43218. for (var x = 0; x < cubeInfo.size; x++) {
  43219. // World direction (not normalised)
  43220. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43221. worldDirection.normalize();
  43222. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43223. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43224. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43225. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43226. // Handle Integer types.
  43227. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43228. r /= 255;
  43229. g /= 255;
  43230. b /= 255;
  43231. }
  43232. // Handle Gamma space textures.
  43233. if (cubeInfo.gammaSpace) {
  43234. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43235. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43236. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43237. }
  43238. var color = new BABYLON.Color3(r, g, b);
  43239. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43240. totalSolidAngle += deltaSolidAngle;
  43241. u += du;
  43242. }
  43243. v += dv;
  43244. }
  43245. }
  43246. // Solid angle for entire sphere is 4*pi
  43247. var sphereSolidAngle = 4.0 * Math.PI;
  43248. // Adjust the solid angle to allow for how many faces we processed.
  43249. var facesProcessed = 6.0;
  43250. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43251. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43252. // This is needed because the numerical integration over the cube uses a
  43253. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43254. // and also to compensate for accumulative error due to float precision in the summation.
  43255. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43256. sphericalHarmonics.scale(correctionFactor);
  43257. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43258. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43259. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43260. };
  43261. CubeMapToSphericalPolynomialTools.FileFaces = [
  43262. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43263. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43264. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43265. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43266. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43267. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43268. ];
  43269. return CubeMapToSphericalPolynomialTools;
  43270. }());
  43271. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43272. })(BABYLON || (BABYLON = {}));
  43273. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43274. var BABYLON;
  43275. (function (BABYLON) {
  43276. /**
  43277. * Manages the defines for the PBR Material.
  43278. * @hiddenChildren
  43279. */
  43280. var PBRMaterialDefines = /** @class */ (function (_super) {
  43281. __extends(PBRMaterialDefines, _super);
  43282. /**
  43283. * Initializes the PBR Material defines.
  43284. */
  43285. function PBRMaterialDefines() {
  43286. var _this = _super.call(this) || this;
  43287. _this.PBR = true;
  43288. _this.MAINUV1 = false;
  43289. _this.MAINUV2 = false;
  43290. _this.UV1 = false;
  43291. _this.UV2 = false;
  43292. _this.ALBEDO = false;
  43293. _this.ALBEDODIRECTUV = 0;
  43294. _this.VERTEXCOLOR = false;
  43295. _this.AMBIENT = false;
  43296. _this.AMBIENTDIRECTUV = 0;
  43297. _this.AMBIENTINGRAYSCALE = false;
  43298. _this.OPACITY = false;
  43299. _this.VERTEXALPHA = false;
  43300. _this.OPACITYDIRECTUV = 0;
  43301. _this.OPACITYRGB = false;
  43302. _this.ALPHATEST = false;
  43303. _this.DEPTHPREPASS = false;
  43304. _this.ALPHABLEND = false;
  43305. _this.ALPHAFROMALBEDO = false;
  43306. _this.ALPHATESTVALUE = "0.5";
  43307. _this.SPECULAROVERALPHA = false;
  43308. _this.RADIANCEOVERALPHA = false;
  43309. _this.ALPHAFRESNEL = false;
  43310. _this.LINEARALPHAFRESNEL = false;
  43311. _this.PREMULTIPLYALPHA = false;
  43312. _this.EMISSIVE = false;
  43313. _this.EMISSIVEDIRECTUV = 0;
  43314. _this.REFLECTIVITY = false;
  43315. _this.REFLECTIVITYDIRECTUV = 0;
  43316. _this.SPECULARTERM = false;
  43317. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43318. _this.MICROSURFACEAUTOMATIC = false;
  43319. _this.LODBASEDMICROSFURACE = false;
  43320. _this.MICROSURFACEMAP = false;
  43321. _this.MICROSURFACEMAPDIRECTUV = 0;
  43322. _this.METALLICWORKFLOW = false;
  43323. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43324. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43325. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43326. _this.AOSTOREINMETALMAPRED = false;
  43327. _this.ENVIRONMENTBRDF = false;
  43328. _this.NORMAL = false;
  43329. _this.TANGENT = false;
  43330. _this.BUMP = false;
  43331. _this.BUMPDIRECTUV = 0;
  43332. _this.OBJECTSPACE_NORMALMAP = false;
  43333. _this.PARALLAX = false;
  43334. _this.PARALLAXOCCLUSION = false;
  43335. _this.NORMALXYSCALE = true;
  43336. _this.LIGHTMAP = false;
  43337. _this.LIGHTMAPDIRECTUV = 0;
  43338. _this.USELIGHTMAPASSHADOWMAP = false;
  43339. _this.GAMMALIGHTMAP = false;
  43340. _this.REFLECTION = false;
  43341. _this.REFLECTIONMAP_3D = false;
  43342. _this.REFLECTIONMAP_SPHERICAL = false;
  43343. _this.REFLECTIONMAP_PLANAR = false;
  43344. _this.REFLECTIONMAP_CUBIC = false;
  43345. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43346. _this.REFLECTIONMAP_PROJECTION = false;
  43347. _this.REFLECTIONMAP_SKYBOX = false;
  43348. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43349. _this.REFLECTIONMAP_EXPLICIT = false;
  43350. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43351. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43352. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43353. _this.INVERTCUBICMAP = false;
  43354. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43355. _this.USESPHERICALINVERTEX = false;
  43356. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43357. _this.LODINREFLECTIONALPHA = false;
  43358. _this.GAMMAREFLECTION = false;
  43359. _this.RGBDREFLECTION = false;
  43360. _this.RADIANCEOCCLUSION = false;
  43361. _this.HORIZONOCCLUSION = false;
  43362. _this.REFRACTION = false;
  43363. _this.REFRACTIONMAP_3D = false;
  43364. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43365. _this.LODINREFRACTIONALPHA = false;
  43366. _this.GAMMAREFRACTION = false;
  43367. _this.RGBDREFRACTION = false;
  43368. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43369. _this.INSTANCES = false;
  43370. _this.NUM_BONE_INFLUENCERS = 0;
  43371. _this.BonesPerMesh = 0;
  43372. _this.NONUNIFORMSCALING = false;
  43373. _this.MORPHTARGETS = false;
  43374. _this.MORPHTARGETS_NORMAL = false;
  43375. _this.MORPHTARGETS_TANGENT = false;
  43376. _this.NUM_MORPH_INFLUENCERS = 0;
  43377. _this.IMAGEPROCESSING = false;
  43378. _this.VIGNETTE = false;
  43379. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43380. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43381. _this.TONEMAPPING = false;
  43382. _this.TONEMAPPING_ACES = false;
  43383. _this.CONTRAST = false;
  43384. _this.COLORCURVES = false;
  43385. _this.COLORGRADING = false;
  43386. _this.COLORGRADING3D = false;
  43387. _this.SAMPLER3DGREENDEPTH = false;
  43388. _this.SAMPLER3DBGRMAP = false;
  43389. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43390. _this.EXPOSURE = false;
  43391. _this.USEPHYSICALLIGHTFALLOFF = false;
  43392. _this.USEGLTFLIGHTFALLOFF = false;
  43393. _this.TWOSIDEDLIGHTING = false;
  43394. _this.SHADOWFLOAT = false;
  43395. _this.CLIPPLANE = false;
  43396. _this.CLIPPLANE2 = false;
  43397. _this.CLIPPLANE3 = false;
  43398. _this.CLIPPLANE4 = false;
  43399. _this.POINTSIZE = false;
  43400. _this.FOG = false;
  43401. _this.LOGARITHMICDEPTH = false;
  43402. _this.FORCENORMALFORWARD = false;
  43403. _this.SPECULARAA = false;
  43404. _this.UNLIT = false;
  43405. _this.rebuild();
  43406. return _this;
  43407. }
  43408. /**
  43409. * Resets the PBR Material defines.
  43410. */
  43411. PBRMaterialDefines.prototype.reset = function () {
  43412. _super.prototype.reset.call(this);
  43413. this.ALPHATESTVALUE = "0.5";
  43414. this.PBR = true;
  43415. };
  43416. return PBRMaterialDefines;
  43417. }(BABYLON.MaterialDefines));
  43418. /**
  43419. * The Physically based material base class of BJS.
  43420. *
  43421. * This offers the main features of a standard PBR material.
  43422. * For more information, please refer to the documentation :
  43423. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43424. */
  43425. var PBRBaseMaterial = /** @class */ (function (_super) {
  43426. __extends(PBRBaseMaterial, _super);
  43427. /**
  43428. * Instantiates a new PBRMaterial instance.
  43429. *
  43430. * @param name The material name
  43431. * @param scene The scene the material will be use in.
  43432. */
  43433. function PBRBaseMaterial(name, scene) {
  43434. var _this = _super.call(this, name, scene) || this;
  43435. /**
  43436. * Intensity of the direct lights e.g. the four lights available in your scene.
  43437. * This impacts both the direct diffuse and specular highlights.
  43438. */
  43439. _this._directIntensity = 1.0;
  43440. /**
  43441. * Intensity of the emissive part of the material.
  43442. * This helps controlling the emissive effect without modifying the emissive color.
  43443. */
  43444. _this._emissiveIntensity = 1.0;
  43445. /**
  43446. * Intensity of the environment e.g. how much the environment will light the object
  43447. * either through harmonics for rough material or through the refelction for shiny ones.
  43448. */
  43449. _this._environmentIntensity = 1.0;
  43450. /**
  43451. * This is a special control allowing the reduction of the specular highlights coming from the
  43452. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43453. */
  43454. _this._specularIntensity = 1.0;
  43455. /**
  43456. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43457. */
  43458. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43459. /**
  43460. * Debug Control allowing disabling the bump map on this material.
  43461. */
  43462. _this._disableBumpMap = false;
  43463. /**
  43464. * AKA Occlusion Texture Intensity in other nomenclature.
  43465. */
  43466. _this._ambientTextureStrength = 1.0;
  43467. /**
  43468. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43469. * 1 means it completely occludes it
  43470. * 0 mean it has no impact
  43471. */
  43472. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43473. /**
  43474. * The color of a material in ambient lighting.
  43475. */
  43476. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43477. /**
  43478. * AKA Diffuse Color in other nomenclature.
  43479. */
  43480. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43481. /**
  43482. * AKA Specular Color in other nomenclature.
  43483. */
  43484. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43485. /**
  43486. * The color applied when light is reflected from a material.
  43487. */
  43488. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43489. /**
  43490. * The color applied when light is emitted from a material.
  43491. */
  43492. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43493. /**
  43494. * AKA Glossiness in other nomenclature.
  43495. */
  43496. _this._microSurface = 0.9;
  43497. /**
  43498. * source material index of refraction (IOR)' / 'destination material IOR.
  43499. */
  43500. _this._indexOfRefraction = 0.66;
  43501. /**
  43502. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43503. */
  43504. _this._invertRefractionY = false;
  43505. /**
  43506. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43507. * Materials half opaque for instance using refraction could benefit from this control.
  43508. */
  43509. _this._linkRefractionWithTransparency = false;
  43510. /**
  43511. * Specifies that the material will use the light map as a show map.
  43512. */
  43513. _this._useLightmapAsShadowmap = false;
  43514. /**
  43515. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43516. * makes the reflect vector face the model (under horizon).
  43517. */
  43518. _this._useHorizonOcclusion = true;
  43519. /**
  43520. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43521. * too much the area relying on ambient texture to define their ambient occlusion.
  43522. */
  43523. _this._useRadianceOcclusion = true;
  43524. /**
  43525. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43526. */
  43527. _this._useAlphaFromAlbedoTexture = false;
  43528. /**
  43529. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43530. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43531. */
  43532. _this._useSpecularOverAlpha = true;
  43533. /**
  43534. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43535. */
  43536. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43537. /**
  43538. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43539. */
  43540. _this._useRoughnessFromMetallicTextureAlpha = true;
  43541. /**
  43542. * Specifies if the metallic texture contains the roughness information in its green channel.
  43543. */
  43544. _this._useRoughnessFromMetallicTextureGreen = false;
  43545. /**
  43546. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43547. */
  43548. _this._useMetallnessFromMetallicTextureBlue = false;
  43549. /**
  43550. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43551. */
  43552. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43553. /**
  43554. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43555. */
  43556. _this._useAmbientInGrayScale = false;
  43557. /**
  43558. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43559. * The material will try to infer what glossiness each pixel should be.
  43560. */
  43561. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43562. /**
  43563. * Defines the falloff type used in this material.
  43564. * It by default is Physical.
  43565. */
  43566. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43567. /**
  43568. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43569. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43570. */
  43571. _this._useRadianceOverAlpha = true;
  43572. /**
  43573. * Allows using an object space normal map (instead of tangent space).
  43574. */
  43575. _this._useObjectSpaceNormalMap = false;
  43576. /**
  43577. * Allows using the bump map in parallax mode.
  43578. */
  43579. _this._useParallax = false;
  43580. /**
  43581. * Allows using the bump map in parallax occlusion mode.
  43582. */
  43583. _this._useParallaxOcclusion = false;
  43584. /**
  43585. * Controls the scale bias of the parallax mode.
  43586. */
  43587. _this._parallaxScaleBias = 0.05;
  43588. /**
  43589. * If sets to true, disables all the lights affecting the material.
  43590. */
  43591. _this._disableLighting = false;
  43592. /**
  43593. * Number of Simultaneous lights allowed on the material.
  43594. */
  43595. _this._maxSimultaneousLights = 4;
  43596. /**
  43597. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43598. */
  43599. _this._invertNormalMapX = false;
  43600. /**
  43601. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43602. */
  43603. _this._invertNormalMapY = false;
  43604. /**
  43605. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43606. */
  43607. _this._twoSidedLighting = false;
  43608. /**
  43609. * Defines the alpha limits in alpha test mode.
  43610. */
  43611. _this._alphaCutOff = 0.4;
  43612. /**
  43613. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43614. */
  43615. _this._forceAlphaTest = false;
  43616. /**
  43617. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43618. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43619. */
  43620. _this._useAlphaFresnel = false;
  43621. /**
  43622. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43623. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43624. */
  43625. _this._useLinearAlphaFresnel = false;
  43626. /**
  43627. * The transparency mode of the material.
  43628. */
  43629. _this._transparencyMode = null;
  43630. /**
  43631. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43632. * from cos thetav and roughness:
  43633. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43634. */
  43635. _this._environmentBRDFTexture = null;
  43636. /**
  43637. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43638. */
  43639. _this._forceIrradianceInFragment = false;
  43640. /**
  43641. * Force normal to face away from face.
  43642. */
  43643. _this._forceNormalForward = false;
  43644. /**
  43645. * Enables specular anti aliasing in the PBR shader.
  43646. * It will both interacts on the Geometry for analytical and IBL lighting.
  43647. * It also prefilter the roughness map based on the bump values.
  43648. */
  43649. _this._enableSpecularAntiAliasing = false;
  43650. /**
  43651. * Stores the available render targets.
  43652. */
  43653. _this._renderTargets = new BABYLON.SmartArray(16);
  43654. /**
  43655. * Sets the global ambient color for the material used in lighting calculations.
  43656. */
  43657. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43658. /**
  43659. * If set to true, no lighting calculations will be applied.
  43660. */
  43661. _this._unlit = false;
  43662. // Setup the default processing configuration to the scene.
  43663. _this._attachImageProcessingConfiguration(null);
  43664. _this.getRenderTargetTextures = function () {
  43665. _this._renderTargets.reset();
  43666. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43667. _this._renderTargets.push(_this._reflectionTexture);
  43668. }
  43669. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43670. _this._renderTargets.push(_this._refractionTexture);
  43671. }
  43672. return _this._renderTargets;
  43673. };
  43674. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43675. return _this;
  43676. }
  43677. /**
  43678. * Attaches a new image processing configuration to the PBR Material.
  43679. * @param configuration
  43680. */
  43681. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43682. var _this = this;
  43683. if (configuration === this._imageProcessingConfiguration) {
  43684. return;
  43685. }
  43686. // Detaches observer.
  43687. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43688. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43689. }
  43690. // Pick the scene configuration if needed.
  43691. if (!configuration) {
  43692. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43693. }
  43694. else {
  43695. this._imageProcessingConfiguration = configuration;
  43696. }
  43697. // Attaches observer.
  43698. if (this._imageProcessingConfiguration) {
  43699. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43700. _this._markAllSubMeshesAsImageProcessingDirty();
  43701. });
  43702. }
  43703. };
  43704. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43705. /**
  43706. * Gets a boolean indicating that current material needs to register RTT
  43707. */
  43708. get: function () {
  43709. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43710. return true;
  43711. }
  43712. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43713. return true;
  43714. }
  43715. return false;
  43716. },
  43717. enumerable: true,
  43718. configurable: true
  43719. });
  43720. /**
  43721. * Gets the name of the material class.
  43722. */
  43723. PBRBaseMaterial.prototype.getClassName = function () {
  43724. return "PBRBaseMaterial";
  43725. };
  43726. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43727. /**
  43728. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43729. */
  43730. get: function () {
  43731. return this._useLogarithmicDepth;
  43732. },
  43733. /**
  43734. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43735. */
  43736. set: function (value) {
  43737. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43738. },
  43739. enumerable: true,
  43740. configurable: true
  43741. });
  43742. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43743. /**
  43744. * Gets the current transparency mode.
  43745. */
  43746. get: function () {
  43747. return this._transparencyMode;
  43748. },
  43749. /**
  43750. * Sets the transparency mode of the material.
  43751. *
  43752. * | Value | Type | Description |
  43753. * | ----- | ----------------------------------- | ----------- |
  43754. * | 0 | OPAQUE | |
  43755. * | 1 | ALPHATEST | |
  43756. * | 2 | ALPHABLEND | |
  43757. * | 3 | ALPHATESTANDBLEND | |
  43758. *
  43759. */
  43760. set: function (value) {
  43761. if (this._transparencyMode === value) {
  43762. return;
  43763. }
  43764. this._transparencyMode = value;
  43765. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43766. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43767. },
  43768. enumerable: true,
  43769. configurable: true
  43770. });
  43771. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43772. /**
  43773. * Returns true if alpha blending should be disabled.
  43774. */
  43775. get: function () {
  43776. return (this._linkRefractionWithTransparency ||
  43777. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43778. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. /**
  43784. * Specifies whether or not this material should be rendered in alpha blend mode.
  43785. */
  43786. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43787. if (this._disableAlphaBlending) {
  43788. return false;
  43789. }
  43790. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43791. };
  43792. /**
  43793. * Specifies if the mesh will require alpha blending.
  43794. * @param mesh - BJS mesh.
  43795. */
  43796. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43797. if (this._disableAlphaBlending) {
  43798. return false;
  43799. }
  43800. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43801. };
  43802. /**
  43803. * Specifies whether or not this material should be rendered in alpha test mode.
  43804. */
  43805. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43806. if (this._forceAlphaTest) {
  43807. return true;
  43808. }
  43809. if (this._linkRefractionWithTransparency) {
  43810. return false;
  43811. }
  43812. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43813. };
  43814. /**
  43815. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43816. */
  43817. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43818. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43819. };
  43820. /**
  43821. * Gets the texture used for the alpha test.
  43822. */
  43823. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43824. return this._albedoTexture;
  43825. };
  43826. /**
  43827. * Specifies that the submesh is ready to be used.
  43828. * @param mesh - BJS mesh.
  43829. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43830. * @param useInstances - Specifies that instances should be used.
  43831. * @returns - boolean indicating that the submesh is ready or not.
  43832. */
  43833. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43834. if (subMesh.effect && this.isFrozen) {
  43835. if (this._wasPreviouslyReady) {
  43836. return true;
  43837. }
  43838. }
  43839. if (!subMesh._materialDefines) {
  43840. subMesh._materialDefines = new PBRMaterialDefines();
  43841. }
  43842. var defines = subMesh._materialDefines;
  43843. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43844. if (defines._renderId === this.getScene().getRenderId()) {
  43845. return true;
  43846. }
  43847. }
  43848. var scene = this.getScene();
  43849. var engine = scene.getEngine();
  43850. if (defines._areTexturesDirty) {
  43851. if (scene.texturesEnabled) {
  43852. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43853. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43854. return false;
  43855. }
  43856. }
  43857. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43858. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43859. return false;
  43860. }
  43861. }
  43862. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43863. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43864. return false;
  43865. }
  43866. }
  43867. var reflectionTexture = this._getReflectionTexture();
  43868. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43869. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43870. return false;
  43871. }
  43872. }
  43873. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43874. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43875. return false;
  43876. }
  43877. }
  43878. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43879. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43880. return false;
  43881. }
  43882. }
  43883. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43884. if (this._metallicTexture) {
  43885. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43886. return false;
  43887. }
  43888. }
  43889. else if (this._reflectivityTexture) {
  43890. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43891. return false;
  43892. }
  43893. }
  43894. if (this._microSurfaceTexture) {
  43895. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43896. return false;
  43897. }
  43898. }
  43899. }
  43900. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43901. // Bump texture cannot be not blocking.
  43902. if (!this._bumpTexture.isReady()) {
  43903. return false;
  43904. }
  43905. }
  43906. var refractionTexture = this._getRefractionTexture();
  43907. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43908. if (!refractionTexture.isReadyOrNotBlocking()) {
  43909. return false;
  43910. }
  43911. }
  43912. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43913. // This is blocking.
  43914. if (!this._environmentBRDFTexture.isReady()) {
  43915. return false;
  43916. }
  43917. }
  43918. }
  43919. }
  43920. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43921. if (!this._imageProcessingConfiguration.isReady()) {
  43922. return false;
  43923. }
  43924. }
  43925. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43926. mesh.createNormals(true);
  43927. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43928. }
  43929. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43930. if (effect) {
  43931. scene.resetCachedMaterial();
  43932. subMesh.setEffect(effect, defines);
  43933. this.buildUniformLayout();
  43934. }
  43935. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43936. return false;
  43937. }
  43938. defines._renderId = scene.getRenderId();
  43939. this._wasPreviouslyReady = true;
  43940. return true;
  43941. };
  43942. /**
  43943. * Specifies if the material uses metallic roughness workflow.
  43944. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43945. */
  43946. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43947. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43948. return true;
  43949. }
  43950. return false;
  43951. };
  43952. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43953. if (onCompiled === void 0) { onCompiled = null; }
  43954. if (onError === void 0) { onError = null; }
  43955. if (useInstances === void 0) { useInstances = null; }
  43956. if (useClipPlane === void 0) { useClipPlane = null; }
  43957. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43958. if (!defines.isDirty) {
  43959. return null;
  43960. }
  43961. defines.markAsProcessed();
  43962. var scene = this.getScene();
  43963. var engine = scene.getEngine();
  43964. // Fallbacks
  43965. var fallbacks = new BABYLON.EffectFallbacks();
  43966. var fallbackRank = 0;
  43967. if (defines.USESPHERICALINVERTEX) {
  43968. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43969. }
  43970. if (defines.FOG) {
  43971. fallbacks.addFallback(fallbackRank, "FOG");
  43972. }
  43973. if (defines.SPECULARAA) {
  43974. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43975. }
  43976. if (defines.POINTSIZE) {
  43977. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43978. }
  43979. if (defines.LOGARITHMICDEPTH) {
  43980. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43981. }
  43982. if (defines.PARALLAX) {
  43983. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43984. }
  43985. if (defines.PARALLAXOCCLUSION) {
  43986. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43987. }
  43988. if (defines.ENVIRONMENTBRDF) {
  43989. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43990. }
  43991. if (defines.TANGENT) {
  43992. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43993. }
  43994. if (defines.BUMP) {
  43995. fallbacks.addFallback(fallbackRank++, "BUMP");
  43996. }
  43997. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43998. if (defines.SPECULARTERM) {
  43999. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44000. }
  44001. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44002. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44003. }
  44004. if (defines.LIGHTMAP) {
  44005. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44006. }
  44007. if (defines.NORMAL) {
  44008. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44009. }
  44010. if (defines.AMBIENT) {
  44011. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44012. }
  44013. if (defines.EMISSIVE) {
  44014. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44015. }
  44016. if (defines.VERTEXCOLOR) {
  44017. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44018. }
  44019. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44020. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44021. }
  44022. if (defines.MORPHTARGETS) {
  44023. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44024. }
  44025. //Attributes
  44026. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44027. if (defines.NORMAL) {
  44028. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44029. }
  44030. if (defines.TANGENT) {
  44031. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44032. }
  44033. if (defines.UV1) {
  44034. attribs.push(BABYLON.VertexBuffer.UVKind);
  44035. }
  44036. if (defines.UV2) {
  44037. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44038. }
  44039. if (defines.VERTEXCOLOR) {
  44040. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44041. }
  44042. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44043. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44044. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44045. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44046. "vFogInfos", "vFogColor", "pointSize",
  44047. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44048. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44049. "mBones",
  44050. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44051. "vLightingIntensity",
  44052. "logarithmicDepthConstant",
  44053. "vSphericalX", "vSphericalY", "vSphericalZ",
  44054. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44055. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44056. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44057. "vTangentSpaceParams"
  44058. ];
  44059. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44060. "bumpSampler", "lightmapSampler", "opacitySampler",
  44061. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44062. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44063. "microSurfaceSampler", "environmentBrdfSampler"];
  44064. var uniformBuffers = ["Material", "Scene"];
  44065. if (BABYLON.ImageProcessingConfiguration) {
  44066. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44067. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44068. }
  44069. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44070. uniformsNames: uniforms,
  44071. uniformBuffersNames: uniformBuffers,
  44072. samplers: samplers,
  44073. defines: defines,
  44074. maxSimultaneousLights: this._maxSimultaneousLights
  44075. });
  44076. var join = defines.toString();
  44077. return engine.createEffect("pbr", {
  44078. attributes: attribs,
  44079. uniformsNames: uniforms,
  44080. uniformBuffersNames: uniformBuffers,
  44081. samplers: samplers,
  44082. defines: join,
  44083. fallbacks: fallbacks,
  44084. onCompiled: onCompiled,
  44085. onError: onError,
  44086. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44087. }, engine);
  44088. };
  44089. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44090. if (useInstances === void 0) { useInstances = null; }
  44091. if (useClipPlane === void 0) { useClipPlane = null; }
  44092. var scene = this.getScene();
  44093. var engine = scene.getEngine();
  44094. // Lights
  44095. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44096. defines._needNormals = true;
  44097. // Textures
  44098. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44099. if (defines._areTexturesDirty) {
  44100. defines._needUVs = false;
  44101. if (scene.texturesEnabled) {
  44102. if (scene.getEngine().getCaps().textureLOD) {
  44103. defines.LODBASEDMICROSFURACE = true;
  44104. }
  44105. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44106. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44107. }
  44108. else {
  44109. defines.ALBEDO = false;
  44110. }
  44111. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44113. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44114. }
  44115. else {
  44116. defines.AMBIENT = false;
  44117. }
  44118. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44119. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44120. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44121. }
  44122. else {
  44123. defines.OPACITY = false;
  44124. }
  44125. var reflectionTexture = this._getReflectionTexture();
  44126. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44127. defines.REFLECTION = true;
  44128. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44129. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44130. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44131. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44132. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44133. defines.INVERTCUBICMAP = true;
  44134. }
  44135. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44136. switch (reflectionTexture.coordinatesMode) {
  44137. case BABYLON.Texture.EXPLICIT_MODE:
  44138. defines.REFLECTIONMAP_EXPLICIT = true;
  44139. break;
  44140. case BABYLON.Texture.PLANAR_MODE:
  44141. defines.REFLECTIONMAP_PLANAR = true;
  44142. break;
  44143. case BABYLON.Texture.PROJECTION_MODE:
  44144. defines.REFLECTIONMAP_PROJECTION = true;
  44145. break;
  44146. case BABYLON.Texture.SKYBOX_MODE:
  44147. defines.REFLECTIONMAP_SKYBOX = true;
  44148. break;
  44149. case BABYLON.Texture.SPHERICAL_MODE:
  44150. defines.REFLECTIONMAP_SPHERICAL = true;
  44151. break;
  44152. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44153. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44154. break;
  44155. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44156. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44157. break;
  44158. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44159. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44160. break;
  44161. case BABYLON.Texture.CUBIC_MODE:
  44162. case BABYLON.Texture.INVCUBIC_MODE:
  44163. default:
  44164. defines.REFLECTIONMAP_CUBIC = true;
  44165. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44166. break;
  44167. }
  44168. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44169. if (reflectionTexture.sphericalPolynomial) {
  44170. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44171. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44172. defines.USESPHERICALINVERTEX = false;
  44173. }
  44174. else {
  44175. defines.USESPHERICALINVERTEX = true;
  44176. }
  44177. }
  44178. }
  44179. else {
  44180. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44181. }
  44182. }
  44183. else {
  44184. defines.REFLECTION = false;
  44185. defines.REFLECTIONMAP_3D = false;
  44186. defines.REFLECTIONMAP_SPHERICAL = false;
  44187. defines.REFLECTIONMAP_PLANAR = false;
  44188. defines.REFLECTIONMAP_CUBIC = false;
  44189. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44190. defines.REFLECTIONMAP_PROJECTION = false;
  44191. defines.REFLECTIONMAP_SKYBOX = false;
  44192. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44193. defines.REFLECTIONMAP_EXPLICIT = false;
  44194. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44195. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44196. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44197. defines.INVERTCUBICMAP = false;
  44198. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44199. defines.USESPHERICALINVERTEX = false;
  44200. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44201. defines.LODINREFLECTIONALPHA = false;
  44202. defines.GAMMAREFLECTION = false;
  44203. defines.RGBDREFLECTION = false;
  44204. }
  44205. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44206. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44207. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44208. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44209. }
  44210. else {
  44211. defines.LIGHTMAP = false;
  44212. }
  44213. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44215. }
  44216. else {
  44217. defines.EMISSIVE = false;
  44218. }
  44219. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44220. if (this._metallicTexture) {
  44221. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44222. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44223. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44224. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44225. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44226. }
  44227. else if (this._reflectivityTexture) {
  44228. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44229. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44230. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44231. }
  44232. else {
  44233. defines.REFLECTIVITY = false;
  44234. }
  44235. if (this._microSurfaceTexture) {
  44236. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44237. }
  44238. else {
  44239. defines.MICROSURFACEMAP = false;
  44240. }
  44241. }
  44242. else {
  44243. defines.REFLECTIVITY = false;
  44244. defines.MICROSURFACEMAP = false;
  44245. }
  44246. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44247. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44248. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44249. defines.PARALLAX = true;
  44250. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44251. }
  44252. else {
  44253. defines.PARALLAX = false;
  44254. }
  44255. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44256. }
  44257. else {
  44258. defines.BUMP = false;
  44259. }
  44260. var refractionTexture = this._getRefractionTexture();
  44261. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44262. defines.REFRACTION = true;
  44263. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44264. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44265. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44266. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44267. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44268. if (this._linkRefractionWithTransparency) {
  44269. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44270. }
  44271. }
  44272. else {
  44273. defines.REFRACTION = false;
  44274. }
  44275. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44276. defines.ENVIRONMENTBRDF = true;
  44277. }
  44278. else {
  44279. defines.ENVIRONMENTBRDF = false;
  44280. }
  44281. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44282. defines.ALPHAFROMALBEDO = true;
  44283. }
  44284. else {
  44285. defines.ALPHAFROMALBEDO = false;
  44286. }
  44287. }
  44288. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44289. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44290. defines.USEPHYSICALLIGHTFALLOFF = false;
  44291. defines.USEGLTFLIGHTFALLOFF = false;
  44292. }
  44293. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44294. defines.USEPHYSICALLIGHTFALLOFF = false;
  44295. defines.USEGLTFLIGHTFALLOFF = true;
  44296. }
  44297. else {
  44298. defines.USEPHYSICALLIGHTFALLOFF = true;
  44299. defines.USEGLTFLIGHTFALLOFF = false;
  44300. }
  44301. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44302. if (!this.backFaceCulling && this._twoSidedLighting) {
  44303. defines.TWOSIDEDLIGHTING = true;
  44304. }
  44305. else {
  44306. defines.TWOSIDEDLIGHTING = false;
  44307. }
  44308. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44309. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44310. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44311. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44312. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44313. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44314. }
  44315. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44316. this._imageProcessingConfiguration.prepareDefines(defines);
  44317. }
  44318. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44319. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44320. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44321. // Misc.
  44322. if (defines._areMiscDirty) {
  44323. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44324. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44325. }
  44326. // Values that need to be evaluated on every frame
  44327. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44328. // Attribs
  44329. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44330. };
  44331. /**
  44332. * Force shader compilation
  44333. */
  44334. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44335. var _this = this;
  44336. var localOptions = __assign({ clipPlane: false }, options);
  44337. var defines = new PBRMaterialDefines();
  44338. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44339. if (effect.isReady()) {
  44340. if (onCompiled) {
  44341. onCompiled(this);
  44342. }
  44343. }
  44344. else {
  44345. effect.onCompileObservable.add(function () {
  44346. if (onCompiled) {
  44347. onCompiled(_this);
  44348. }
  44349. });
  44350. }
  44351. };
  44352. /**
  44353. * Initializes the uniform buffer layout for the shader.
  44354. */
  44355. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44356. // Order is important !
  44357. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44358. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44359. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44360. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44361. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44362. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44363. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44364. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44365. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44366. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44367. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44368. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44369. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44370. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44371. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44372. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44373. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44374. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44375. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44376. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44377. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44378. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44379. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44380. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44381. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44382. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44383. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44384. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44385. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44386. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44387. this._uniformBuffer.addUniform("pointSize", 1);
  44388. this._uniformBuffer.create();
  44389. };
  44390. /**
  44391. * Unbinds the textures.
  44392. */
  44393. PBRBaseMaterial.prototype.unbind = function () {
  44394. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44395. this._uniformBuffer.setTexture("reflectionSampler", null);
  44396. }
  44397. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44398. this._uniformBuffer.setTexture("refractionSampler", null);
  44399. }
  44400. _super.prototype.unbind.call(this);
  44401. };
  44402. /**
  44403. * Binds the submesh data.
  44404. * @param world - The world matrix.
  44405. * @param mesh - The BJS mesh.
  44406. * @param subMesh - A submesh of the BJS mesh.
  44407. */
  44408. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44409. var scene = this.getScene();
  44410. var defines = subMesh._materialDefines;
  44411. if (!defines) {
  44412. return;
  44413. }
  44414. var effect = subMesh.effect;
  44415. if (!effect) {
  44416. return;
  44417. }
  44418. this._activeEffect = effect;
  44419. // Matrices
  44420. this.bindOnlyWorldMatrix(world);
  44421. // Normal Matrix
  44422. if (defines.OBJECTSPACE_NORMALMAP) {
  44423. world.toNormalMatrix(this._normalMatrix);
  44424. this.bindOnlyNormalMatrix(this._normalMatrix);
  44425. }
  44426. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44427. // Bones
  44428. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44429. var reflectionTexture = null;
  44430. if (mustRebind) {
  44431. this._uniformBuffer.bindToEffect(effect, "Material");
  44432. this.bindViewProjection(effect);
  44433. reflectionTexture = this._getReflectionTexture();
  44434. var refractionTexture = this._getRefractionTexture();
  44435. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44436. // Texture uniforms
  44437. if (scene.texturesEnabled) {
  44438. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44439. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44440. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44441. }
  44442. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44443. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44444. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44445. }
  44446. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44447. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44448. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44449. }
  44450. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44451. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44452. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44453. if (reflectionTexture.boundingBoxSize) {
  44454. var cubeTexture = reflectionTexture;
  44455. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44456. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44457. }
  44458. var polynomials = reflectionTexture.sphericalPolynomial;
  44459. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44460. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44461. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44462. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44463. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44464. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44465. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44466. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44467. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44468. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44469. }
  44470. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44471. }
  44472. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44473. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44474. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44475. }
  44476. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44477. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44478. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44479. }
  44480. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44481. if (this._metallicTexture) {
  44482. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44483. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44484. }
  44485. else if (this._reflectivityTexture) {
  44486. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44487. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44488. }
  44489. if (this._microSurfaceTexture) {
  44490. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44491. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44492. }
  44493. }
  44494. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44495. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44496. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44497. if (scene._mirroredCameraPosition) {
  44498. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44499. }
  44500. else {
  44501. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44502. }
  44503. }
  44504. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44505. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44506. var depth = 1.0;
  44507. if (!refractionTexture.isCube) {
  44508. if (refractionTexture.depth) {
  44509. depth = refractionTexture.depth;
  44510. }
  44511. }
  44512. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44513. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44514. }
  44515. }
  44516. // Point size
  44517. if (this.pointsCloud) {
  44518. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44519. }
  44520. // Colors
  44521. if (defines.METALLICWORKFLOW) {
  44522. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44523. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44524. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44525. }
  44526. else {
  44527. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44528. }
  44529. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44530. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44531. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44532. // Misc
  44533. this._lightingInfos.x = this._directIntensity;
  44534. this._lightingInfos.y = this._emissiveIntensity;
  44535. this._lightingInfos.z = this._environmentIntensity;
  44536. this._lightingInfos.w = this._specularIntensity;
  44537. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44538. }
  44539. // Textures
  44540. if (scene.texturesEnabled) {
  44541. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44542. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44543. }
  44544. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44545. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44546. }
  44547. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44548. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44549. }
  44550. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44551. if (defines.LODBASEDMICROSFURACE) {
  44552. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44553. }
  44554. else {
  44555. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44556. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44557. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44558. }
  44559. }
  44560. if (defines.ENVIRONMENTBRDF) {
  44561. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44562. }
  44563. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44564. if (defines.LODBASEDMICROSFURACE) {
  44565. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44566. }
  44567. else {
  44568. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44569. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44570. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44571. }
  44572. }
  44573. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44574. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44575. }
  44576. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44577. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44578. }
  44579. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44580. if (this._metallicTexture) {
  44581. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44582. }
  44583. else if (this._reflectivityTexture) {
  44584. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44585. }
  44586. if (this._microSurfaceTexture) {
  44587. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44588. }
  44589. }
  44590. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44591. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44592. }
  44593. }
  44594. // Clip plane
  44595. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44596. // Colors
  44597. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44598. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44599. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44600. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44601. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44602. }
  44603. if (mustRebind || !this.isFrozen) {
  44604. // Lights
  44605. if (scene.lightsEnabled && !this._disableLighting) {
  44606. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44607. }
  44608. // View
  44609. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44610. this.bindView(effect);
  44611. }
  44612. // Fog
  44613. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44614. // Morph targets
  44615. if (defines.NUM_MORPH_INFLUENCERS) {
  44616. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44617. }
  44618. // image processing
  44619. this._imageProcessingConfiguration.bind(this._activeEffect);
  44620. // Log. depth
  44621. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44622. }
  44623. this._uniformBuffer.update();
  44624. this._afterBind(mesh, this._activeEffect);
  44625. };
  44626. /**
  44627. * Returns the animatable textures.
  44628. * @returns - Array of animatable textures.
  44629. */
  44630. PBRBaseMaterial.prototype.getAnimatables = function () {
  44631. var results = [];
  44632. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44633. results.push(this._albedoTexture);
  44634. }
  44635. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44636. results.push(this._ambientTexture);
  44637. }
  44638. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44639. results.push(this._opacityTexture);
  44640. }
  44641. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44642. results.push(this._reflectionTexture);
  44643. }
  44644. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44645. results.push(this._emissiveTexture);
  44646. }
  44647. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44648. results.push(this._metallicTexture);
  44649. }
  44650. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44651. results.push(this._reflectivityTexture);
  44652. }
  44653. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44654. results.push(this._bumpTexture);
  44655. }
  44656. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44657. results.push(this._lightmapTexture);
  44658. }
  44659. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44660. results.push(this._refractionTexture);
  44661. }
  44662. return results;
  44663. };
  44664. /**
  44665. * Returns the texture used for reflections.
  44666. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44667. */
  44668. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44669. if (this._reflectionTexture) {
  44670. return this._reflectionTexture;
  44671. }
  44672. return this.getScene().environmentTexture;
  44673. };
  44674. /**
  44675. * Returns the texture used for refraction or null if none is used.
  44676. * @returns - Refection texture if present. If no refraction texture and refraction
  44677. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44678. */
  44679. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44680. if (this._refractionTexture) {
  44681. return this._refractionTexture;
  44682. }
  44683. if (this._linkRefractionWithTransparency) {
  44684. return this.getScene().environmentTexture;
  44685. }
  44686. return null;
  44687. };
  44688. /**
  44689. * Disposes the resources of the material.
  44690. * @param forceDisposeEffect - Forces the disposal of effects.
  44691. * @param forceDisposeTextures - Forces the disposal of all textures.
  44692. */
  44693. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44694. if (forceDisposeTextures) {
  44695. if (this._albedoTexture) {
  44696. this._albedoTexture.dispose();
  44697. }
  44698. if (this._ambientTexture) {
  44699. this._ambientTexture.dispose();
  44700. }
  44701. if (this._opacityTexture) {
  44702. this._opacityTexture.dispose();
  44703. }
  44704. if (this._reflectionTexture) {
  44705. this._reflectionTexture.dispose();
  44706. }
  44707. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44708. this._environmentBRDFTexture.dispose();
  44709. }
  44710. if (this._emissiveTexture) {
  44711. this._emissiveTexture.dispose();
  44712. }
  44713. if (this._metallicTexture) {
  44714. this._metallicTexture.dispose();
  44715. }
  44716. if (this._reflectivityTexture) {
  44717. this._reflectivityTexture.dispose();
  44718. }
  44719. if (this._bumpTexture) {
  44720. this._bumpTexture.dispose();
  44721. }
  44722. if (this._lightmapTexture) {
  44723. this._lightmapTexture.dispose();
  44724. }
  44725. if (this._refractionTexture) {
  44726. this._refractionTexture.dispose();
  44727. }
  44728. }
  44729. this._renderTargets.dispose();
  44730. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44731. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44732. }
  44733. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44734. };
  44735. /**
  44736. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44737. */
  44738. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44739. /**
  44740. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44741. * to enhance interoperability with other engines.
  44742. */
  44743. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44744. /**
  44745. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44746. * to enhance interoperability with other materials.
  44747. */
  44748. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44749. /**
  44750. * Stores the reflectivity values based on metallic roughness workflow.
  44751. */
  44752. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44753. __decorate([
  44754. BABYLON.serializeAsImageProcessingConfiguration()
  44755. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44756. __decorate([
  44757. BABYLON.serialize()
  44758. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44759. __decorate([
  44760. BABYLON.serialize()
  44761. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44762. return PBRBaseMaterial;
  44763. }(BABYLON.PushMaterial));
  44764. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44765. })(BABYLON || (BABYLON = {}));
  44766. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44767. var BABYLON;
  44768. (function (BABYLON) {
  44769. /**
  44770. * The Physically based simple base material of BJS.
  44771. *
  44772. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44773. * It is used as the base class for both the specGloss and metalRough conventions.
  44774. */
  44775. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44776. __extends(PBRBaseSimpleMaterial, _super);
  44777. /**
  44778. * Instantiates a new PBRMaterial instance.
  44779. *
  44780. * @param name The material name
  44781. * @param scene The scene the material will be use in.
  44782. */
  44783. function PBRBaseSimpleMaterial(name, scene) {
  44784. var _this = _super.call(this, name, scene) || this;
  44785. /**
  44786. * Number of Simultaneous lights allowed on the material.
  44787. */
  44788. _this.maxSimultaneousLights = 4;
  44789. /**
  44790. * If sets to true, disables all the lights affecting the material.
  44791. */
  44792. _this.disableLighting = false;
  44793. /**
  44794. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44795. */
  44796. _this.invertNormalMapX = false;
  44797. /**
  44798. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44799. */
  44800. _this.invertNormalMapY = false;
  44801. /**
  44802. * Emissivie color used to self-illuminate the model.
  44803. */
  44804. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44805. /**
  44806. * Occlusion Channel Strenght.
  44807. */
  44808. _this.occlusionStrength = 1.0;
  44809. _this.useLightmapAsShadowmap = false;
  44810. _this._useAlphaFromAlbedoTexture = true;
  44811. _this._useAmbientInGrayScale = true;
  44812. return _this;
  44813. }
  44814. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44815. /**
  44816. * Gets the current double sided mode.
  44817. */
  44818. get: function () {
  44819. return this._twoSidedLighting;
  44820. },
  44821. /**
  44822. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44823. */
  44824. set: function (value) {
  44825. if (this._twoSidedLighting === value) {
  44826. return;
  44827. }
  44828. this._twoSidedLighting = value;
  44829. this.backFaceCulling = !value;
  44830. this._markAllSubMeshesAsTexturesDirty();
  44831. },
  44832. enumerable: true,
  44833. configurable: true
  44834. });
  44835. /**
  44836. * Return the active textures of the material.
  44837. */
  44838. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44839. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44840. if (this.environmentTexture) {
  44841. activeTextures.push(this.environmentTexture);
  44842. }
  44843. if (this.normalTexture) {
  44844. activeTextures.push(this.normalTexture);
  44845. }
  44846. if (this.emissiveTexture) {
  44847. activeTextures.push(this.emissiveTexture);
  44848. }
  44849. if (this.occlusionTexture) {
  44850. activeTextures.push(this.occlusionTexture);
  44851. }
  44852. if (this.lightmapTexture) {
  44853. activeTextures.push(this.lightmapTexture);
  44854. }
  44855. return activeTextures;
  44856. };
  44857. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44858. if (_super.prototype.hasTexture.call(this, texture)) {
  44859. return true;
  44860. }
  44861. if (this.lightmapTexture === texture) {
  44862. return true;
  44863. }
  44864. return false;
  44865. };
  44866. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44867. return "PBRBaseSimpleMaterial";
  44868. };
  44869. __decorate([
  44870. BABYLON.serialize(),
  44871. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44872. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44873. __decorate([
  44874. BABYLON.serialize(),
  44875. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44876. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44877. __decorate([
  44878. BABYLON.serializeAsTexture(),
  44879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44880. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44881. __decorate([
  44882. BABYLON.serialize(),
  44883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44884. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44885. __decorate([
  44886. BABYLON.serialize(),
  44887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44888. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44889. __decorate([
  44890. BABYLON.serializeAsTexture(),
  44891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44892. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44893. __decorate([
  44894. BABYLON.serializeAsColor3("emissive"),
  44895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44896. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44897. __decorate([
  44898. BABYLON.serializeAsTexture(),
  44899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44900. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44901. __decorate([
  44902. BABYLON.serialize(),
  44903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44904. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44905. __decorate([
  44906. BABYLON.serializeAsTexture(),
  44907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44908. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44909. __decorate([
  44910. BABYLON.serialize(),
  44911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44912. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44913. __decorate([
  44914. BABYLON.serialize()
  44915. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44916. __decorate([
  44917. BABYLON.serializeAsTexture(),
  44918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44919. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44920. __decorate([
  44921. BABYLON.serialize(),
  44922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44923. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44924. return PBRBaseSimpleMaterial;
  44925. }(BABYLON.PBRBaseMaterial));
  44926. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44927. })(BABYLON || (BABYLON = {}));
  44928. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44929. var BABYLON;
  44930. (function (BABYLON) {
  44931. /**
  44932. * The Physically based material of BJS.
  44933. *
  44934. * This offers the main features of a standard PBR material.
  44935. * For more information, please refer to the documentation :
  44936. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44937. */
  44938. var PBRMaterial = /** @class */ (function (_super) {
  44939. __extends(PBRMaterial, _super);
  44940. /**
  44941. * Instantiates a new PBRMaterial instance.
  44942. *
  44943. * @param name The material name
  44944. * @param scene The scene the material will be use in.
  44945. */
  44946. function PBRMaterial(name, scene) {
  44947. var _this = _super.call(this, name, scene) || this;
  44948. /**
  44949. * Intensity of the direct lights e.g. the four lights available in your scene.
  44950. * This impacts both the direct diffuse and specular highlights.
  44951. */
  44952. _this.directIntensity = 1.0;
  44953. /**
  44954. * Intensity of the emissive part of the material.
  44955. * This helps controlling the emissive effect without modifying the emissive color.
  44956. */
  44957. _this.emissiveIntensity = 1.0;
  44958. /**
  44959. * Intensity of the environment e.g. how much the environment will light the object
  44960. * either through harmonics for rough material or through the refelction for shiny ones.
  44961. */
  44962. _this.environmentIntensity = 1.0;
  44963. /**
  44964. * This is a special control allowing the reduction of the specular highlights coming from the
  44965. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44966. */
  44967. _this.specularIntensity = 1.0;
  44968. /**
  44969. * Debug Control allowing disabling the bump map on this material.
  44970. */
  44971. _this.disableBumpMap = false;
  44972. /**
  44973. * AKA Occlusion Texture Intensity in other nomenclature.
  44974. */
  44975. _this.ambientTextureStrength = 1.0;
  44976. /**
  44977. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44978. * 1 means it completely occludes it
  44979. * 0 mean it has no impact
  44980. */
  44981. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44982. /**
  44983. * The color of a material in ambient lighting.
  44984. */
  44985. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44986. /**
  44987. * AKA Diffuse Color in other nomenclature.
  44988. */
  44989. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44990. /**
  44991. * AKA Specular Color in other nomenclature.
  44992. */
  44993. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44994. /**
  44995. * The color reflected from the material.
  44996. */
  44997. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44998. /**
  44999. * The color emitted from the material.
  45000. */
  45001. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45002. /**
  45003. * AKA Glossiness in other nomenclature.
  45004. */
  45005. _this.microSurface = 1.0;
  45006. /**
  45007. * source material index of refraction (IOR)' / 'destination material IOR.
  45008. */
  45009. _this.indexOfRefraction = 0.66;
  45010. /**
  45011. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45012. */
  45013. _this.invertRefractionY = false;
  45014. /**
  45015. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45016. * Materials half opaque for instance using refraction could benefit from this control.
  45017. */
  45018. _this.linkRefractionWithTransparency = false;
  45019. _this.useLightmapAsShadowmap = false;
  45020. /**
  45021. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45022. */
  45023. _this.useAlphaFromAlbedoTexture = false;
  45024. /**
  45025. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45026. */
  45027. _this.forceAlphaTest = false;
  45028. /**
  45029. * Defines the alpha limits in alpha test mode.
  45030. */
  45031. _this.alphaCutOff = 0.4;
  45032. /**
  45033. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45034. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45035. */
  45036. _this.useSpecularOverAlpha = true;
  45037. /**
  45038. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45039. */
  45040. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45041. /**
  45042. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45043. */
  45044. _this.useRoughnessFromMetallicTextureAlpha = true;
  45045. /**
  45046. * Specifies if the metallic texture contains the roughness information in its green channel.
  45047. */
  45048. _this.useRoughnessFromMetallicTextureGreen = false;
  45049. /**
  45050. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45051. */
  45052. _this.useMetallnessFromMetallicTextureBlue = false;
  45053. /**
  45054. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45055. */
  45056. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45057. /**
  45058. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45059. */
  45060. _this.useAmbientInGrayScale = false;
  45061. /**
  45062. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45063. * The material will try to infer what glossiness each pixel should be.
  45064. */
  45065. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45066. /**
  45067. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45068. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45069. */
  45070. _this.useRadianceOverAlpha = true;
  45071. /**
  45072. * Allows using an object space normal map (instead of tangent space).
  45073. */
  45074. _this.useObjectSpaceNormalMap = false;
  45075. /**
  45076. * Allows using the bump map in parallax mode.
  45077. */
  45078. _this.useParallax = false;
  45079. /**
  45080. * Allows using the bump map in parallax occlusion mode.
  45081. */
  45082. _this.useParallaxOcclusion = false;
  45083. /**
  45084. * Controls the scale bias of the parallax mode.
  45085. */
  45086. _this.parallaxScaleBias = 0.05;
  45087. /**
  45088. * If sets to true, disables all the lights affecting the material.
  45089. */
  45090. _this.disableLighting = false;
  45091. /**
  45092. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45093. */
  45094. _this.forceIrradianceInFragment = false;
  45095. /**
  45096. * Number of Simultaneous lights allowed on the material.
  45097. */
  45098. _this.maxSimultaneousLights = 4;
  45099. /**
  45100. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45101. */
  45102. _this.invertNormalMapX = false;
  45103. /**
  45104. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45105. */
  45106. _this.invertNormalMapY = false;
  45107. /**
  45108. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45109. */
  45110. _this.twoSidedLighting = false;
  45111. /**
  45112. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45113. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45114. */
  45115. _this.useAlphaFresnel = false;
  45116. /**
  45117. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45118. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45119. */
  45120. _this.useLinearAlphaFresnel = false;
  45121. /**
  45122. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45123. * And/Or occlude the blended part.
  45124. */
  45125. _this.environmentBRDFTexture = null;
  45126. /**
  45127. * Force normal to face away from face.
  45128. */
  45129. _this.forceNormalForward = false;
  45130. /**
  45131. * Enables specular anti aliasing in the PBR shader.
  45132. * It will both interacts on the Geometry for analytical and IBL lighting.
  45133. * It also prefilter the roughness map based on the bump values.
  45134. */
  45135. _this.enableSpecularAntiAliasing = false;
  45136. /**
  45137. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45138. * makes the reflect vector face the model (under horizon).
  45139. */
  45140. _this.useHorizonOcclusion = true;
  45141. /**
  45142. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45143. * too much the area relying on ambient texture to define their ambient occlusion.
  45144. */
  45145. _this.useRadianceOcclusion = true;
  45146. /**
  45147. * If set to true, no lighting calculations will be applied.
  45148. */
  45149. _this.unlit = false;
  45150. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45151. return _this;
  45152. }
  45153. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45154. /**
  45155. * BJS is using an harcoded light falloff based on a manually sets up range.
  45156. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45157. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45158. */
  45159. get: function () {
  45160. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45161. },
  45162. /**
  45163. * BJS is using an harcoded light falloff based on a manually sets up range.
  45164. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45165. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45166. */
  45167. set: function (value) {
  45168. if (value !== this.usePhysicalLightFalloff) {
  45169. // Ensure the effect will be rebuilt.
  45170. this._markAllSubMeshesAsTexturesDirty();
  45171. if (value) {
  45172. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45173. }
  45174. else {
  45175. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45176. }
  45177. }
  45178. },
  45179. enumerable: true,
  45180. configurable: true
  45181. });
  45182. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45183. /**
  45184. * In order to support the falloff compatibility with gltf, a special mode has been added
  45185. * to reproduce the gltf light falloff.
  45186. */
  45187. get: function () {
  45188. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45189. },
  45190. /**
  45191. * In order to support the falloff compatibility with gltf, a special mode has been added
  45192. * to reproduce the gltf light falloff.
  45193. */
  45194. set: function (value) {
  45195. if (value !== this.useGLTFLightFalloff) {
  45196. // Ensure the effect will be rebuilt.
  45197. this._markAllSubMeshesAsTexturesDirty();
  45198. if (value) {
  45199. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45200. }
  45201. else {
  45202. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45203. }
  45204. }
  45205. },
  45206. enumerable: true,
  45207. configurable: true
  45208. });
  45209. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45210. /**
  45211. * Gets the image processing configuration used either in this material.
  45212. */
  45213. get: function () {
  45214. return this._imageProcessingConfiguration;
  45215. },
  45216. /**
  45217. * Sets the Default image processing configuration used either in the this material.
  45218. *
  45219. * If sets to null, the scene one is in use.
  45220. */
  45221. set: function (value) {
  45222. this._attachImageProcessingConfiguration(value);
  45223. // Ensure the effect will be rebuilt.
  45224. this._markAllSubMeshesAsTexturesDirty();
  45225. },
  45226. enumerable: true,
  45227. configurable: true
  45228. });
  45229. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45230. /**
  45231. * Gets wether the color curves effect is enabled.
  45232. */
  45233. get: function () {
  45234. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45235. },
  45236. /**
  45237. * Sets wether the color curves effect is enabled.
  45238. */
  45239. set: function (value) {
  45240. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45241. },
  45242. enumerable: true,
  45243. configurable: true
  45244. });
  45245. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45246. /**
  45247. * Gets wether the color grading effect is enabled.
  45248. */
  45249. get: function () {
  45250. return this.imageProcessingConfiguration.colorGradingEnabled;
  45251. },
  45252. /**
  45253. * Gets wether the color grading effect is enabled.
  45254. */
  45255. set: function (value) {
  45256. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45257. },
  45258. enumerable: true,
  45259. configurable: true
  45260. });
  45261. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45262. /**
  45263. * Gets wether tonemapping is enabled or not.
  45264. */
  45265. get: function () {
  45266. return this._imageProcessingConfiguration.toneMappingEnabled;
  45267. },
  45268. /**
  45269. * Sets wether tonemapping is enabled or not
  45270. */
  45271. set: function (value) {
  45272. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45273. },
  45274. enumerable: true,
  45275. configurable: true
  45276. });
  45277. ;
  45278. ;
  45279. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45280. /**
  45281. * The camera exposure used on this material.
  45282. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45283. * This corresponds to a photographic exposure.
  45284. */
  45285. get: function () {
  45286. return this._imageProcessingConfiguration.exposure;
  45287. },
  45288. /**
  45289. * The camera exposure used on this material.
  45290. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45291. * This corresponds to a photographic exposure.
  45292. */
  45293. set: function (value) {
  45294. this._imageProcessingConfiguration.exposure = value;
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. ;
  45300. ;
  45301. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45302. /**
  45303. * Gets The camera contrast used on this material.
  45304. */
  45305. get: function () {
  45306. return this._imageProcessingConfiguration.contrast;
  45307. },
  45308. /**
  45309. * Sets The camera contrast used on this material.
  45310. */
  45311. set: function (value) {
  45312. this._imageProcessingConfiguration.contrast = value;
  45313. },
  45314. enumerable: true,
  45315. configurable: true
  45316. });
  45317. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45318. /**
  45319. * Gets the Color Grading 2D Lookup Texture.
  45320. */
  45321. get: function () {
  45322. return this._imageProcessingConfiguration.colorGradingTexture;
  45323. },
  45324. /**
  45325. * Sets the Color Grading 2D Lookup Texture.
  45326. */
  45327. set: function (value) {
  45328. this._imageProcessingConfiguration.colorGradingTexture = value;
  45329. },
  45330. enumerable: true,
  45331. configurable: true
  45332. });
  45333. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45334. /**
  45335. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45336. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45337. * 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;
  45338. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45339. */
  45340. get: function () {
  45341. return this._imageProcessingConfiguration.colorCurves;
  45342. },
  45343. /**
  45344. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45345. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45346. * 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;
  45347. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45348. */
  45349. set: function (value) {
  45350. this._imageProcessingConfiguration.colorCurves = value;
  45351. },
  45352. enumerable: true,
  45353. configurable: true
  45354. });
  45355. /**
  45356. * Returns the name of this material class.
  45357. */
  45358. PBRMaterial.prototype.getClassName = function () {
  45359. return "PBRMaterial";
  45360. };
  45361. /**
  45362. * Returns an array of the actively used textures.
  45363. * @returns - Array of BaseTextures
  45364. */
  45365. PBRMaterial.prototype.getActiveTextures = function () {
  45366. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45367. if (this._albedoTexture) {
  45368. activeTextures.push(this._albedoTexture);
  45369. }
  45370. if (this._ambientTexture) {
  45371. activeTextures.push(this._ambientTexture);
  45372. }
  45373. if (this._opacityTexture) {
  45374. activeTextures.push(this._opacityTexture);
  45375. }
  45376. if (this._reflectionTexture) {
  45377. activeTextures.push(this._reflectionTexture);
  45378. }
  45379. if (this._emissiveTexture) {
  45380. activeTextures.push(this._emissiveTexture);
  45381. }
  45382. if (this._reflectivityTexture) {
  45383. activeTextures.push(this._reflectivityTexture);
  45384. }
  45385. if (this._metallicTexture) {
  45386. activeTextures.push(this._metallicTexture);
  45387. }
  45388. if (this._microSurfaceTexture) {
  45389. activeTextures.push(this._microSurfaceTexture);
  45390. }
  45391. if (this._bumpTexture) {
  45392. activeTextures.push(this._bumpTexture);
  45393. }
  45394. if (this._lightmapTexture) {
  45395. activeTextures.push(this._lightmapTexture);
  45396. }
  45397. if (this._refractionTexture) {
  45398. activeTextures.push(this._refractionTexture);
  45399. }
  45400. return activeTextures;
  45401. };
  45402. /**
  45403. * Checks to see if a texture is used in the material.
  45404. * @param texture - Base texture to use.
  45405. * @returns - Boolean specifying if a texture is used in the material.
  45406. */
  45407. PBRMaterial.prototype.hasTexture = function (texture) {
  45408. if (_super.prototype.hasTexture.call(this, texture)) {
  45409. return true;
  45410. }
  45411. if (this._albedoTexture === texture) {
  45412. return true;
  45413. }
  45414. if (this._ambientTexture === texture) {
  45415. return true;
  45416. }
  45417. if (this._opacityTexture === texture) {
  45418. return true;
  45419. }
  45420. if (this._reflectionTexture === texture) {
  45421. return true;
  45422. }
  45423. if (this._reflectivityTexture === texture) {
  45424. return true;
  45425. }
  45426. if (this._metallicTexture === texture) {
  45427. return true;
  45428. }
  45429. if (this._microSurfaceTexture === texture) {
  45430. return true;
  45431. }
  45432. if (this._bumpTexture === texture) {
  45433. return true;
  45434. }
  45435. if (this._lightmapTexture === texture) {
  45436. return true;
  45437. }
  45438. if (this._refractionTexture === texture) {
  45439. return true;
  45440. }
  45441. return false;
  45442. };
  45443. /**
  45444. * Makes a duplicate of the current material.
  45445. * @param name - name to use for the new material.
  45446. */
  45447. PBRMaterial.prototype.clone = function (name) {
  45448. var _this = this;
  45449. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45450. clone.id = name;
  45451. clone.name = name;
  45452. return clone;
  45453. };
  45454. /**
  45455. * Serializes this PBR Material.
  45456. * @returns - An object with the serialized material.
  45457. */
  45458. PBRMaterial.prototype.serialize = function () {
  45459. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45460. serializationObject.customType = "BABYLON.PBRMaterial";
  45461. return serializationObject;
  45462. };
  45463. // Statics
  45464. /**
  45465. * Parses a PBR Material from a serialized object.
  45466. * @param source - Serialized object.
  45467. * @param scene - BJS scene instance.
  45468. * @param rootUrl - url for the scene object
  45469. * @returns - PBRMaterial
  45470. */
  45471. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45472. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45473. };
  45474. /**
  45475. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45476. */
  45477. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45478. /**
  45479. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45480. */
  45481. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45482. /**
  45483. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45484. */
  45485. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45486. /**
  45487. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45488. * They are also discarded below the alpha cutoff threshold to improve performances.
  45489. */
  45490. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45491. /**
  45492. * Defines the default value of how much AO map is occluding the analytical lights
  45493. * (point spot...).
  45494. */
  45495. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45496. __decorate([
  45497. BABYLON.serialize(),
  45498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45499. ], PBRMaterial.prototype, "directIntensity", void 0);
  45500. __decorate([
  45501. BABYLON.serialize(),
  45502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45503. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45504. __decorate([
  45505. BABYLON.serialize(),
  45506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45507. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45508. __decorate([
  45509. BABYLON.serialize(),
  45510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45511. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45512. __decorate([
  45513. BABYLON.serialize(),
  45514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45515. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45516. __decorate([
  45517. BABYLON.serializeAsTexture(),
  45518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45519. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45520. __decorate([
  45521. BABYLON.serializeAsTexture(),
  45522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45523. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45524. __decorate([
  45525. BABYLON.serialize(),
  45526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45527. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45528. __decorate([
  45529. BABYLON.serialize(),
  45530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45531. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45532. __decorate([
  45533. BABYLON.serializeAsTexture(),
  45534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45535. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45536. __decorate([
  45537. BABYLON.serializeAsTexture(),
  45538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45539. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45540. __decorate([
  45541. BABYLON.serializeAsTexture(),
  45542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45543. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45544. __decorate([
  45545. BABYLON.serializeAsTexture(),
  45546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45547. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45548. __decorate([
  45549. BABYLON.serializeAsTexture(),
  45550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45551. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45552. __decorate([
  45553. BABYLON.serialize(),
  45554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45555. ], PBRMaterial.prototype, "metallic", void 0);
  45556. __decorate([
  45557. BABYLON.serialize(),
  45558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45559. ], PBRMaterial.prototype, "roughness", void 0);
  45560. __decorate([
  45561. BABYLON.serializeAsTexture(),
  45562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45563. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45564. __decorate([
  45565. BABYLON.serializeAsTexture(),
  45566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45567. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45568. __decorate([
  45569. BABYLON.serializeAsTexture(),
  45570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45571. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45572. __decorate([
  45573. BABYLON.serializeAsTexture(),
  45574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45575. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45576. __decorate([
  45577. BABYLON.serializeAsColor3("ambient"),
  45578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45579. ], PBRMaterial.prototype, "ambientColor", void 0);
  45580. __decorate([
  45581. BABYLON.serializeAsColor3("albedo"),
  45582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45583. ], PBRMaterial.prototype, "albedoColor", void 0);
  45584. __decorate([
  45585. BABYLON.serializeAsColor3("reflectivity"),
  45586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45587. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45588. __decorate([
  45589. BABYLON.serializeAsColor3("reflection"),
  45590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45591. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45592. __decorate([
  45593. BABYLON.serializeAsColor3("emissive"),
  45594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45595. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45596. __decorate([
  45597. BABYLON.serialize(),
  45598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45599. ], PBRMaterial.prototype, "microSurface", void 0);
  45600. __decorate([
  45601. BABYLON.serialize(),
  45602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45603. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45604. __decorate([
  45605. BABYLON.serialize(),
  45606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45607. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45608. __decorate([
  45609. BABYLON.serialize(),
  45610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45611. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45612. __decorate([
  45613. BABYLON.serialize(),
  45614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45615. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45616. __decorate([
  45617. BABYLON.serialize(),
  45618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45619. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45620. __decorate([
  45621. BABYLON.serialize(),
  45622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45623. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45624. __decorate([
  45625. BABYLON.serialize(),
  45626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45627. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45628. __decorate([
  45629. BABYLON.serialize(),
  45630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45631. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45632. __decorate([
  45633. BABYLON.serialize(),
  45634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45635. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45636. __decorate([
  45637. BABYLON.serialize(),
  45638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45639. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45640. __decorate([
  45641. BABYLON.serialize(),
  45642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45643. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45644. __decorate([
  45645. BABYLON.serialize(),
  45646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45647. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45648. __decorate([
  45649. BABYLON.serialize(),
  45650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45651. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45652. __decorate([
  45653. BABYLON.serialize(),
  45654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45655. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45656. __decorate([
  45657. BABYLON.serialize(),
  45658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45659. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45660. __decorate([
  45661. BABYLON.serialize()
  45662. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45663. __decorate([
  45664. BABYLON.serialize()
  45665. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45666. __decorate([
  45667. BABYLON.serialize(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45669. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45670. __decorate([
  45671. BABYLON.serialize(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45673. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45674. __decorate([
  45675. BABYLON.serialize(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "useParallax", void 0);
  45678. __decorate([
  45679. BABYLON.serialize(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45681. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45682. __decorate([
  45683. BABYLON.serialize(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45685. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45686. __decorate([
  45687. BABYLON.serialize(),
  45688. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45689. ], PBRMaterial.prototype, "disableLighting", void 0);
  45690. __decorate([
  45691. BABYLON.serialize(),
  45692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45693. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45694. __decorate([
  45695. BABYLON.serialize(),
  45696. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45697. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45698. __decorate([
  45699. BABYLON.serialize(),
  45700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45701. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45702. __decorate([
  45703. BABYLON.serialize(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45705. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45706. __decorate([
  45707. BABYLON.serialize(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45709. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45710. __decorate([
  45711. BABYLON.serialize(),
  45712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45713. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45714. __decorate([
  45715. BABYLON.serialize(),
  45716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45717. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45718. __decorate([
  45719. BABYLON.serializeAsTexture(),
  45720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45721. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45722. __decorate([
  45723. BABYLON.serialize(),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45725. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45726. __decorate([
  45727. BABYLON.serialize(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45729. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45730. __decorate([
  45731. BABYLON.serialize(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45733. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45734. __decorate([
  45735. BABYLON.serialize(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45737. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45738. __decorate([
  45739. BABYLON.serialize(),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45741. ], PBRMaterial.prototype, "unlit", void 0);
  45742. return PBRMaterial;
  45743. }(BABYLON.PBRBaseMaterial));
  45744. BABYLON.PBRMaterial = PBRMaterial;
  45745. })(BABYLON || (BABYLON = {}));
  45746. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45747. var BABYLON;
  45748. (function (BABYLON) {
  45749. /**
  45750. * The PBR material of BJS following the metal roughness convention.
  45751. *
  45752. * This fits to the PBR convention in the GLTF definition:
  45753. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45754. */
  45755. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45756. __extends(PBRMetallicRoughnessMaterial, _super);
  45757. /**
  45758. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45759. *
  45760. * @param name The material name
  45761. * @param scene The scene the material will be use in.
  45762. */
  45763. function PBRMetallicRoughnessMaterial(name, scene) {
  45764. var _this = _super.call(this, name, scene) || this;
  45765. _this._useRoughnessFromMetallicTextureAlpha = false;
  45766. _this._useRoughnessFromMetallicTextureGreen = true;
  45767. _this._useMetallnessFromMetallicTextureBlue = true;
  45768. _this.metallic = 1.0;
  45769. _this.roughness = 1.0;
  45770. return _this;
  45771. }
  45772. /**
  45773. * Return the currrent class name of the material.
  45774. */
  45775. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45776. return "PBRMetallicRoughnessMaterial";
  45777. };
  45778. /**
  45779. * Return the active textures of the material.
  45780. */
  45781. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45782. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45783. if (this.baseTexture) {
  45784. activeTextures.push(this.baseTexture);
  45785. }
  45786. if (this.metallicRoughnessTexture) {
  45787. activeTextures.push(this.metallicRoughnessTexture);
  45788. }
  45789. return activeTextures;
  45790. };
  45791. /**
  45792. * Checks to see if a texture is used in the material.
  45793. * @param texture - Base texture to use.
  45794. * @returns - Boolean specifying if a texture is used in the material.
  45795. */
  45796. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45797. if (_super.prototype.hasTexture.call(this, texture)) {
  45798. return true;
  45799. }
  45800. if (this.baseTexture === texture) {
  45801. return true;
  45802. }
  45803. if (this.metallicRoughnessTexture === texture) {
  45804. return true;
  45805. }
  45806. return false;
  45807. };
  45808. /**
  45809. * Makes a duplicate of the current material.
  45810. * @param name - name to use for the new material.
  45811. */
  45812. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45813. var _this = this;
  45814. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45815. clone.id = name;
  45816. clone.name = name;
  45817. return clone;
  45818. };
  45819. /**
  45820. * Serialize the material to a parsable JSON object.
  45821. */
  45822. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45823. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45824. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45825. return serializationObject;
  45826. };
  45827. /**
  45828. * Parses a JSON object correponding to the serialize function.
  45829. */
  45830. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45831. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45832. };
  45833. __decorate([
  45834. BABYLON.serializeAsColor3(),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45836. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45837. __decorate([
  45838. BABYLON.serializeAsTexture(),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45840. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45841. __decorate([
  45842. BABYLON.serialize(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45844. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45845. __decorate([
  45846. BABYLON.serialize(),
  45847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45848. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45849. __decorate([
  45850. BABYLON.serializeAsTexture(),
  45851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45852. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45853. return PBRMetallicRoughnessMaterial;
  45854. }(BABYLON.PBRBaseSimpleMaterial));
  45855. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45856. })(BABYLON || (BABYLON = {}));
  45857. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45858. var BABYLON;
  45859. (function (BABYLON) {
  45860. /**
  45861. * The PBR material of BJS following the specular glossiness convention.
  45862. *
  45863. * This fits to the PBR convention in the GLTF definition:
  45864. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45865. */
  45866. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45867. __extends(PBRSpecularGlossinessMaterial, _super);
  45868. /**
  45869. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45870. *
  45871. * @param name The material name
  45872. * @param scene The scene the material will be use in.
  45873. */
  45874. function PBRSpecularGlossinessMaterial(name, scene) {
  45875. var _this = _super.call(this, name, scene) || this;
  45876. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45877. return _this;
  45878. }
  45879. /**
  45880. * Return the currrent class name of the material.
  45881. */
  45882. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45883. return "PBRSpecularGlossinessMaterial";
  45884. };
  45885. /**
  45886. * Return the active textures of the material.
  45887. */
  45888. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45889. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45890. if (this.diffuseTexture) {
  45891. activeTextures.push(this.diffuseTexture);
  45892. }
  45893. if (this.specularGlossinessTexture) {
  45894. activeTextures.push(this.specularGlossinessTexture);
  45895. }
  45896. return activeTextures;
  45897. };
  45898. /**
  45899. * Checks to see if a texture is used in the material.
  45900. * @param texture - Base texture to use.
  45901. * @returns - Boolean specifying if a texture is used in the material.
  45902. */
  45903. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45904. if (_super.prototype.hasTexture.call(this, texture)) {
  45905. return true;
  45906. }
  45907. if (this.diffuseTexture === texture) {
  45908. return true;
  45909. }
  45910. if (this.specularGlossinessTexture === texture) {
  45911. return true;
  45912. }
  45913. return false;
  45914. };
  45915. /**
  45916. * Makes a duplicate of the current material.
  45917. * @param name - name to use for the new material.
  45918. */
  45919. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45920. var _this = this;
  45921. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45922. clone.id = name;
  45923. clone.name = name;
  45924. return clone;
  45925. };
  45926. /**
  45927. * Serialize the material to a parsable JSON object.
  45928. */
  45929. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45930. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45931. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45932. return serializationObject;
  45933. };
  45934. /**
  45935. * Parses a JSON object correponding to the serialize function.
  45936. */
  45937. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45938. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45939. };
  45940. __decorate([
  45941. BABYLON.serializeAsColor3("diffuse"),
  45942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45943. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45944. __decorate([
  45945. BABYLON.serializeAsTexture(),
  45946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45947. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45948. __decorate([
  45949. BABYLON.serializeAsColor3("specular"),
  45950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45951. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45952. __decorate([
  45953. BABYLON.serialize(),
  45954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45955. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45956. __decorate([
  45957. BABYLON.serializeAsTexture(),
  45958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45959. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45960. return PBRSpecularGlossinessMaterial;
  45961. }(BABYLON.PBRBaseSimpleMaterial));
  45962. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45963. })(BABYLON || (BABYLON = {}));
  45964. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45965. var BABYLON;
  45966. (function (BABYLON) {
  45967. BABYLON.CameraInputTypes = {};
  45968. var CameraInputsManager = /** @class */ (function () {
  45969. function CameraInputsManager(camera) {
  45970. this.attached = {};
  45971. this.camera = camera;
  45972. this.checkInputs = function () { };
  45973. }
  45974. /**
  45975. * Add an input method to a camera
  45976. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45977. * @param input camera input method
  45978. */
  45979. CameraInputsManager.prototype.add = function (input) {
  45980. var type = input.getSimpleName();
  45981. if (this.attached[type]) {
  45982. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45983. return;
  45984. }
  45985. this.attached[type] = input;
  45986. input.camera = this.camera;
  45987. //for checkInputs, we are dynamically creating a function
  45988. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45989. if (input.checkInputs) {
  45990. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45991. }
  45992. if (this.attachedElement) {
  45993. input.attachControl(this.attachedElement);
  45994. }
  45995. };
  45996. /**
  45997. * Remove a specific input method from a camera
  45998. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45999. * @param inputToRemove camera input method
  46000. */
  46001. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46002. for (var cam in this.attached) {
  46003. var input = this.attached[cam];
  46004. if (input === inputToRemove) {
  46005. input.detachControl(this.attachedElement);
  46006. input.camera = null;
  46007. delete this.attached[cam];
  46008. this.rebuildInputCheck();
  46009. }
  46010. }
  46011. };
  46012. CameraInputsManager.prototype.removeByType = function (inputType) {
  46013. for (var cam in this.attached) {
  46014. var input = this.attached[cam];
  46015. if (input.getClassName() === inputType) {
  46016. input.detachControl(this.attachedElement);
  46017. input.camera = null;
  46018. delete this.attached[cam];
  46019. this.rebuildInputCheck();
  46020. }
  46021. }
  46022. };
  46023. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46024. var current = this.checkInputs;
  46025. return function () {
  46026. current();
  46027. fn();
  46028. };
  46029. };
  46030. CameraInputsManager.prototype.attachInput = function (input) {
  46031. if (this.attachedElement) {
  46032. input.attachControl(this.attachedElement, this.noPreventDefault);
  46033. }
  46034. };
  46035. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46036. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46037. if (this.attachedElement) {
  46038. return;
  46039. }
  46040. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46041. this.attachedElement = element;
  46042. this.noPreventDefault = noPreventDefault;
  46043. for (var cam in this.attached) {
  46044. this.attached[cam].attachControl(element, noPreventDefault);
  46045. }
  46046. };
  46047. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46048. if (disconnect === void 0) { disconnect = false; }
  46049. if (this.attachedElement !== element) {
  46050. return;
  46051. }
  46052. for (var cam in this.attached) {
  46053. this.attached[cam].detachControl(element);
  46054. if (disconnect) {
  46055. this.attached[cam].camera = null;
  46056. }
  46057. }
  46058. this.attachedElement = null;
  46059. };
  46060. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46061. this.checkInputs = function () { };
  46062. for (var cam in this.attached) {
  46063. var input = this.attached[cam];
  46064. if (input.checkInputs) {
  46065. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46066. }
  46067. }
  46068. };
  46069. /**
  46070. * Remove all attached input methods from a camera
  46071. */
  46072. CameraInputsManager.prototype.clear = function () {
  46073. if (this.attachedElement) {
  46074. this.detachElement(this.attachedElement, true);
  46075. }
  46076. this.attached = {};
  46077. this.attachedElement = null;
  46078. this.checkInputs = function () { };
  46079. };
  46080. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46081. var inputs = {};
  46082. for (var cam in this.attached) {
  46083. var input = this.attached[cam];
  46084. var res = BABYLON.SerializationHelper.Serialize(input);
  46085. inputs[input.getClassName()] = res;
  46086. }
  46087. serializedCamera.inputsmgr = inputs;
  46088. };
  46089. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46090. var parsedInputs = parsedCamera.inputsmgr;
  46091. if (parsedInputs) {
  46092. this.clear();
  46093. for (var n in parsedInputs) {
  46094. var construct = BABYLON.CameraInputTypes[n];
  46095. if (construct) {
  46096. var parsedinput = parsedInputs[n];
  46097. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46098. this.add(input);
  46099. }
  46100. }
  46101. }
  46102. else {
  46103. //2016-03-08 this part is for managing backward compatibility
  46104. for (var n in this.attached) {
  46105. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46106. if (construct) {
  46107. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46108. this.remove(this.attached[n]);
  46109. this.add(input);
  46110. }
  46111. }
  46112. }
  46113. };
  46114. return CameraInputsManager;
  46115. }());
  46116. BABYLON.CameraInputsManager = CameraInputsManager;
  46117. })(BABYLON || (BABYLON = {}));
  46118. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46119. var BABYLON;
  46120. (function (BABYLON) {
  46121. var TargetCamera = /** @class */ (function (_super) {
  46122. __extends(TargetCamera, _super);
  46123. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46124. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46125. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46126. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46127. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46128. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46129. _this.speed = 2.0;
  46130. _this.noRotationConstraint = false;
  46131. _this.lockedTarget = null;
  46132. /** @hidden */
  46133. _this._currentTarget = BABYLON.Vector3.Zero();
  46134. /** @hidden */
  46135. _this._viewMatrix = BABYLON.Matrix.Zero();
  46136. /** @hidden */
  46137. _this._camMatrix = BABYLON.Matrix.Zero();
  46138. /** @hidden */
  46139. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46140. /** @hidden */
  46141. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46142. /** @hidden */
  46143. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46144. /** @hidden */
  46145. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46146. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46147. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46148. _this._defaultUp = BABYLON.Vector3.Up();
  46149. _this._cachedRotationZ = 0;
  46150. return _this;
  46151. }
  46152. TargetCamera.prototype.getFrontPosition = function (distance) {
  46153. this.getWorldMatrix();
  46154. var direction = this.getTarget().subtract(this.position);
  46155. direction.normalize();
  46156. direction.scaleInPlace(distance);
  46157. return this.globalPosition.add(direction);
  46158. };
  46159. /** @hidden */
  46160. TargetCamera.prototype._getLockedTargetPosition = function () {
  46161. if (!this.lockedTarget) {
  46162. return null;
  46163. }
  46164. if (this.lockedTarget.absolutePosition) {
  46165. this.lockedTarget.computeWorldMatrix();
  46166. }
  46167. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46168. };
  46169. TargetCamera.prototype.storeState = function () {
  46170. this._storedPosition = this.position.clone();
  46171. this._storedRotation = this.rotation.clone();
  46172. if (this.rotationQuaternion) {
  46173. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46174. }
  46175. return _super.prototype.storeState.call(this);
  46176. };
  46177. /**
  46178. * Restored camera state. You must call storeState() first
  46179. * @returns whether it was successful or not
  46180. * @hidden
  46181. */
  46182. TargetCamera.prototype._restoreStateValues = function () {
  46183. if (!_super.prototype._restoreStateValues.call(this)) {
  46184. return false;
  46185. }
  46186. this.position = this._storedPosition.clone();
  46187. this.rotation = this._storedRotation.clone();
  46188. if (this.rotationQuaternion) {
  46189. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46190. }
  46191. this.cameraDirection.copyFromFloats(0, 0, 0);
  46192. this.cameraRotation.copyFromFloats(0, 0);
  46193. return true;
  46194. };
  46195. // Cache
  46196. /** @hidden */
  46197. TargetCamera.prototype._initCache = function () {
  46198. _super.prototype._initCache.call(this);
  46199. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46200. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46201. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46202. };
  46203. /** @hidden */
  46204. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46205. if (!ignoreParentClass) {
  46206. _super.prototype._updateCache.call(this);
  46207. }
  46208. var lockedTargetPosition = this._getLockedTargetPosition();
  46209. if (!lockedTargetPosition) {
  46210. this._cache.lockedTarget = null;
  46211. }
  46212. else {
  46213. if (!this._cache.lockedTarget) {
  46214. this._cache.lockedTarget = lockedTargetPosition.clone();
  46215. }
  46216. else {
  46217. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46218. }
  46219. }
  46220. this._cache.rotation.copyFrom(this.rotation);
  46221. if (this.rotationQuaternion)
  46222. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46223. };
  46224. // Synchronized
  46225. /** @hidden */
  46226. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46227. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46228. return false;
  46229. }
  46230. var lockedTargetPosition = this._getLockedTargetPosition();
  46231. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46232. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46233. };
  46234. // Methods
  46235. /** @hidden */
  46236. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46237. var engine = this.getEngine();
  46238. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46239. };
  46240. // Target
  46241. /** @hidden */
  46242. TargetCamera.prototype.setTarget = function (target) {
  46243. this.upVector.normalize();
  46244. if (this.position.z === target.z) {
  46245. this.position.z += BABYLON.Epsilon;
  46246. }
  46247. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46248. this._camMatrix.invert();
  46249. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46250. var vDir = target.subtract(this.position);
  46251. if (vDir.x >= 0.0) {
  46252. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46253. }
  46254. else {
  46255. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46256. }
  46257. this.rotation.z = 0;
  46258. if (isNaN(this.rotation.x)) {
  46259. this.rotation.x = 0;
  46260. }
  46261. if (isNaN(this.rotation.y)) {
  46262. this.rotation.y = 0;
  46263. }
  46264. if (isNaN(this.rotation.z)) {
  46265. this.rotation.z = 0;
  46266. }
  46267. if (this.rotationQuaternion) {
  46268. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46269. }
  46270. };
  46271. /**
  46272. * Return the current target position of the camera. This value is expressed in local space.
  46273. */
  46274. TargetCamera.prototype.getTarget = function () {
  46275. return this._currentTarget;
  46276. };
  46277. /** @hidden */
  46278. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46279. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46280. };
  46281. /** @hidden */
  46282. TargetCamera.prototype._updatePosition = function () {
  46283. if (this.parent) {
  46284. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46285. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46286. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46287. return;
  46288. }
  46289. this.position.addInPlace(this.cameraDirection);
  46290. };
  46291. /** @hidden */
  46292. TargetCamera.prototype._checkInputs = function () {
  46293. var needToMove = this._decideIfNeedsToMove();
  46294. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46295. // Move
  46296. if (needToMove) {
  46297. this._updatePosition();
  46298. }
  46299. // Rotate
  46300. if (needToRotate) {
  46301. this.rotation.x += this.cameraRotation.x;
  46302. this.rotation.y += this.cameraRotation.y;
  46303. //rotate, if quaternion is set and rotation was used
  46304. if (this.rotationQuaternion) {
  46305. var len = this.rotation.lengthSquared();
  46306. if (len) {
  46307. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46308. }
  46309. }
  46310. if (!this.noRotationConstraint) {
  46311. var limit = (Math.PI / 2) * 0.95;
  46312. if (this.rotation.x > limit)
  46313. this.rotation.x = limit;
  46314. if (this.rotation.x < -limit)
  46315. this.rotation.x = -limit;
  46316. }
  46317. }
  46318. // Inertia
  46319. if (needToMove) {
  46320. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46321. this.cameraDirection.x = 0;
  46322. }
  46323. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46324. this.cameraDirection.y = 0;
  46325. }
  46326. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46327. this.cameraDirection.z = 0;
  46328. }
  46329. this.cameraDirection.scaleInPlace(this.inertia);
  46330. }
  46331. if (needToRotate) {
  46332. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46333. this.cameraRotation.x = 0;
  46334. }
  46335. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46336. this.cameraRotation.y = 0;
  46337. }
  46338. this.cameraRotation.scaleInPlace(this.inertia);
  46339. }
  46340. _super.prototype._checkInputs.call(this);
  46341. };
  46342. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46343. if (this.rotationQuaternion) {
  46344. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46345. }
  46346. else {
  46347. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46348. }
  46349. };
  46350. /**
  46351. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46352. * @returns the current camera
  46353. */
  46354. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46355. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46356. return this;
  46357. };
  46358. /** @hidden */
  46359. TargetCamera.prototype._getViewMatrix = function () {
  46360. if (this.lockedTarget) {
  46361. this.setTarget(this._getLockedTargetPosition());
  46362. }
  46363. // Compute
  46364. this._updateCameraRotationMatrix();
  46365. // Apply the changed rotation to the upVector.
  46366. if (this._cachedRotationZ != this.rotation.z) {
  46367. this._rotateUpVectorWithCameraRotationMatrix();
  46368. this._cachedRotationZ = this.rotation.z;
  46369. }
  46370. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46371. // Computing target and final matrix
  46372. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46373. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46374. return this._viewMatrix;
  46375. };
  46376. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46377. if (this.parent) {
  46378. var parentWorldMatrix = this.parent.getWorldMatrix();
  46379. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46380. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46381. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46382. this._markSyncedWithParent();
  46383. }
  46384. else {
  46385. this._globalPosition.copyFrom(position);
  46386. this._globalCurrentTarget.copyFrom(target);
  46387. this._globalCurrentUpVector.copyFrom(up);
  46388. }
  46389. if (this.getScene().useRightHandedSystem) {
  46390. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46391. }
  46392. else {
  46393. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46394. }
  46395. };
  46396. /**
  46397. * @override
  46398. * Override Camera.createRigCamera
  46399. */
  46400. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46401. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46402. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46403. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46404. if (!this.rotationQuaternion) {
  46405. this.rotationQuaternion = new BABYLON.Quaternion();
  46406. }
  46407. rigCamera._cameraRigParams = {};
  46408. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46409. }
  46410. return rigCamera;
  46411. }
  46412. return null;
  46413. };
  46414. /**
  46415. * @hidden
  46416. * @override
  46417. * Override Camera._updateRigCameras
  46418. */
  46419. TargetCamera.prototype._updateRigCameras = function () {
  46420. var camLeft = this._rigCameras[0];
  46421. var camRight = this._rigCameras[1];
  46422. switch (this.cameraRigMode) {
  46423. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46424. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46425. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46426. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46427. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46428. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46429. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46430. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46431. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46432. camLeft.setTarget(this.getTarget());
  46433. camRight.setTarget(this.getTarget());
  46434. break;
  46435. case BABYLON.Camera.RIG_MODE_VR:
  46436. if (camLeft.rotationQuaternion) {
  46437. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46438. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46439. }
  46440. else {
  46441. camLeft.rotation.copyFrom(this.rotation);
  46442. camRight.rotation.copyFrom(this.rotation);
  46443. }
  46444. camLeft.position.copyFrom(this.position);
  46445. camRight.position.copyFrom(this.position);
  46446. break;
  46447. }
  46448. _super.prototype._updateRigCameras.call(this);
  46449. };
  46450. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46451. if (!this._rigCamTransformMatrix) {
  46452. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46453. }
  46454. var target = this.getTarget();
  46455. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46456. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46457. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46458. };
  46459. TargetCamera.prototype.getClassName = function () {
  46460. return "TargetCamera";
  46461. };
  46462. __decorate([
  46463. BABYLON.serializeAsVector3()
  46464. ], TargetCamera.prototype, "rotation", void 0);
  46465. __decorate([
  46466. BABYLON.serialize()
  46467. ], TargetCamera.prototype, "speed", void 0);
  46468. __decorate([
  46469. BABYLON.serializeAsMeshReference("lockedTargetId")
  46470. ], TargetCamera.prototype, "lockedTarget", void 0);
  46471. return TargetCamera;
  46472. }(BABYLON.Camera));
  46473. BABYLON.TargetCamera = TargetCamera;
  46474. })(BABYLON || (BABYLON = {}));
  46475. //# sourceMappingURL=babylon.targetCamera.js.map
  46476. var BABYLON;
  46477. (function (BABYLON) {
  46478. var FreeCameraMouseInput = /** @class */ (function () {
  46479. function FreeCameraMouseInput(touchEnabled) {
  46480. if (touchEnabled === void 0) { touchEnabled = true; }
  46481. this.touchEnabled = touchEnabled;
  46482. this.buttons = [0, 1, 2];
  46483. this.angularSensibility = 2000.0;
  46484. this.previousPosition = null;
  46485. }
  46486. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46487. var _this = this;
  46488. var engine = this.camera.getEngine();
  46489. if (!this._pointerInput) {
  46490. this._pointerInput = function (p, s) {
  46491. var evt = p.event;
  46492. if (engine.isInVRExclusivePointerMode) {
  46493. return;
  46494. }
  46495. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46496. return;
  46497. }
  46498. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46499. return;
  46500. }
  46501. var srcElement = (evt.srcElement || evt.target);
  46502. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46503. try {
  46504. srcElement.setPointerCapture(evt.pointerId);
  46505. }
  46506. catch (e) {
  46507. //Nothing to do with the error. Execution will continue.
  46508. }
  46509. _this.previousPosition = {
  46510. x: evt.clientX,
  46511. y: evt.clientY
  46512. };
  46513. if (!noPreventDefault) {
  46514. evt.preventDefault();
  46515. element.focus();
  46516. }
  46517. }
  46518. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46519. try {
  46520. srcElement.releasePointerCapture(evt.pointerId);
  46521. }
  46522. catch (e) {
  46523. //Nothing to do with the error.
  46524. }
  46525. _this.previousPosition = null;
  46526. if (!noPreventDefault) {
  46527. evt.preventDefault();
  46528. }
  46529. }
  46530. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46531. if (!_this.previousPosition || engine.isPointerLock) {
  46532. return;
  46533. }
  46534. var offsetX = evt.clientX - _this.previousPosition.x;
  46535. if (_this.camera.getScene().useRightHandedSystem)
  46536. offsetX *= -1;
  46537. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46538. offsetX *= -1;
  46539. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46540. var offsetY = evt.clientY - _this.previousPosition.y;
  46541. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46542. _this.previousPosition = {
  46543. x: evt.clientX,
  46544. y: evt.clientY
  46545. };
  46546. if (!noPreventDefault) {
  46547. evt.preventDefault();
  46548. }
  46549. }
  46550. };
  46551. }
  46552. this._onMouseMove = function (evt) {
  46553. if (!engine.isPointerLock) {
  46554. return;
  46555. }
  46556. if (engine.isInVRExclusivePointerMode) {
  46557. return;
  46558. }
  46559. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46560. if (_this.camera.getScene().useRightHandedSystem)
  46561. offsetX *= -1;
  46562. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46563. offsetX *= -1;
  46564. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46565. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46566. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46567. _this.previousPosition = null;
  46568. if (!noPreventDefault) {
  46569. evt.preventDefault();
  46570. }
  46571. };
  46572. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46573. element.addEventListener("mousemove", this._onMouseMove, false);
  46574. };
  46575. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46576. if (this._observer && element) {
  46577. this.camera.getScene().onPointerObservable.remove(this._observer);
  46578. if (this._onMouseMove) {
  46579. element.removeEventListener("mousemove", this._onMouseMove);
  46580. }
  46581. this._observer = null;
  46582. this._onMouseMove = null;
  46583. this.previousPosition = null;
  46584. }
  46585. };
  46586. FreeCameraMouseInput.prototype.getClassName = function () {
  46587. return "FreeCameraMouseInput";
  46588. };
  46589. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46590. return "mouse";
  46591. };
  46592. __decorate([
  46593. BABYLON.serialize()
  46594. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46595. __decorate([
  46596. BABYLON.serialize()
  46597. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46598. return FreeCameraMouseInput;
  46599. }());
  46600. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46601. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46602. })(BABYLON || (BABYLON = {}));
  46603. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46604. var BABYLON;
  46605. (function (BABYLON) {
  46606. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46607. function FreeCameraKeyboardMoveInput() {
  46608. this._keys = new Array();
  46609. this.keysUp = [38];
  46610. this.keysDown = [40];
  46611. this.keysLeft = [37];
  46612. this.keysRight = [39];
  46613. }
  46614. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46615. var _this = this;
  46616. if (this._onCanvasBlurObserver) {
  46617. return;
  46618. }
  46619. this._scene = this.camera.getScene();
  46620. this._engine = this._scene.getEngine();
  46621. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46622. _this._keys = [];
  46623. });
  46624. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46625. var evt = info.event;
  46626. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46627. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46628. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46629. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46630. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46631. var index = _this._keys.indexOf(evt.keyCode);
  46632. if (index === -1) {
  46633. _this._keys.push(evt.keyCode);
  46634. }
  46635. if (!noPreventDefault) {
  46636. evt.preventDefault();
  46637. }
  46638. }
  46639. }
  46640. else {
  46641. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46642. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46643. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46644. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46645. var index = _this._keys.indexOf(evt.keyCode);
  46646. if (index >= 0) {
  46647. _this._keys.splice(index, 1);
  46648. }
  46649. if (!noPreventDefault) {
  46650. evt.preventDefault();
  46651. }
  46652. }
  46653. }
  46654. });
  46655. };
  46656. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46657. if (this._scene) {
  46658. if (this._onKeyboardObserver) {
  46659. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46660. }
  46661. if (this._onCanvasBlurObserver) {
  46662. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46663. }
  46664. this._onKeyboardObserver = null;
  46665. this._onCanvasBlurObserver = null;
  46666. }
  46667. this._keys = [];
  46668. };
  46669. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46670. if (this._onKeyboardObserver) {
  46671. var camera = this.camera;
  46672. // Keyboard
  46673. for (var index = 0; index < this._keys.length; index++) {
  46674. var keyCode = this._keys[index];
  46675. var speed = camera._computeLocalCameraSpeed();
  46676. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46677. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46678. }
  46679. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46680. camera._localDirection.copyFromFloats(0, 0, speed);
  46681. }
  46682. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46683. camera._localDirection.copyFromFloats(speed, 0, 0);
  46684. }
  46685. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46686. camera._localDirection.copyFromFloats(0, 0, -speed);
  46687. }
  46688. if (camera.getScene().useRightHandedSystem) {
  46689. camera._localDirection.z *= -1;
  46690. }
  46691. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46692. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46693. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46694. }
  46695. }
  46696. };
  46697. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46698. return "FreeCameraKeyboardMoveInput";
  46699. };
  46700. /** @hidden */
  46701. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46702. this._keys = [];
  46703. };
  46704. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46705. return "keyboard";
  46706. };
  46707. __decorate([
  46708. BABYLON.serialize()
  46709. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46710. __decorate([
  46711. BABYLON.serialize()
  46712. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46713. __decorate([
  46714. BABYLON.serialize()
  46715. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46716. __decorate([
  46717. BABYLON.serialize()
  46718. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46719. return FreeCameraKeyboardMoveInput;
  46720. }());
  46721. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46722. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46723. })(BABYLON || (BABYLON = {}));
  46724. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46725. var BABYLON;
  46726. (function (BABYLON) {
  46727. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46728. __extends(FreeCameraInputsManager, _super);
  46729. function FreeCameraInputsManager(camera) {
  46730. return _super.call(this, camera) || this;
  46731. }
  46732. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46733. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46734. return this;
  46735. };
  46736. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46737. if (touchEnabled === void 0) { touchEnabled = true; }
  46738. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46739. return this;
  46740. };
  46741. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46742. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46743. return this;
  46744. };
  46745. FreeCameraInputsManager.prototype.addTouch = function () {
  46746. this.add(new BABYLON.FreeCameraTouchInput());
  46747. return this;
  46748. };
  46749. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46750. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46751. return this;
  46752. };
  46753. return FreeCameraInputsManager;
  46754. }(BABYLON.CameraInputsManager));
  46755. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46756. })(BABYLON || (BABYLON = {}));
  46757. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46758. var BABYLON;
  46759. (function (BABYLON) {
  46760. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46761. // Forcing to use the Universal camera
  46762. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46763. });
  46764. var FreeCamera = /** @class */ (function (_super) {
  46765. __extends(FreeCamera, _super);
  46766. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46767. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46768. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46769. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46770. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46771. _this.checkCollisions = false;
  46772. _this.applyGravity = false;
  46773. _this._needMoveForGravity = false;
  46774. _this._oldPosition = BABYLON.Vector3.Zero();
  46775. _this._diffPosition = BABYLON.Vector3.Zero();
  46776. _this._newPosition = BABYLON.Vector3.Zero();
  46777. // Collisions
  46778. _this._collisionMask = -1;
  46779. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46780. if (collidedMesh === void 0) { collidedMesh = null; }
  46781. //TODO move this to the collision coordinator!
  46782. if (_this.getScene().workerCollisions)
  46783. newPosition.multiplyInPlace(_this._collider._radius);
  46784. var updatePosition = function (newPos) {
  46785. _this._newPosition.copyFrom(newPos);
  46786. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46787. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46788. _this.position.addInPlace(_this._diffPosition);
  46789. if (_this.onCollide && collidedMesh) {
  46790. _this.onCollide(collidedMesh);
  46791. }
  46792. }
  46793. };
  46794. updatePosition(newPosition);
  46795. };
  46796. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46797. _this.inputs.addKeyboard().addMouse();
  46798. return _this;
  46799. }
  46800. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46801. //-- begin properties for backward compatibility for inputs
  46802. /**
  46803. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46804. * Higher values reduce sensitivity.
  46805. */
  46806. get: function () {
  46807. var mouse = this.inputs.attached["mouse"];
  46808. if (mouse)
  46809. return mouse.angularSensibility;
  46810. return 0;
  46811. },
  46812. /**
  46813. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46814. * Higher values reduce sensitivity.
  46815. */
  46816. set: function (value) {
  46817. var mouse = this.inputs.attached["mouse"];
  46818. if (mouse)
  46819. mouse.angularSensibility = value;
  46820. },
  46821. enumerable: true,
  46822. configurable: true
  46823. });
  46824. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46825. get: function () {
  46826. var keyboard = this.inputs.attached["keyboard"];
  46827. if (keyboard)
  46828. return keyboard.keysUp;
  46829. return [];
  46830. },
  46831. set: function (value) {
  46832. var keyboard = this.inputs.attached["keyboard"];
  46833. if (keyboard)
  46834. keyboard.keysUp = value;
  46835. },
  46836. enumerable: true,
  46837. configurable: true
  46838. });
  46839. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46840. get: function () {
  46841. var keyboard = this.inputs.attached["keyboard"];
  46842. if (keyboard)
  46843. return keyboard.keysDown;
  46844. return [];
  46845. },
  46846. set: function (value) {
  46847. var keyboard = this.inputs.attached["keyboard"];
  46848. if (keyboard)
  46849. keyboard.keysDown = value;
  46850. },
  46851. enumerable: true,
  46852. configurable: true
  46853. });
  46854. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46855. get: function () {
  46856. var keyboard = this.inputs.attached["keyboard"];
  46857. if (keyboard)
  46858. return keyboard.keysLeft;
  46859. return [];
  46860. },
  46861. set: function (value) {
  46862. var keyboard = this.inputs.attached["keyboard"];
  46863. if (keyboard)
  46864. keyboard.keysLeft = value;
  46865. },
  46866. enumerable: true,
  46867. configurable: true
  46868. });
  46869. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46870. get: function () {
  46871. var keyboard = this.inputs.attached["keyboard"];
  46872. if (keyboard)
  46873. return keyboard.keysRight;
  46874. return [];
  46875. },
  46876. set: function (value) {
  46877. var keyboard = this.inputs.attached["keyboard"];
  46878. if (keyboard)
  46879. keyboard.keysRight = value;
  46880. },
  46881. enumerable: true,
  46882. configurable: true
  46883. });
  46884. // Controls
  46885. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46886. this.inputs.attachElement(element, noPreventDefault);
  46887. };
  46888. FreeCamera.prototype.detachControl = function (element) {
  46889. this.inputs.detachElement(element);
  46890. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46891. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46892. };
  46893. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46894. get: function () {
  46895. return this._collisionMask;
  46896. },
  46897. set: function (mask) {
  46898. this._collisionMask = !isNaN(mask) ? mask : -1;
  46899. },
  46900. enumerable: true,
  46901. configurable: true
  46902. });
  46903. /** @hidden */
  46904. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46905. var globalPosition;
  46906. if (this.parent) {
  46907. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46908. }
  46909. else {
  46910. globalPosition = this.position;
  46911. }
  46912. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46913. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46914. if (!this._collider) {
  46915. this._collider = new BABYLON.Collider();
  46916. }
  46917. this._collider._radius = this.ellipsoid;
  46918. this._collider.collisionMask = this._collisionMask;
  46919. //no need for clone, as long as gravity is not on.
  46920. var actualDisplacement = displacement;
  46921. //add gravity to the direction to prevent the dual-collision checking
  46922. if (this.applyGravity) {
  46923. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46924. actualDisplacement = displacement.add(this.getScene().gravity);
  46925. }
  46926. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46927. };
  46928. /** @hidden */
  46929. FreeCamera.prototype._checkInputs = function () {
  46930. if (!this._localDirection) {
  46931. this._localDirection = BABYLON.Vector3.Zero();
  46932. this._transformedDirection = BABYLON.Vector3.Zero();
  46933. }
  46934. this.inputs.checkInputs();
  46935. _super.prototype._checkInputs.call(this);
  46936. };
  46937. /** @hidden */
  46938. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46939. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46940. };
  46941. /** @hidden */
  46942. FreeCamera.prototype._updatePosition = function () {
  46943. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46944. this._collideWithWorld(this.cameraDirection);
  46945. }
  46946. else {
  46947. _super.prototype._updatePosition.call(this);
  46948. }
  46949. };
  46950. FreeCamera.prototype.dispose = function () {
  46951. this.inputs.clear();
  46952. _super.prototype.dispose.call(this);
  46953. };
  46954. FreeCamera.prototype.getClassName = function () {
  46955. return "FreeCamera";
  46956. };
  46957. __decorate([
  46958. BABYLON.serializeAsVector3()
  46959. ], FreeCamera.prototype, "ellipsoid", void 0);
  46960. __decorate([
  46961. BABYLON.serializeAsVector3()
  46962. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46963. __decorate([
  46964. BABYLON.serialize()
  46965. ], FreeCamera.prototype, "checkCollisions", void 0);
  46966. __decorate([
  46967. BABYLON.serialize()
  46968. ], FreeCamera.prototype, "applyGravity", void 0);
  46969. return FreeCamera;
  46970. }(BABYLON.TargetCamera));
  46971. BABYLON.FreeCamera = FreeCamera;
  46972. })(BABYLON || (BABYLON = {}));
  46973. //# sourceMappingURL=babylon.freeCamera.js.map
  46974. var BABYLON;
  46975. (function (BABYLON) {
  46976. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46977. function ArcRotateCameraKeyboardMoveInput() {
  46978. this._keys = new Array();
  46979. this.keysUp = [38];
  46980. this.keysDown = [40];
  46981. this.keysLeft = [37];
  46982. this.keysRight = [39];
  46983. this.keysReset = [220];
  46984. this.panningSensibility = 50.0;
  46985. this.zoomingSensibility = 25.0;
  46986. this.useAltToZoom = true;
  46987. }
  46988. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46989. var _this = this;
  46990. if (this._onCanvasBlurObserver) {
  46991. return;
  46992. }
  46993. this._scene = this.camera.getScene();
  46994. this._engine = this._scene.getEngine();
  46995. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46996. _this._keys = [];
  46997. });
  46998. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46999. var evt = info.event;
  47000. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47001. _this._ctrlPressed = evt.ctrlKey;
  47002. _this._altPressed = evt.altKey;
  47003. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47004. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47005. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47006. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47007. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47008. var index = _this._keys.indexOf(evt.keyCode);
  47009. if (index === -1) {
  47010. _this._keys.push(evt.keyCode);
  47011. }
  47012. if (evt.preventDefault) {
  47013. if (!noPreventDefault) {
  47014. evt.preventDefault();
  47015. }
  47016. }
  47017. }
  47018. }
  47019. else {
  47020. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47021. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47022. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47023. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47024. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47025. var index = _this._keys.indexOf(evt.keyCode);
  47026. if (index >= 0) {
  47027. _this._keys.splice(index, 1);
  47028. }
  47029. if (evt.preventDefault) {
  47030. if (!noPreventDefault) {
  47031. evt.preventDefault();
  47032. }
  47033. }
  47034. }
  47035. }
  47036. });
  47037. };
  47038. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47039. if (this._scene) {
  47040. if (this._onKeyboardObserver) {
  47041. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47042. }
  47043. if (this._onCanvasBlurObserver) {
  47044. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47045. }
  47046. this._onKeyboardObserver = null;
  47047. this._onCanvasBlurObserver = null;
  47048. }
  47049. this._keys = [];
  47050. };
  47051. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47052. if (this._onKeyboardObserver) {
  47053. var camera = this.camera;
  47054. for (var index = 0; index < this._keys.length; index++) {
  47055. var keyCode = this._keys[index];
  47056. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47057. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47058. camera.inertialPanningX -= 1 / this.panningSensibility;
  47059. }
  47060. else {
  47061. camera.inertialAlphaOffset -= 0.01;
  47062. }
  47063. }
  47064. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47065. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47066. camera.inertialPanningY += 1 / this.panningSensibility;
  47067. }
  47068. else if (this._altPressed && this.useAltToZoom) {
  47069. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47070. }
  47071. else {
  47072. camera.inertialBetaOffset -= 0.01;
  47073. }
  47074. }
  47075. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47076. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47077. camera.inertialPanningX += 1 / this.panningSensibility;
  47078. }
  47079. else {
  47080. camera.inertialAlphaOffset += 0.01;
  47081. }
  47082. }
  47083. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47084. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47085. camera.inertialPanningY -= 1 / this.panningSensibility;
  47086. }
  47087. else if (this._altPressed && this.useAltToZoom) {
  47088. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47089. }
  47090. else {
  47091. camera.inertialBetaOffset += 0.01;
  47092. }
  47093. }
  47094. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47095. camera.restoreState();
  47096. }
  47097. }
  47098. }
  47099. };
  47100. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47101. return "ArcRotateCameraKeyboardMoveInput";
  47102. };
  47103. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47104. return "keyboard";
  47105. };
  47106. __decorate([
  47107. BABYLON.serialize()
  47108. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47109. __decorate([
  47110. BABYLON.serialize()
  47111. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47112. __decorate([
  47113. BABYLON.serialize()
  47114. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47115. __decorate([
  47116. BABYLON.serialize()
  47117. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47118. __decorate([
  47119. BABYLON.serialize()
  47120. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47121. __decorate([
  47122. BABYLON.serialize()
  47123. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47124. __decorate([
  47125. BABYLON.serialize()
  47126. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47127. __decorate([
  47128. BABYLON.serialize()
  47129. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47130. return ArcRotateCameraKeyboardMoveInput;
  47131. }());
  47132. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47133. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47134. })(BABYLON || (BABYLON = {}));
  47135. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47136. var BABYLON;
  47137. (function (BABYLON) {
  47138. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47139. function ArcRotateCameraMouseWheelInput() {
  47140. this.wheelPrecision = 3.0;
  47141. /**
  47142. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47143. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47144. */
  47145. this.wheelDeltaPercentage = 0;
  47146. }
  47147. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47148. var _this = this;
  47149. this._wheel = function (p, s) {
  47150. //sanity check - this should be a PointerWheel event.
  47151. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47152. return;
  47153. var event = p.event;
  47154. var delta = 0;
  47155. if (event.wheelDelta) {
  47156. if (_this.wheelDeltaPercentage) {
  47157. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47158. if (event.wheelDelta > 0) {
  47159. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47160. }
  47161. else {
  47162. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47163. }
  47164. }
  47165. else {
  47166. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47167. }
  47168. }
  47169. else if (event.detail) {
  47170. delta = -event.detail / _this.wheelPrecision;
  47171. }
  47172. if (delta)
  47173. _this.camera.inertialRadiusOffset += delta;
  47174. if (event.preventDefault) {
  47175. if (!noPreventDefault) {
  47176. event.preventDefault();
  47177. }
  47178. }
  47179. };
  47180. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47181. };
  47182. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47183. if (this._observer && element) {
  47184. this.camera.getScene().onPointerObservable.remove(this._observer);
  47185. this._observer = null;
  47186. this._wheel = null;
  47187. }
  47188. };
  47189. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47190. return "ArcRotateCameraMouseWheelInput";
  47191. };
  47192. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47193. return "mousewheel";
  47194. };
  47195. __decorate([
  47196. BABYLON.serialize()
  47197. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47198. __decorate([
  47199. BABYLON.serialize()
  47200. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47201. return ArcRotateCameraMouseWheelInput;
  47202. }());
  47203. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47204. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47205. })(BABYLON || (BABYLON = {}));
  47206. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47207. var BABYLON;
  47208. (function (BABYLON) {
  47209. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47210. function ArcRotateCameraPointersInput() {
  47211. this.buttons = [0, 1, 2];
  47212. this.angularSensibilityX = 1000.0;
  47213. this.angularSensibilityY = 1000.0;
  47214. this.pinchPrecision = 12.0;
  47215. /**
  47216. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47217. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47218. */
  47219. this.pinchDeltaPercentage = 0;
  47220. this.panningSensibility = 1000.0;
  47221. this.multiTouchPanning = true;
  47222. this.multiTouchPanAndZoom = true;
  47223. this._isPanClick = false;
  47224. this.pinchInwards = true;
  47225. }
  47226. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47227. var _this = this;
  47228. var engine = this.camera.getEngine();
  47229. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47230. var pointA = null;
  47231. var pointB = null;
  47232. var previousPinchSquaredDistance = 0;
  47233. var initialDistance = 0;
  47234. var twoFingerActivityCount = 0;
  47235. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47236. this._pointerInput = function (p, s) {
  47237. var evt = p.event;
  47238. var isTouch = p.event.pointerType === "touch";
  47239. if (engine.isInVRExclusivePointerMode) {
  47240. return;
  47241. }
  47242. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47243. return;
  47244. }
  47245. var srcElement = (evt.srcElement || evt.target);
  47246. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47247. try {
  47248. srcElement.setPointerCapture(evt.pointerId);
  47249. }
  47250. catch (e) {
  47251. //Nothing to do with the error. Execution will continue.
  47252. }
  47253. // Manage panning with pan button click
  47254. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47255. // manage pointers
  47256. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47257. if (pointA === null) {
  47258. pointA = cacheSoloPointer;
  47259. }
  47260. else if (pointB === null) {
  47261. pointB = cacheSoloPointer;
  47262. }
  47263. if (!noPreventDefault) {
  47264. evt.preventDefault();
  47265. element.focus();
  47266. }
  47267. }
  47268. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47269. _this.camera.restoreState();
  47270. }
  47271. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47272. try {
  47273. srcElement.releasePointerCapture(evt.pointerId);
  47274. }
  47275. catch (e) {
  47276. //Nothing to do with the error.
  47277. }
  47278. cacheSoloPointer = null;
  47279. previousPinchSquaredDistance = 0;
  47280. previousMultiTouchPanPosition.isPaning = false;
  47281. previousMultiTouchPanPosition.isPinching = false;
  47282. twoFingerActivityCount = 0;
  47283. initialDistance = 0;
  47284. if (!isTouch) {
  47285. pointB = null; // Mouse and pen are mono pointer
  47286. }
  47287. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47288. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47289. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47290. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47291. if (engine._badOS) {
  47292. pointA = pointB = null;
  47293. }
  47294. else {
  47295. //only remove the impacted pointer in case of multitouch allowing on most
  47296. //platforms switching from rotate to zoom and pan seamlessly.
  47297. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47298. pointA = pointB;
  47299. pointB = null;
  47300. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47301. }
  47302. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47303. pointB = null;
  47304. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47305. }
  47306. else {
  47307. pointA = pointB = null;
  47308. }
  47309. }
  47310. if (!noPreventDefault) {
  47311. evt.preventDefault();
  47312. }
  47313. }
  47314. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47315. if (!noPreventDefault) {
  47316. evt.preventDefault();
  47317. }
  47318. // One button down
  47319. if (pointA && pointB === null && cacheSoloPointer) {
  47320. if (_this.panningSensibility !== 0 &&
  47321. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47322. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47323. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47324. }
  47325. else {
  47326. var offsetX = evt.clientX - cacheSoloPointer.x;
  47327. var offsetY = evt.clientY - cacheSoloPointer.y;
  47328. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47329. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47330. }
  47331. cacheSoloPointer.x = evt.clientX;
  47332. cacheSoloPointer.y = evt.clientY;
  47333. }
  47334. // Two buttons down: pinch/pan
  47335. else if (pointA && pointB) {
  47336. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47337. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47338. ed.x = evt.clientX;
  47339. ed.y = evt.clientY;
  47340. var direction = _this.pinchInwards ? 1 : -1;
  47341. var distX = pointA.x - pointB.x;
  47342. var distY = pointA.y - pointB.y;
  47343. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47344. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47345. if (previousPinchSquaredDistance === 0) {
  47346. initialDistance = pinchDistance;
  47347. previousPinchSquaredDistance = pinchSquaredDistance;
  47348. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47349. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47350. return;
  47351. }
  47352. if (_this.multiTouchPanAndZoom) {
  47353. if (_this.pinchDeltaPercentage) {
  47354. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47355. }
  47356. else {
  47357. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47358. (_this.pinchPrecision *
  47359. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47360. direction);
  47361. }
  47362. if (_this.panningSensibility !== 0) {
  47363. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47364. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47365. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47366. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47367. previousMultiTouchPanPosition.x = pointersCenterX;
  47368. previousMultiTouchPanPosition.y = pointersCenterY;
  47369. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47370. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47371. }
  47372. }
  47373. else {
  47374. twoFingerActivityCount++;
  47375. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47376. if (_this.pinchDeltaPercentage) {
  47377. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47378. }
  47379. else {
  47380. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47381. (_this.pinchPrecision *
  47382. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47383. direction);
  47384. }
  47385. previousMultiTouchPanPosition.isPaning = false;
  47386. previousMultiTouchPanPosition.isPinching = true;
  47387. }
  47388. else {
  47389. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47390. if (!previousMultiTouchPanPosition.isPaning) {
  47391. previousMultiTouchPanPosition.isPaning = true;
  47392. previousMultiTouchPanPosition.isPinching = false;
  47393. previousMultiTouchPanPosition.x = ed.x;
  47394. previousMultiTouchPanPosition.y = ed.y;
  47395. return;
  47396. }
  47397. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47398. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47399. }
  47400. }
  47401. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47402. previousMultiTouchPanPosition.x = ed.x;
  47403. previousMultiTouchPanPosition.y = ed.y;
  47404. }
  47405. }
  47406. previousPinchSquaredDistance = pinchSquaredDistance;
  47407. }
  47408. }
  47409. };
  47410. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47411. this._onContextMenu = function (evt) {
  47412. evt.preventDefault();
  47413. };
  47414. if (!this.camera._useCtrlForPanning) {
  47415. element.addEventListener("contextmenu", this._onContextMenu, false);
  47416. }
  47417. this._onLostFocus = function () {
  47418. //this._keys = [];
  47419. pointA = pointB = null;
  47420. previousPinchSquaredDistance = 0;
  47421. previousMultiTouchPanPosition.isPaning = false;
  47422. previousMultiTouchPanPosition.isPinching = false;
  47423. twoFingerActivityCount = 0;
  47424. cacheSoloPointer = null;
  47425. initialDistance = 0;
  47426. };
  47427. this._onMouseMove = function (evt) {
  47428. if (!engine.isPointerLock) {
  47429. return;
  47430. }
  47431. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47432. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47433. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47434. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47435. if (!noPreventDefault) {
  47436. evt.preventDefault();
  47437. }
  47438. };
  47439. this._onGestureStart = function (e) {
  47440. if (window.MSGesture === undefined) {
  47441. return;
  47442. }
  47443. if (!_this._MSGestureHandler) {
  47444. _this._MSGestureHandler = new MSGesture();
  47445. _this._MSGestureHandler.target = element;
  47446. }
  47447. _this._MSGestureHandler.addPointer(e.pointerId);
  47448. };
  47449. this._onGesture = function (e) {
  47450. _this.camera.radius *= e.scale;
  47451. if (e.preventDefault) {
  47452. if (!noPreventDefault) {
  47453. e.stopPropagation();
  47454. e.preventDefault();
  47455. }
  47456. }
  47457. };
  47458. element.addEventListener("mousemove", this._onMouseMove, false);
  47459. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47460. element.addEventListener("MSGestureChange", this._onGesture, false);
  47461. BABYLON.Tools.RegisterTopRootEvents([
  47462. { name: "blur", handler: this._onLostFocus }
  47463. ]);
  47464. };
  47465. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47466. if (this._onLostFocus) {
  47467. BABYLON.Tools.UnregisterTopRootEvents([
  47468. { name: "blur", handler: this._onLostFocus }
  47469. ]);
  47470. }
  47471. if (element && this._observer) {
  47472. this.camera.getScene().onPointerObservable.remove(this._observer);
  47473. this._observer = null;
  47474. if (this._onContextMenu) {
  47475. element.removeEventListener("contextmenu", this._onContextMenu);
  47476. }
  47477. if (this._onMouseMove) {
  47478. element.removeEventListener("mousemove", this._onMouseMove);
  47479. }
  47480. if (this._onGestureStart) {
  47481. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47482. }
  47483. if (this._onGesture) {
  47484. element.removeEventListener("MSGestureChange", this._onGesture);
  47485. }
  47486. this._isPanClick = false;
  47487. this.pinchInwards = true;
  47488. this._onMouseMove = null;
  47489. this._onGestureStart = null;
  47490. this._onGesture = null;
  47491. this._MSGestureHandler = null;
  47492. this._onLostFocus = null;
  47493. this._onContextMenu = null;
  47494. }
  47495. };
  47496. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47497. return "ArcRotateCameraPointersInput";
  47498. };
  47499. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47500. return "pointers";
  47501. };
  47502. __decorate([
  47503. BABYLON.serialize()
  47504. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47505. __decorate([
  47506. BABYLON.serialize()
  47507. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47508. __decorate([
  47509. BABYLON.serialize()
  47510. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47511. __decorate([
  47512. BABYLON.serialize()
  47513. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47514. __decorate([
  47515. BABYLON.serialize()
  47516. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47517. __decorate([
  47518. BABYLON.serialize()
  47519. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47520. __decorate([
  47521. BABYLON.serialize()
  47522. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47523. __decorate([
  47524. BABYLON.serialize()
  47525. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47526. return ArcRotateCameraPointersInput;
  47527. }());
  47528. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47529. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47530. })(BABYLON || (BABYLON = {}));
  47531. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47532. var BABYLON;
  47533. (function (BABYLON) {
  47534. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47535. __extends(ArcRotateCameraInputsManager, _super);
  47536. function ArcRotateCameraInputsManager(camera) {
  47537. return _super.call(this, camera) || this;
  47538. }
  47539. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47540. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47541. return this;
  47542. };
  47543. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47544. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47545. return this;
  47546. };
  47547. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47548. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47549. return this;
  47550. };
  47551. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47552. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47553. return this;
  47554. };
  47555. return ArcRotateCameraInputsManager;
  47556. }(BABYLON.CameraInputsManager));
  47557. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47558. })(BABYLON || (BABYLON = {}));
  47559. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47560. var BABYLON;
  47561. (function (BABYLON) {
  47562. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47563. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47564. });
  47565. var ArcRotateCamera = /** @class */ (function (_super) {
  47566. __extends(ArcRotateCamera, _super);
  47567. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47568. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47569. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47570. _this.inertialAlphaOffset = 0;
  47571. _this.inertialBetaOffset = 0;
  47572. _this.inertialRadiusOffset = 0;
  47573. _this.lowerAlphaLimit = null;
  47574. _this.upperAlphaLimit = null;
  47575. _this.lowerBetaLimit = 0.01;
  47576. _this.upperBetaLimit = Math.PI;
  47577. _this.lowerRadiusLimit = null;
  47578. _this.upperRadiusLimit = null;
  47579. _this.inertialPanningX = 0;
  47580. _this.inertialPanningY = 0;
  47581. _this.pinchToPanMaxDistance = 20;
  47582. _this.panningDistanceLimit = null;
  47583. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47584. _this.panningInertia = 0.9;
  47585. //-- end properties for backward compatibility for inputs
  47586. _this.zoomOnFactor = 1;
  47587. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47588. _this.allowUpsideDown = true;
  47589. /** @hidden */
  47590. _this._viewMatrix = new BABYLON.Matrix();
  47591. // Panning
  47592. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47593. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47594. _this.checkCollisions = false;
  47595. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47596. _this._previousPosition = BABYLON.Vector3.Zero();
  47597. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47598. _this._newPosition = BABYLON.Vector3.Zero();
  47599. _this._computationVector = BABYLON.Vector3.Zero();
  47600. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47601. if (collidedMesh === void 0) { collidedMesh = null; }
  47602. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47603. newPosition.multiplyInPlace(_this._collider._radius);
  47604. }
  47605. if (!collidedMesh) {
  47606. _this._previousPosition.copyFrom(_this.position);
  47607. }
  47608. else {
  47609. _this.setPosition(newPosition);
  47610. if (_this.onCollide) {
  47611. _this.onCollide(collidedMesh);
  47612. }
  47613. }
  47614. // Recompute because of constraints
  47615. var cosa = Math.cos(_this.alpha);
  47616. var sina = Math.sin(_this.alpha);
  47617. var cosb = Math.cos(_this.beta);
  47618. var sinb = Math.sin(_this.beta);
  47619. if (sinb === 0) {
  47620. sinb = 0.0001;
  47621. }
  47622. var target = _this._getTargetPosition();
  47623. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47624. target.addToRef(_this._computationVector, _this._newPosition);
  47625. _this.position.copyFrom(_this._newPosition);
  47626. var up = _this.upVector;
  47627. if (_this.allowUpsideDown && _this.beta < 0) {
  47628. up = up.clone();
  47629. up = up.negate();
  47630. }
  47631. _this._computeViewMatrix(_this.position, target, up);
  47632. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47633. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47634. _this._collisionTriggered = false;
  47635. };
  47636. _this._target = BABYLON.Vector3.Zero();
  47637. if (target) {
  47638. _this.setTarget(target);
  47639. }
  47640. _this.alpha = alpha;
  47641. _this.beta = beta;
  47642. _this.radius = radius;
  47643. _this.getViewMatrix();
  47644. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47645. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47646. return _this;
  47647. }
  47648. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47649. get: function () {
  47650. return this._target;
  47651. },
  47652. set: function (value) {
  47653. this.setTarget(value);
  47654. },
  47655. enumerable: true,
  47656. configurable: true
  47657. });
  47658. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47659. //-- begin properties for backward compatibility for inputs
  47660. get: function () {
  47661. var pointers = this.inputs.attached["pointers"];
  47662. if (pointers)
  47663. return pointers.angularSensibilityX;
  47664. return 0;
  47665. },
  47666. set: function (value) {
  47667. var pointers = this.inputs.attached["pointers"];
  47668. if (pointers) {
  47669. pointers.angularSensibilityX = value;
  47670. }
  47671. },
  47672. enumerable: true,
  47673. configurable: true
  47674. });
  47675. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47676. get: function () {
  47677. var pointers = this.inputs.attached["pointers"];
  47678. if (pointers)
  47679. return pointers.angularSensibilityY;
  47680. return 0;
  47681. },
  47682. set: function (value) {
  47683. var pointers = this.inputs.attached["pointers"];
  47684. if (pointers) {
  47685. pointers.angularSensibilityY = value;
  47686. }
  47687. },
  47688. enumerable: true,
  47689. configurable: true
  47690. });
  47691. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47692. get: function () {
  47693. var pointers = this.inputs.attached["pointers"];
  47694. if (pointers)
  47695. return pointers.pinchPrecision;
  47696. return 0;
  47697. },
  47698. set: function (value) {
  47699. var pointers = this.inputs.attached["pointers"];
  47700. if (pointers) {
  47701. pointers.pinchPrecision = value;
  47702. }
  47703. },
  47704. enumerable: true,
  47705. configurable: true
  47706. });
  47707. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47708. get: function () {
  47709. var pointers = this.inputs.attached["pointers"];
  47710. if (pointers)
  47711. return pointers.pinchDeltaPercentage;
  47712. return 0;
  47713. },
  47714. set: function (value) {
  47715. var pointers = this.inputs.attached["pointers"];
  47716. if (pointers) {
  47717. pointers.pinchDeltaPercentage = value;
  47718. }
  47719. },
  47720. enumerable: true,
  47721. configurable: true
  47722. });
  47723. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47724. get: function () {
  47725. var pointers = this.inputs.attached["pointers"];
  47726. if (pointers)
  47727. return pointers.panningSensibility;
  47728. return 0;
  47729. },
  47730. set: function (value) {
  47731. var pointers = this.inputs.attached["pointers"];
  47732. if (pointers) {
  47733. pointers.panningSensibility = value;
  47734. }
  47735. },
  47736. enumerable: true,
  47737. configurable: true
  47738. });
  47739. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47740. get: function () {
  47741. var keyboard = this.inputs.attached["keyboard"];
  47742. if (keyboard)
  47743. return keyboard.keysUp;
  47744. return [];
  47745. },
  47746. set: function (value) {
  47747. var keyboard = this.inputs.attached["keyboard"];
  47748. if (keyboard)
  47749. keyboard.keysUp = value;
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47755. get: function () {
  47756. var keyboard = this.inputs.attached["keyboard"];
  47757. if (keyboard)
  47758. return keyboard.keysDown;
  47759. return [];
  47760. },
  47761. set: function (value) {
  47762. var keyboard = this.inputs.attached["keyboard"];
  47763. if (keyboard)
  47764. keyboard.keysDown = value;
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47770. get: function () {
  47771. var keyboard = this.inputs.attached["keyboard"];
  47772. if (keyboard)
  47773. return keyboard.keysLeft;
  47774. return [];
  47775. },
  47776. set: function (value) {
  47777. var keyboard = this.inputs.attached["keyboard"];
  47778. if (keyboard)
  47779. keyboard.keysLeft = value;
  47780. },
  47781. enumerable: true,
  47782. configurable: true
  47783. });
  47784. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47785. get: function () {
  47786. var keyboard = this.inputs.attached["keyboard"];
  47787. if (keyboard)
  47788. return keyboard.keysRight;
  47789. return [];
  47790. },
  47791. set: function (value) {
  47792. var keyboard = this.inputs.attached["keyboard"];
  47793. if (keyboard)
  47794. keyboard.keysRight = value;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47800. get: function () {
  47801. var mousewheel = this.inputs.attached["mousewheel"];
  47802. if (mousewheel)
  47803. return mousewheel.wheelPrecision;
  47804. return 0;
  47805. },
  47806. set: function (value) {
  47807. var mousewheel = this.inputs.attached["mousewheel"];
  47808. if (mousewheel)
  47809. mousewheel.wheelPrecision = value;
  47810. },
  47811. enumerable: true,
  47812. configurable: true
  47813. });
  47814. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47815. get: function () {
  47816. var mousewheel = this.inputs.attached["mousewheel"];
  47817. if (mousewheel)
  47818. return mousewheel.wheelDeltaPercentage;
  47819. return 0;
  47820. },
  47821. set: function (value) {
  47822. var mousewheel = this.inputs.attached["mousewheel"];
  47823. if (mousewheel)
  47824. mousewheel.wheelDeltaPercentage = value;
  47825. },
  47826. enumerable: true,
  47827. configurable: true
  47828. });
  47829. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47830. get: function () {
  47831. return this._bouncingBehavior;
  47832. },
  47833. enumerable: true,
  47834. configurable: true
  47835. });
  47836. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47837. get: function () {
  47838. return this._bouncingBehavior != null;
  47839. },
  47840. set: function (value) {
  47841. if (value === this.useBouncingBehavior) {
  47842. return;
  47843. }
  47844. if (value) {
  47845. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47846. this.addBehavior(this._bouncingBehavior);
  47847. }
  47848. else if (this._bouncingBehavior) {
  47849. this.removeBehavior(this._bouncingBehavior);
  47850. this._bouncingBehavior = null;
  47851. }
  47852. },
  47853. enumerable: true,
  47854. configurable: true
  47855. });
  47856. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47857. get: function () {
  47858. return this._framingBehavior;
  47859. },
  47860. enumerable: true,
  47861. configurable: true
  47862. });
  47863. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47864. get: function () {
  47865. return this._framingBehavior != null;
  47866. },
  47867. set: function (value) {
  47868. if (value === this.useFramingBehavior) {
  47869. return;
  47870. }
  47871. if (value) {
  47872. this._framingBehavior = new BABYLON.FramingBehavior();
  47873. this.addBehavior(this._framingBehavior);
  47874. }
  47875. else if (this._framingBehavior) {
  47876. this.removeBehavior(this._framingBehavior);
  47877. this._framingBehavior = null;
  47878. }
  47879. },
  47880. enumerable: true,
  47881. configurable: true
  47882. });
  47883. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47884. get: function () {
  47885. return this._autoRotationBehavior;
  47886. },
  47887. enumerable: true,
  47888. configurable: true
  47889. });
  47890. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47891. get: function () {
  47892. return this._autoRotationBehavior != null;
  47893. },
  47894. set: function (value) {
  47895. if (value === this.useAutoRotationBehavior) {
  47896. return;
  47897. }
  47898. if (value) {
  47899. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47900. this.addBehavior(this._autoRotationBehavior);
  47901. }
  47902. else if (this._autoRotationBehavior) {
  47903. this.removeBehavior(this._autoRotationBehavior);
  47904. this._autoRotationBehavior = null;
  47905. }
  47906. },
  47907. enumerable: true,
  47908. configurable: true
  47909. });
  47910. // Cache
  47911. /** @hidden */
  47912. ArcRotateCamera.prototype._initCache = function () {
  47913. _super.prototype._initCache.call(this);
  47914. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47915. this._cache.alpha = undefined;
  47916. this._cache.beta = undefined;
  47917. this._cache.radius = undefined;
  47918. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47919. };
  47920. /** @hidden */
  47921. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47922. if (!ignoreParentClass) {
  47923. _super.prototype._updateCache.call(this);
  47924. }
  47925. this._cache._target.copyFrom(this._getTargetPosition());
  47926. this._cache.alpha = this.alpha;
  47927. this._cache.beta = this.beta;
  47928. this._cache.radius = this.radius;
  47929. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47930. };
  47931. ArcRotateCamera.prototype._getTargetPosition = function () {
  47932. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47933. var pos = this._targetHost.getAbsolutePosition();
  47934. if (this._targetBoundingCenter) {
  47935. pos.addToRef(this._targetBoundingCenter, this._target);
  47936. }
  47937. else {
  47938. this._target.copyFrom(pos);
  47939. }
  47940. }
  47941. var lockedTargetPosition = this._getLockedTargetPosition();
  47942. if (lockedTargetPosition) {
  47943. return lockedTargetPosition;
  47944. }
  47945. return this._target;
  47946. };
  47947. ArcRotateCamera.prototype.storeState = function () {
  47948. this._storedAlpha = this.alpha;
  47949. this._storedBeta = this.beta;
  47950. this._storedRadius = this.radius;
  47951. this._storedTarget = this._getTargetPosition().clone();
  47952. return _super.prototype.storeState.call(this);
  47953. };
  47954. /**
  47955. * @hidden
  47956. * Restored camera state. You must call storeState() first
  47957. */
  47958. ArcRotateCamera.prototype._restoreStateValues = function () {
  47959. if (!_super.prototype._restoreStateValues.call(this)) {
  47960. return false;
  47961. }
  47962. this.alpha = this._storedAlpha;
  47963. this.beta = this._storedBeta;
  47964. this.radius = this._storedRadius;
  47965. this.setTarget(this._storedTarget.clone());
  47966. this.inertialAlphaOffset = 0;
  47967. this.inertialBetaOffset = 0;
  47968. this.inertialRadiusOffset = 0;
  47969. this.inertialPanningX = 0;
  47970. this.inertialPanningY = 0;
  47971. return true;
  47972. };
  47973. // Synchronized
  47974. /** @hidden */
  47975. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47976. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47977. return false;
  47978. return this._cache._target.equals(this._getTargetPosition())
  47979. && this._cache.alpha === this.alpha
  47980. && this._cache.beta === this.beta
  47981. && this._cache.radius === this.radius
  47982. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47983. };
  47984. // Methods
  47985. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47986. var _this = this;
  47987. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47988. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47989. this._useCtrlForPanning = useCtrlForPanning;
  47990. this._panningMouseButton = panningMouseButton;
  47991. this.inputs.attachElement(element, noPreventDefault);
  47992. this._reset = function () {
  47993. _this.inertialAlphaOffset = 0;
  47994. _this.inertialBetaOffset = 0;
  47995. _this.inertialRadiusOffset = 0;
  47996. _this.inertialPanningX = 0;
  47997. _this.inertialPanningY = 0;
  47998. };
  47999. };
  48000. ArcRotateCamera.prototype.detachControl = function (element) {
  48001. this.inputs.detachElement(element);
  48002. if (this._reset) {
  48003. this._reset();
  48004. }
  48005. };
  48006. /** @hidden */
  48007. ArcRotateCamera.prototype._checkInputs = function () {
  48008. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48009. if (this._collisionTriggered) {
  48010. return;
  48011. }
  48012. this.inputs.checkInputs();
  48013. // Inertia
  48014. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48015. var inertialAlphaOffset = this.inertialAlphaOffset;
  48016. if (this.beta <= 0)
  48017. inertialAlphaOffset *= -1;
  48018. if (this.getScene().useRightHandedSystem)
  48019. inertialAlphaOffset *= -1;
  48020. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48021. inertialAlphaOffset *= -1;
  48022. this.alpha += inertialAlphaOffset;
  48023. this.beta += this.inertialBetaOffset;
  48024. this.radius -= this.inertialRadiusOffset;
  48025. this.inertialAlphaOffset *= this.inertia;
  48026. this.inertialBetaOffset *= this.inertia;
  48027. this.inertialRadiusOffset *= this.inertia;
  48028. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48029. this.inertialAlphaOffset = 0;
  48030. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48031. this.inertialBetaOffset = 0;
  48032. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48033. this.inertialRadiusOffset = 0;
  48034. }
  48035. // Panning inertia
  48036. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48037. if (!this._localDirection) {
  48038. this._localDirection = BABYLON.Vector3.Zero();
  48039. this._transformedDirection = BABYLON.Vector3.Zero();
  48040. }
  48041. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48042. this._localDirection.multiplyInPlace(this.panningAxis);
  48043. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48044. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48045. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48046. if (!this.panningAxis.y) {
  48047. this._transformedDirection.y = 0;
  48048. }
  48049. if (!this._targetHost) {
  48050. if (this.panningDistanceLimit) {
  48051. this._transformedDirection.addInPlace(this._target);
  48052. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48053. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48054. this._target.copyFrom(this._transformedDirection);
  48055. }
  48056. }
  48057. else {
  48058. this._target.addInPlace(this._transformedDirection);
  48059. }
  48060. }
  48061. this.inertialPanningX *= this.panningInertia;
  48062. this.inertialPanningY *= this.panningInertia;
  48063. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48064. this.inertialPanningX = 0;
  48065. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48066. this.inertialPanningY = 0;
  48067. }
  48068. // Limits
  48069. this._checkLimits();
  48070. _super.prototype._checkInputs.call(this);
  48071. };
  48072. ArcRotateCamera.prototype._checkLimits = function () {
  48073. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48074. if (this.allowUpsideDown && this.beta > Math.PI) {
  48075. this.beta = this.beta - (2 * Math.PI);
  48076. }
  48077. }
  48078. else {
  48079. if (this.beta < this.lowerBetaLimit) {
  48080. this.beta = this.lowerBetaLimit;
  48081. }
  48082. }
  48083. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48084. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48085. this.beta = this.beta + (2 * Math.PI);
  48086. }
  48087. }
  48088. else {
  48089. if (this.beta > this.upperBetaLimit) {
  48090. this.beta = this.upperBetaLimit;
  48091. }
  48092. }
  48093. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48094. this.alpha = this.lowerAlphaLimit;
  48095. }
  48096. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48097. this.alpha = this.upperAlphaLimit;
  48098. }
  48099. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48100. this.radius = this.lowerRadiusLimit;
  48101. }
  48102. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48103. this.radius = this.upperRadiusLimit;
  48104. }
  48105. };
  48106. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48107. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48108. this.radius = this._computationVector.length();
  48109. if (this.radius === 0) {
  48110. this.radius = 0.0001; // Just to avoid division by zero
  48111. }
  48112. // Alpha
  48113. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48114. if (this._computationVector.z < 0) {
  48115. this.alpha = 2 * Math.PI - this.alpha;
  48116. }
  48117. // Beta
  48118. this.beta = Math.acos(this._computationVector.y / this.radius);
  48119. this._checkLimits();
  48120. };
  48121. ArcRotateCamera.prototype.setPosition = function (position) {
  48122. if (this.position.equals(position)) {
  48123. return;
  48124. }
  48125. this.position.copyFrom(position);
  48126. this.rebuildAnglesAndRadius();
  48127. };
  48128. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48129. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48130. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48131. if (target.getBoundingInfo) {
  48132. if (toBoundingCenter) {
  48133. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48134. }
  48135. else {
  48136. this._targetBoundingCenter = null;
  48137. }
  48138. this._targetHost = target;
  48139. this._target = this._getTargetPosition();
  48140. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48141. }
  48142. else {
  48143. var newTarget = target;
  48144. var currentTarget = this._getTargetPosition();
  48145. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48146. return;
  48147. }
  48148. this._targetHost = null;
  48149. this._target = newTarget;
  48150. this._targetBoundingCenter = null;
  48151. this.onMeshTargetChangedObservable.notifyObservers(null);
  48152. }
  48153. this.rebuildAnglesAndRadius();
  48154. };
  48155. /** @hidden */
  48156. ArcRotateCamera.prototype._getViewMatrix = function () {
  48157. // Compute
  48158. var cosa = Math.cos(this.alpha);
  48159. var sina = Math.sin(this.alpha);
  48160. var cosb = Math.cos(this.beta);
  48161. var sinb = Math.sin(this.beta);
  48162. if (sinb === 0) {
  48163. sinb = 0.0001;
  48164. }
  48165. var target = this._getTargetPosition();
  48166. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48167. target.addToRef(this._computationVector, this._newPosition);
  48168. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48169. if (!this._collider) {
  48170. this._collider = new BABYLON.Collider();
  48171. }
  48172. this._collider._radius = this.collisionRadius;
  48173. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48174. this._collisionTriggered = true;
  48175. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48176. }
  48177. else {
  48178. this.position.copyFrom(this._newPosition);
  48179. var up = this.upVector;
  48180. if (this.allowUpsideDown && sinb < 0) {
  48181. up = up.clone();
  48182. up = up.negate();
  48183. }
  48184. this._computeViewMatrix(this.position, target, up);
  48185. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48186. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48187. }
  48188. this._currentTarget = target;
  48189. return this._viewMatrix;
  48190. };
  48191. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48192. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48193. meshes = meshes || this.getScene().meshes;
  48194. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48195. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48196. this.radius = distance * this.zoomOnFactor;
  48197. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48198. };
  48199. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48200. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48201. var meshesOrMinMaxVector;
  48202. var distance;
  48203. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48204. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48205. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48206. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48207. }
  48208. else { //minMaxVector and distance
  48209. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48210. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48211. distance = minMaxVectorAndDistance.distance;
  48212. }
  48213. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48214. if (!doNotUpdateMaxZ) {
  48215. this.maxZ = distance * 2;
  48216. }
  48217. };
  48218. /**
  48219. * @override
  48220. * Override Camera.createRigCamera
  48221. */
  48222. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48223. var alphaShift = 0;
  48224. switch (this.cameraRigMode) {
  48225. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48226. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48227. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48228. case BABYLON.Camera.RIG_MODE_VR:
  48229. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48230. break;
  48231. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48232. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48233. break;
  48234. }
  48235. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48236. rigCam._cameraRigParams = {};
  48237. return rigCam;
  48238. };
  48239. /**
  48240. * @hidden
  48241. * @override
  48242. * Override Camera._updateRigCameras
  48243. */
  48244. ArcRotateCamera.prototype._updateRigCameras = function () {
  48245. var camLeft = this._rigCameras[0];
  48246. var camRight = this._rigCameras[1];
  48247. camLeft.beta = camRight.beta = this.beta;
  48248. camLeft.radius = camRight.radius = this.radius;
  48249. switch (this.cameraRigMode) {
  48250. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48251. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48252. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48253. case BABYLON.Camera.RIG_MODE_VR:
  48254. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48255. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48256. break;
  48257. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48258. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48259. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48260. break;
  48261. }
  48262. _super.prototype._updateRigCameras.call(this);
  48263. };
  48264. ArcRotateCamera.prototype.dispose = function () {
  48265. this.inputs.clear();
  48266. _super.prototype.dispose.call(this);
  48267. };
  48268. ArcRotateCamera.prototype.getClassName = function () {
  48269. return "ArcRotateCamera";
  48270. };
  48271. __decorate([
  48272. BABYLON.serialize()
  48273. ], ArcRotateCamera.prototype, "alpha", void 0);
  48274. __decorate([
  48275. BABYLON.serialize()
  48276. ], ArcRotateCamera.prototype, "beta", void 0);
  48277. __decorate([
  48278. BABYLON.serialize()
  48279. ], ArcRotateCamera.prototype, "radius", void 0);
  48280. __decorate([
  48281. BABYLON.serializeAsVector3("target")
  48282. ], ArcRotateCamera.prototype, "_target", void 0);
  48283. __decorate([
  48284. BABYLON.serialize()
  48285. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48286. __decorate([
  48287. BABYLON.serialize()
  48288. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48289. __decorate([
  48290. BABYLON.serialize()
  48291. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48292. __decorate([
  48293. BABYLON.serialize()
  48294. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48295. __decorate([
  48296. BABYLON.serialize()
  48297. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48298. __decorate([
  48299. BABYLON.serialize()
  48300. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48301. __decorate([
  48302. BABYLON.serialize()
  48303. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48304. __decorate([
  48305. BABYLON.serialize()
  48306. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48307. __decorate([
  48308. BABYLON.serialize()
  48309. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48310. __decorate([
  48311. BABYLON.serialize()
  48312. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48313. __decorate([
  48314. BABYLON.serialize()
  48315. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48316. __decorate([
  48317. BABYLON.serialize()
  48318. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48319. __decorate([
  48320. BABYLON.serialize()
  48321. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48322. __decorate([
  48323. BABYLON.serializeAsVector3()
  48324. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48325. __decorate([
  48326. BABYLON.serialize()
  48327. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48328. __decorate([
  48329. BABYLON.serialize()
  48330. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48331. __decorate([
  48332. BABYLON.serialize()
  48333. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48334. return ArcRotateCamera;
  48335. }(BABYLON.TargetCamera));
  48336. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48337. })(BABYLON || (BABYLON = {}));
  48338. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48339. var BABYLON;
  48340. (function (BABYLON) {
  48341. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48342. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48343. });
  48344. /**
  48345. * The HemisphericLight simulates the ambient environment light,
  48346. * so the passed direction is the light reflection direction, not the incoming direction.
  48347. */
  48348. var HemisphericLight = /** @class */ (function (_super) {
  48349. __extends(HemisphericLight, _super);
  48350. /**
  48351. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48352. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48353. * The HemisphericLight can't cast shadows.
  48354. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48355. * @param name The friendly name of the light
  48356. * @param direction The direction of the light reflection
  48357. * @param scene The scene the light belongs to
  48358. */
  48359. function HemisphericLight(name, direction, scene) {
  48360. var _this = _super.call(this, name, scene) || this;
  48361. /**
  48362. * The groundColor is the light in the opposite direction to the one specified during creation.
  48363. * 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.
  48364. */
  48365. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48366. _this.direction = direction || BABYLON.Vector3.Up();
  48367. return _this;
  48368. }
  48369. HemisphericLight.prototype._buildUniformLayout = function () {
  48370. this._uniformBuffer.addUniform("vLightData", 4);
  48371. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48372. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48373. this._uniformBuffer.addUniform("vLightGround", 3);
  48374. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48375. this._uniformBuffer.addUniform("depthValues", 2);
  48376. this._uniformBuffer.create();
  48377. };
  48378. /**
  48379. * Returns the string "HemisphericLight".
  48380. * @return The class name
  48381. */
  48382. HemisphericLight.prototype.getClassName = function () {
  48383. return "HemisphericLight";
  48384. };
  48385. /**
  48386. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48387. * Returns the updated direction.
  48388. * @param target The target the direction should point to
  48389. * @return The computed direction
  48390. */
  48391. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48392. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48393. return this.direction;
  48394. };
  48395. /**
  48396. * Returns the shadow generator associated to the light.
  48397. * @returns Always null for hemispheric lights because it does not support shadows.
  48398. */
  48399. HemisphericLight.prototype.getShadowGenerator = function () {
  48400. return null;
  48401. };
  48402. /**
  48403. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48404. * @param effect The effect to update
  48405. * @param lightIndex The index of the light in the effect to update
  48406. * @returns The hemispheric light
  48407. */
  48408. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48409. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48410. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48411. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48412. return this;
  48413. };
  48414. /**
  48415. * Computes the world matrix of the node
  48416. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48417. * @param useWasUpdatedFlag defines a reserved property
  48418. * @returns the world matrix
  48419. */
  48420. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  48421. if (!this._worldMatrix) {
  48422. this._worldMatrix = BABYLON.Matrix.Identity();
  48423. }
  48424. return this._worldMatrix;
  48425. };
  48426. /**
  48427. * Returns the integer 3.
  48428. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48429. */
  48430. HemisphericLight.prototype.getTypeID = function () {
  48431. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48432. };
  48433. /**
  48434. * Prepares the list of defines specific to the light type.
  48435. * @param defines the list of defines
  48436. * @param lightIndex defines the index of the light for the effect
  48437. */
  48438. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48439. defines["HEMILIGHT" + lightIndex] = true;
  48440. };
  48441. __decorate([
  48442. BABYLON.serializeAsColor3()
  48443. ], HemisphericLight.prototype, "groundColor", void 0);
  48444. __decorate([
  48445. BABYLON.serializeAsVector3()
  48446. ], HemisphericLight.prototype, "direction", void 0);
  48447. return HemisphericLight;
  48448. }(BABYLON.Light));
  48449. BABYLON.HemisphericLight = HemisphericLight;
  48450. })(BABYLON || (BABYLON = {}));
  48451. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48452. var BABYLON;
  48453. (function (BABYLON) {
  48454. /**
  48455. * Base implementation IShadowLight
  48456. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48457. */
  48458. var ShadowLight = /** @class */ (function (_super) {
  48459. __extends(ShadowLight, _super);
  48460. function ShadowLight() {
  48461. var _this = _super !== null && _super.apply(this, arguments) || this;
  48462. _this._needProjectionMatrixCompute = true;
  48463. return _this;
  48464. }
  48465. ShadowLight.prototype._setPosition = function (value) {
  48466. this._position = value;
  48467. };
  48468. Object.defineProperty(ShadowLight.prototype, "position", {
  48469. /**
  48470. * Sets the position the shadow will be casted from. Also use as the light position for both
  48471. * point and spot lights.
  48472. */
  48473. get: function () {
  48474. return this._position;
  48475. },
  48476. /**
  48477. * Sets the position the shadow will be casted from. Also use as the light position for both
  48478. * point and spot lights.
  48479. */
  48480. set: function (value) {
  48481. this._setPosition(value);
  48482. },
  48483. enumerable: true,
  48484. configurable: true
  48485. });
  48486. ShadowLight.prototype._setDirection = function (value) {
  48487. this._direction = value;
  48488. };
  48489. Object.defineProperty(ShadowLight.prototype, "direction", {
  48490. /**
  48491. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48492. * Also use as the light direction on spot and directional lights.
  48493. */
  48494. get: function () {
  48495. return this._direction;
  48496. },
  48497. /**
  48498. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48499. * Also use as the light direction on spot and directional lights.
  48500. */
  48501. set: function (value) {
  48502. this._setDirection(value);
  48503. },
  48504. enumerable: true,
  48505. configurable: true
  48506. });
  48507. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48508. /**
  48509. * Gets the shadow projection clipping minimum z value.
  48510. */
  48511. get: function () {
  48512. return this._shadowMinZ;
  48513. },
  48514. /**
  48515. * Sets the shadow projection clipping minimum z value.
  48516. */
  48517. set: function (value) {
  48518. this._shadowMinZ = value;
  48519. this.forceProjectionMatrixCompute();
  48520. },
  48521. enumerable: true,
  48522. configurable: true
  48523. });
  48524. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48525. /**
  48526. * Sets the shadow projection clipping maximum z value.
  48527. */
  48528. get: function () {
  48529. return this._shadowMaxZ;
  48530. },
  48531. /**
  48532. * Gets the shadow projection clipping maximum z value.
  48533. */
  48534. set: function (value) {
  48535. this._shadowMaxZ = value;
  48536. this.forceProjectionMatrixCompute();
  48537. },
  48538. enumerable: true,
  48539. configurable: true
  48540. });
  48541. /**
  48542. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48543. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48544. */
  48545. ShadowLight.prototype.computeTransformedInformation = function () {
  48546. if (this.parent && this.parent.getWorldMatrix) {
  48547. if (!this.transformedPosition) {
  48548. this.transformedPosition = BABYLON.Vector3.Zero();
  48549. }
  48550. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48551. // In case the direction is present.
  48552. if (this.direction) {
  48553. if (!this.transformedDirection) {
  48554. this.transformedDirection = BABYLON.Vector3.Zero();
  48555. }
  48556. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48557. }
  48558. return true;
  48559. }
  48560. return false;
  48561. };
  48562. /**
  48563. * Return the depth scale used for the shadow map.
  48564. * @returns the depth scale.
  48565. */
  48566. ShadowLight.prototype.getDepthScale = function () {
  48567. return 50.0;
  48568. };
  48569. /**
  48570. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48571. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48572. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48573. */
  48574. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48575. return this.transformedDirection ? this.transformedDirection : this.direction;
  48576. };
  48577. /**
  48578. * Returns the ShadowLight absolute position in the World.
  48579. * @returns the position vector in world space
  48580. */
  48581. ShadowLight.prototype.getAbsolutePosition = function () {
  48582. return this.transformedPosition ? this.transformedPosition : this.position;
  48583. };
  48584. /**
  48585. * Sets the ShadowLight direction toward the passed target.
  48586. * @param target The point tot target in local space
  48587. * @returns the updated ShadowLight direction
  48588. */
  48589. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48590. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48591. return this.direction;
  48592. };
  48593. /**
  48594. * Returns the light rotation in euler definition.
  48595. * @returns the x y z rotation in local space.
  48596. */
  48597. ShadowLight.prototype.getRotation = function () {
  48598. this.direction.normalize();
  48599. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48600. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48601. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48602. };
  48603. /**
  48604. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48605. * @returns true if a cube texture needs to be use
  48606. */
  48607. ShadowLight.prototype.needCube = function () {
  48608. return false;
  48609. };
  48610. /**
  48611. * Detects if the projection matrix requires to be recomputed this frame.
  48612. * @returns true if it requires to be recomputed otherwise, false.
  48613. */
  48614. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48615. return this._needProjectionMatrixCompute;
  48616. };
  48617. /**
  48618. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48619. */
  48620. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48621. this._needProjectionMatrixCompute = true;
  48622. };
  48623. /** @hidden */
  48624. ShadowLight.prototype._initCache = function () {
  48625. _super.prototype._initCache.call(this);
  48626. this._cache.position = BABYLON.Vector3.Zero();
  48627. };
  48628. /** @hidden */
  48629. ShadowLight.prototype._isSynchronized = function () {
  48630. if (!this._cache.position.equals(this.position))
  48631. return false;
  48632. return true;
  48633. };
  48634. /**
  48635. * Computes the world matrix of the node
  48636. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48637. * @returns the world matrix
  48638. */
  48639. ShadowLight.prototype.computeWorldMatrix = function (force) {
  48640. if (!force && this.isSynchronized()) {
  48641. this._currentRenderId = this.getScene().getRenderId();
  48642. return this._worldMatrix;
  48643. }
  48644. this._updateCache();
  48645. this._cache.position.copyFrom(this.position);
  48646. if (!this._worldMatrix) {
  48647. this._worldMatrix = BABYLON.Matrix.Identity();
  48648. }
  48649. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48650. if (this.parent && this.parent.getWorldMatrix) {
  48651. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  48652. this._markSyncedWithParent();
  48653. }
  48654. // Cache the determinant
  48655. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  48656. return this._worldMatrix;
  48657. };
  48658. /**
  48659. * Gets the minZ used for shadow according to both the scene and the light.
  48660. * @param activeCamera The camera we are returning the min for
  48661. * @returns the depth min z
  48662. */
  48663. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48664. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48665. };
  48666. /**
  48667. * Gets the maxZ used for shadow according to both the scene and the light.
  48668. * @param activeCamera The camera we are returning the max for
  48669. * @returns the depth max z
  48670. */
  48671. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48672. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48673. };
  48674. /**
  48675. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48676. * @param matrix The materix to updated with the projection information
  48677. * @param viewMatrix The transform matrix of the light
  48678. * @param renderList The list of mesh to render in the map
  48679. * @returns The current light
  48680. */
  48681. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48682. if (this.customProjectionMatrixBuilder) {
  48683. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48684. }
  48685. else {
  48686. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48687. }
  48688. return this;
  48689. };
  48690. __decorate([
  48691. BABYLON.serializeAsVector3()
  48692. ], ShadowLight.prototype, "position", null);
  48693. __decorate([
  48694. BABYLON.serializeAsVector3()
  48695. ], ShadowLight.prototype, "direction", null);
  48696. __decorate([
  48697. BABYLON.serialize()
  48698. ], ShadowLight.prototype, "shadowMinZ", null);
  48699. __decorate([
  48700. BABYLON.serialize()
  48701. ], ShadowLight.prototype, "shadowMaxZ", null);
  48702. return ShadowLight;
  48703. }(BABYLON.Light));
  48704. BABYLON.ShadowLight = ShadowLight;
  48705. })(BABYLON || (BABYLON = {}));
  48706. //# sourceMappingURL=babylon.shadowLight.js.map
  48707. var BABYLON;
  48708. (function (BABYLON) {
  48709. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48710. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48711. });
  48712. /**
  48713. * A point light is a light defined by an unique point in world space.
  48714. * The light is emitted in every direction from this point.
  48715. * A good example of a point light is a standard light bulb.
  48716. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48717. */
  48718. var PointLight = /** @class */ (function (_super) {
  48719. __extends(PointLight, _super);
  48720. /**
  48721. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48722. * A PointLight emits the light in every direction.
  48723. * It can cast shadows.
  48724. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48725. * ```javascript
  48726. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48727. * ```
  48728. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48729. * @param name The light friendly name
  48730. * @param position The position of the point light in the scene
  48731. * @param scene The scene the lights belongs to
  48732. */
  48733. function PointLight(name, position, scene) {
  48734. var _this = _super.call(this, name, scene) || this;
  48735. _this._shadowAngle = Math.PI / 2;
  48736. _this.position = position;
  48737. return _this;
  48738. }
  48739. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48740. /**
  48741. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48742. * This specifies what angle the shadow will use to be created.
  48743. *
  48744. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48745. */
  48746. get: function () {
  48747. return this._shadowAngle;
  48748. },
  48749. /**
  48750. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48751. * This specifies what angle the shadow will use to be created.
  48752. *
  48753. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48754. */
  48755. set: function (value) {
  48756. this._shadowAngle = value;
  48757. this.forceProjectionMatrixCompute();
  48758. },
  48759. enumerable: true,
  48760. configurable: true
  48761. });
  48762. Object.defineProperty(PointLight.prototype, "direction", {
  48763. /**
  48764. * Gets the direction if it has been set.
  48765. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48766. */
  48767. get: function () {
  48768. return this._direction;
  48769. },
  48770. /**
  48771. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48772. */
  48773. set: function (value) {
  48774. var previousNeedCube = this.needCube();
  48775. this._direction = value;
  48776. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48777. this._shadowGenerator.recreateShadowMap();
  48778. }
  48779. },
  48780. enumerable: true,
  48781. configurable: true
  48782. });
  48783. /**
  48784. * Returns the string "PointLight"
  48785. * @returns the class name
  48786. */
  48787. PointLight.prototype.getClassName = function () {
  48788. return "PointLight";
  48789. };
  48790. /**
  48791. * Returns the integer 0.
  48792. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48793. */
  48794. PointLight.prototype.getTypeID = function () {
  48795. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48796. };
  48797. /**
  48798. * Specifies wether or not the shadowmap should be a cube texture.
  48799. * @returns true if the shadowmap needs to be a cube texture.
  48800. */
  48801. PointLight.prototype.needCube = function () {
  48802. return !this.direction;
  48803. };
  48804. /**
  48805. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48806. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48807. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48808. */
  48809. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48810. if (this.direction) {
  48811. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48812. }
  48813. else {
  48814. switch (faceIndex) {
  48815. case 0:
  48816. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48817. case 1:
  48818. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48819. case 2:
  48820. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48821. case 3:
  48822. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48823. case 4:
  48824. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48825. case 5:
  48826. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48827. }
  48828. }
  48829. return BABYLON.Vector3.Zero();
  48830. };
  48831. /**
  48832. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48833. * - fov = PI / 2
  48834. * - aspect ratio : 1.0
  48835. * - z-near and far equal to the active camera minZ and maxZ.
  48836. * Returns the PointLight.
  48837. */
  48838. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48839. var activeCamera = this.getScene().activeCamera;
  48840. if (!activeCamera) {
  48841. return;
  48842. }
  48843. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48844. };
  48845. PointLight.prototype._buildUniformLayout = function () {
  48846. this._uniformBuffer.addUniform("vLightData", 4);
  48847. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48848. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48849. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48850. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48851. this._uniformBuffer.addUniform("depthValues", 2);
  48852. this._uniformBuffer.create();
  48853. };
  48854. /**
  48855. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48856. * @param effect The effect to update
  48857. * @param lightIndex The index of the light in the effect to update
  48858. * @returns The point light
  48859. */
  48860. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48861. if (this.computeTransformedInformation()) {
  48862. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48863. }
  48864. else {
  48865. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48866. }
  48867. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48868. return this;
  48869. };
  48870. /**
  48871. * Prepares the list of defines specific to the light type.
  48872. * @param defines the list of defines
  48873. * @param lightIndex defines the index of the light for the effect
  48874. */
  48875. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48876. defines["POINTLIGHT" + lightIndex] = true;
  48877. };
  48878. __decorate([
  48879. BABYLON.serialize()
  48880. ], PointLight.prototype, "shadowAngle", null);
  48881. return PointLight;
  48882. }(BABYLON.ShadowLight));
  48883. BABYLON.PointLight = PointLight;
  48884. })(BABYLON || (BABYLON = {}));
  48885. //# sourceMappingURL=babylon.pointLight.js.map
  48886. var BABYLON;
  48887. (function (BABYLON) {
  48888. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48889. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48890. });
  48891. /**
  48892. * A directional light is defined by a direction (what a surprise!).
  48893. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48894. * 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.
  48895. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48896. */
  48897. var DirectionalLight = /** @class */ (function (_super) {
  48898. __extends(DirectionalLight, _super);
  48899. /**
  48900. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48901. * The directional light is emitted from everywhere in the given direction.
  48902. * It can cast shawdows.
  48903. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48904. * @param name The friendly name of the light
  48905. * @param direction The direction of the light
  48906. * @param scene The scene the light belongs to
  48907. */
  48908. function DirectionalLight(name, direction, scene) {
  48909. var _this = _super.call(this, name, scene) || this;
  48910. _this._shadowFrustumSize = 0;
  48911. _this._shadowOrthoScale = 0.1;
  48912. /**
  48913. * Automatically compute the projection matrix to best fit (including all the casters)
  48914. * on each frame.
  48915. */
  48916. _this.autoUpdateExtends = true;
  48917. // Cache
  48918. _this._orthoLeft = Number.MAX_VALUE;
  48919. _this._orthoRight = Number.MIN_VALUE;
  48920. _this._orthoTop = Number.MIN_VALUE;
  48921. _this._orthoBottom = Number.MAX_VALUE;
  48922. _this.position = direction.scale(-1.0);
  48923. _this.direction = direction;
  48924. return _this;
  48925. }
  48926. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48927. /**
  48928. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48929. */
  48930. get: function () {
  48931. return this._shadowFrustumSize;
  48932. },
  48933. /**
  48934. * Specifies a fix frustum size for the shadow generation.
  48935. */
  48936. set: function (value) {
  48937. this._shadowFrustumSize = value;
  48938. this.forceProjectionMatrixCompute();
  48939. },
  48940. enumerable: true,
  48941. configurable: true
  48942. });
  48943. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48944. /**
  48945. * Gets the shadow projection scale against the optimal computed one.
  48946. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48947. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48948. */
  48949. get: function () {
  48950. return this._shadowOrthoScale;
  48951. },
  48952. /**
  48953. * Sets the shadow projection scale against the optimal computed one.
  48954. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48955. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48956. */
  48957. set: function (value) {
  48958. this._shadowOrthoScale = value;
  48959. this.forceProjectionMatrixCompute();
  48960. },
  48961. enumerable: true,
  48962. configurable: true
  48963. });
  48964. /**
  48965. * Returns the string "DirectionalLight".
  48966. * @return The class name
  48967. */
  48968. DirectionalLight.prototype.getClassName = function () {
  48969. return "DirectionalLight";
  48970. };
  48971. /**
  48972. * Returns the integer 1.
  48973. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48974. */
  48975. DirectionalLight.prototype.getTypeID = function () {
  48976. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48977. };
  48978. /**
  48979. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48980. * Returns the DirectionalLight Shadow projection matrix.
  48981. */
  48982. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48983. if (this.shadowFrustumSize > 0) {
  48984. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48985. }
  48986. else {
  48987. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48988. }
  48989. };
  48990. /**
  48991. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48992. * Returns the DirectionalLight Shadow projection matrix.
  48993. */
  48994. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48995. var activeCamera = this.getScene().activeCamera;
  48996. if (!activeCamera) {
  48997. return;
  48998. }
  48999. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49000. };
  49001. /**
  49002. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49003. * Returns the DirectionalLight Shadow projection matrix.
  49004. */
  49005. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49006. var activeCamera = this.getScene().activeCamera;
  49007. if (!activeCamera) {
  49008. return;
  49009. }
  49010. // Check extends
  49011. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49012. var tempVector3 = BABYLON.Vector3.Zero();
  49013. this._orthoLeft = Number.MAX_VALUE;
  49014. this._orthoRight = Number.MIN_VALUE;
  49015. this._orthoTop = Number.MIN_VALUE;
  49016. this._orthoBottom = Number.MAX_VALUE;
  49017. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49018. var mesh = renderList[meshIndex];
  49019. if (!mesh) {
  49020. continue;
  49021. }
  49022. var boundingInfo = mesh.getBoundingInfo();
  49023. var boundingBox = boundingInfo.boundingBox;
  49024. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49025. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49026. if (tempVector3.x < this._orthoLeft)
  49027. this._orthoLeft = tempVector3.x;
  49028. if (tempVector3.y < this._orthoBottom)
  49029. this._orthoBottom = tempVector3.y;
  49030. if (tempVector3.x > this._orthoRight)
  49031. this._orthoRight = tempVector3.x;
  49032. if (tempVector3.y > this._orthoTop)
  49033. this._orthoTop = tempVector3.y;
  49034. }
  49035. }
  49036. }
  49037. var xOffset = this._orthoRight - this._orthoLeft;
  49038. var yOffset = this._orthoTop - this._orthoBottom;
  49039. 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);
  49040. };
  49041. DirectionalLight.prototype._buildUniformLayout = function () {
  49042. this._uniformBuffer.addUniform("vLightData", 4);
  49043. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49044. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49045. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49046. this._uniformBuffer.addUniform("depthValues", 2);
  49047. this._uniformBuffer.create();
  49048. };
  49049. /**
  49050. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49051. * @param effect The effect to update
  49052. * @param lightIndex The index of the light in the effect to update
  49053. * @returns The directional light
  49054. */
  49055. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49056. if (this.computeTransformedInformation()) {
  49057. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49058. return this;
  49059. }
  49060. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49061. return this;
  49062. };
  49063. /**
  49064. * Gets the minZ used for shadow according to both the scene and the light.
  49065. *
  49066. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49067. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49068. * @param activeCamera The camera we are returning the min for
  49069. * @returns the depth min z
  49070. */
  49071. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49072. return 1;
  49073. };
  49074. /**
  49075. * Gets the maxZ used for shadow according to both the scene and the light.
  49076. *
  49077. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49078. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49079. * @param activeCamera The camera we are returning the max for
  49080. * @returns the depth max z
  49081. */
  49082. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49083. return 1;
  49084. };
  49085. /**
  49086. * Prepares the list of defines specific to the light type.
  49087. * @param defines the list of defines
  49088. * @param lightIndex defines the index of the light for the effect
  49089. */
  49090. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49091. defines["DIRLIGHT" + lightIndex] = true;
  49092. };
  49093. __decorate([
  49094. BABYLON.serialize()
  49095. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49096. __decorate([
  49097. BABYLON.serialize()
  49098. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49099. __decorate([
  49100. BABYLON.serialize()
  49101. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49102. return DirectionalLight;
  49103. }(BABYLON.ShadowLight));
  49104. BABYLON.DirectionalLight = DirectionalLight;
  49105. })(BABYLON || (BABYLON = {}));
  49106. //# sourceMappingURL=babylon.directionalLight.js.map
  49107. var BABYLON;
  49108. (function (BABYLON) {
  49109. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49110. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49111. });
  49112. /**
  49113. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49114. * These values define a cone of light starting from the position, emitting toward the direction.
  49115. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49116. * and the exponent defines the speed of the decay of the light with distance (reach).
  49117. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49118. */
  49119. var SpotLight = /** @class */ (function (_super) {
  49120. __extends(SpotLight, _super);
  49121. /**
  49122. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49123. * It can cast shadows.
  49124. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49125. * @param name The light friendly name
  49126. * @param position The position of the spot light in the scene
  49127. * @param direction The direction of the light in the scene
  49128. * @param angle The cone angle of the light in Radians
  49129. * @param exponent The light decay speed with the distance from the emission spot
  49130. * @param scene The scene the lights belongs to
  49131. */
  49132. function SpotLight(name, position, direction, angle, exponent, scene) {
  49133. var _this = _super.call(this, name, scene) || this;
  49134. _this._innerAngle = 0;
  49135. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49136. _this._projectionTextureLightNear = 1e-6;
  49137. _this._projectionTextureLightFar = 1000.0;
  49138. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49139. _this._projectionTextureViewLightDirty = true;
  49140. _this._projectionTextureProjectionLightDirty = true;
  49141. _this._projectionTextureDirty = true;
  49142. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49143. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49144. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49145. _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);
  49146. _this.position = position;
  49147. _this.direction = direction;
  49148. _this.angle = angle;
  49149. _this.exponent = exponent;
  49150. return _this;
  49151. }
  49152. Object.defineProperty(SpotLight.prototype, "angle", {
  49153. /**
  49154. * Gets the cone angle of the spot light in Radians.
  49155. */
  49156. get: function () {
  49157. return this._angle;
  49158. },
  49159. /**
  49160. * Sets the cone angle of the spot light in Radians.
  49161. */
  49162. set: function (value) {
  49163. this._angle = value;
  49164. this._cosHalfAngle = Math.cos(value * 0.5);
  49165. this._projectionTextureProjectionLightDirty = true;
  49166. this.forceProjectionMatrixCompute();
  49167. this._computeAngleValues();
  49168. },
  49169. enumerable: true,
  49170. configurable: true
  49171. });
  49172. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49173. /**
  49174. * Only used in gltf falloff mode, this defines the angle where
  49175. * the directional falloff will start before cutting at angle which could be seen
  49176. * as outer angle.
  49177. */
  49178. get: function () {
  49179. return this._angle;
  49180. },
  49181. /**
  49182. * Only used in gltf falloff mode, this defines the angle where
  49183. * the directional falloff will start before cutting at angle which could be seen
  49184. * as outer angle.
  49185. */
  49186. set: function (value) {
  49187. this._innerAngle = value;
  49188. this._computeAngleValues();
  49189. },
  49190. enumerable: true,
  49191. configurable: true
  49192. });
  49193. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49194. /**
  49195. * Allows scaling the angle of the light for shadow generation only.
  49196. */
  49197. get: function () {
  49198. return this._shadowAngleScale;
  49199. },
  49200. /**
  49201. * Allows scaling the angle of the light for shadow generation only.
  49202. */
  49203. set: function (value) {
  49204. this._shadowAngleScale = value;
  49205. this.forceProjectionMatrixCompute();
  49206. },
  49207. enumerable: true,
  49208. configurable: true
  49209. });
  49210. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49211. /**
  49212. * Allows reading the projecton texture
  49213. */
  49214. get: function () {
  49215. return this._projectionTextureMatrix;
  49216. },
  49217. enumerable: true,
  49218. configurable: true
  49219. });
  49220. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49221. /**
  49222. * Gets the near clip of the Spotlight for texture projection.
  49223. */
  49224. get: function () {
  49225. return this._projectionTextureLightNear;
  49226. },
  49227. /**
  49228. * Sets the near clip of the Spotlight for texture projection.
  49229. */
  49230. set: function (value) {
  49231. this._projectionTextureLightNear = value;
  49232. this._projectionTextureProjectionLightDirty = true;
  49233. },
  49234. enumerable: true,
  49235. configurable: true
  49236. });
  49237. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49238. /**
  49239. * Gets the far clip of the Spotlight for texture projection.
  49240. */
  49241. get: function () {
  49242. return this._projectionTextureLightFar;
  49243. },
  49244. /**
  49245. * Sets the far clip of the Spotlight for texture projection.
  49246. */
  49247. set: function (value) {
  49248. this._projectionTextureLightFar = value;
  49249. this._projectionTextureProjectionLightDirty = true;
  49250. },
  49251. enumerable: true,
  49252. configurable: true
  49253. });
  49254. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49255. /**
  49256. * Gets the Up vector of the Spotlight for texture projection.
  49257. */
  49258. get: function () {
  49259. return this._projectionTextureUpDirection;
  49260. },
  49261. /**
  49262. * Sets the Up vector of the Spotlight for texture projection.
  49263. */
  49264. set: function (value) {
  49265. this._projectionTextureUpDirection = value;
  49266. this._projectionTextureProjectionLightDirty = true;
  49267. },
  49268. enumerable: true,
  49269. configurable: true
  49270. });
  49271. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49272. /**
  49273. * Gets the projection texture of the light.
  49274. */
  49275. get: function () {
  49276. return this._projectionTexture;
  49277. },
  49278. /**
  49279. * Sets the projection texture of the light.
  49280. */
  49281. set: function (value) {
  49282. this._projectionTexture = value;
  49283. this._projectionTextureDirty = true;
  49284. },
  49285. enumerable: true,
  49286. configurable: true
  49287. });
  49288. /**
  49289. * Returns the string "SpotLight".
  49290. * @returns the class name
  49291. */
  49292. SpotLight.prototype.getClassName = function () {
  49293. return "SpotLight";
  49294. };
  49295. /**
  49296. * Returns the integer 2.
  49297. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49298. */
  49299. SpotLight.prototype.getTypeID = function () {
  49300. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49301. };
  49302. /**
  49303. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49304. */
  49305. SpotLight.prototype._setDirection = function (value) {
  49306. _super.prototype._setDirection.call(this, value);
  49307. this._projectionTextureViewLightDirty = true;
  49308. };
  49309. /**
  49310. * Overrides the position setter to recompute the projection texture view light Matrix.
  49311. */
  49312. SpotLight.prototype._setPosition = function (value) {
  49313. _super.prototype._setPosition.call(this, value);
  49314. this._projectionTextureViewLightDirty = true;
  49315. };
  49316. /**
  49317. * 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.
  49318. * Returns the SpotLight.
  49319. */
  49320. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49321. var activeCamera = this.getScene().activeCamera;
  49322. if (!activeCamera) {
  49323. return;
  49324. }
  49325. this._shadowAngleScale = this._shadowAngleScale || 1;
  49326. var angle = this._shadowAngleScale * this._angle;
  49327. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49328. };
  49329. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49330. this._projectionTextureViewLightDirty = false;
  49331. this._projectionTextureDirty = true;
  49332. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49333. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49334. };
  49335. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49336. this._projectionTextureProjectionLightDirty = false;
  49337. this._projectionTextureDirty = true;
  49338. var light_far = this.projectionTextureLightFar;
  49339. var light_near = this.projectionTextureLightNear;
  49340. var P = light_far / (light_far - light_near);
  49341. var Q = -P * light_near;
  49342. var S = 1.0 / Math.tan(this._angle / 2.0);
  49343. var A = 1.0;
  49344. 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);
  49345. };
  49346. /**
  49347. * Main function for light texture projection matrix computing.
  49348. */
  49349. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49350. this._projectionTextureDirty = false;
  49351. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49352. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49353. };
  49354. SpotLight.prototype._buildUniformLayout = function () {
  49355. this._uniformBuffer.addUniform("vLightData", 4);
  49356. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49357. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49358. this._uniformBuffer.addUniform("vLightDirection", 3);
  49359. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49360. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49361. this._uniformBuffer.addUniform("depthValues", 2);
  49362. this._uniformBuffer.create();
  49363. };
  49364. SpotLight.prototype._computeAngleValues = function () {
  49365. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49366. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49367. };
  49368. /**
  49369. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49370. * @param effect The effect to update
  49371. * @param lightIndex The index of the light in the effect to update
  49372. * @returns The spot light
  49373. */
  49374. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49375. var normalizeDirection;
  49376. if (this.computeTransformedInformation()) {
  49377. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49378. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49379. }
  49380. else {
  49381. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49382. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49383. }
  49384. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49385. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49386. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49387. if (this._projectionTextureViewLightDirty) {
  49388. this._computeProjectionTextureViewLightMatrix();
  49389. }
  49390. if (this._projectionTextureProjectionLightDirty) {
  49391. this._computeProjectionTextureProjectionLightMatrix();
  49392. }
  49393. if (this._projectionTextureDirty) {
  49394. this._computeProjectionTextureMatrix();
  49395. }
  49396. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49397. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49398. }
  49399. return this;
  49400. };
  49401. /**
  49402. * Disposes the light and the associated resources.
  49403. */
  49404. SpotLight.prototype.dispose = function () {
  49405. _super.prototype.dispose.call(this);
  49406. if (this._projectionTexture) {
  49407. this._projectionTexture.dispose();
  49408. }
  49409. };
  49410. /**
  49411. * Prepares the list of defines specific to the light type.
  49412. * @param defines the list of defines
  49413. * @param lightIndex defines the index of the light for the effect
  49414. */
  49415. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49416. defines["SPOTLIGHT" + lightIndex] = true;
  49417. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49418. };
  49419. __decorate([
  49420. BABYLON.serialize()
  49421. ], SpotLight.prototype, "angle", null);
  49422. __decorate([
  49423. BABYLON.serialize()
  49424. ], SpotLight.prototype, "innerAngle", null);
  49425. __decorate([
  49426. BABYLON.serialize()
  49427. ], SpotLight.prototype, "shadowAngleScale", null);
  49428. __decorate([
  49429. BABYLON.serialize()
  49430. ], SpotLight.prototype, "exponent", void 0);
  49431. __decorate([
  49432. BABYLON.serialize()
  49433. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49434. __decorate([
  49435. BABYLON.serialize()
  49436. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49437. __decorate([
  49438. BABYLON.serialize()
  49439. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49440. __decorate([
  49441. BABYLON.serializeAsTexture("projectedLightTexture")
  49442. ], SpotLight.prototype, "_projectionTexture", void 0);
  49443. return SpotLight;
  49444. }(BABYLON.ShadowLight));
  49445. BABYLON.SpotLight = SpotLight;
  49446. })(BABYLON || (BABYLON = {}));
  49447. //# sourceMappingURL=babylon.spotLight.js.map
  49448. var BABYLON;
  49449. (function (BABYLON) {
  49450. /**
  49451. * Class used to override all child animations of a given target
  49452. */
  49453. var AnimationPropertiesOverride = /** @class */ (function () {
  49454. function AnimationPropertiesOverride() {
  49455. /**
  49456. * Gets or sets a value indicating if animation blending must be used
  49457. */
  49458. this.enableBlending = false;
  49459. /**
  49460. * Gets or sets the blending speed to use when enableBlending is true
  49461. */
  49462. this.blendingSpeed = 0.01;
  49463. /**
  49464. * Gets or sets the default loop mode to use
  49465. */
  49466. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49467. }
  49468. return AnimationPropertiesOverride;
  49469. }());
  49470. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49471. })(BABYLON || (BABYLON = {}));
  49472. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49473. var BABYLON;
  49474. (function (BABYLON) {
  49475. /**
  49476. * Represents the range of an animation
  49477. */
  49478. var AnimationRange = /** @class */ (function () {
  49479. /**
  49480. * Initializes the range of an animation
  49481. * @param name The name of the animation range
  49482. * @param from The starting frame of the animation
  49483. * @param to The ending frame of the animation
  49484. */
  49485. function AnimationRange(
  49486. /**The name of the animation range**/
  49487. name,
  49488. /**The starting frame of the animation */
  49489. from,
  49490. /**The ending frame of the animation*/
  49491. to) {
  49492. this.name = name;
  49493. this.from = from;
  49494. this.to = to;
  49495. }
  49496. /**
  49497. * Makes a copy of the animation range
  49498. * @returns A copy of the animation range
  49499. */
  49500. AnimationRange.prototype.clone = function () {
  49501. return new AnimationRange(this.name, this.from, this.to);
  49502. };
  49503. return AnimationRange;
  49504. }());
  49505. BABYLON.AnimationRange = AnimationRange;
  49506. /**
  49507. * Composed of a frame, and an action function
  49508. */
  49509. var AnimationEvent = /** @class */ (function () {
  49510. /**
  49511. * Initializes the animation event
  49512. * @param frame The frame for which the event is triggered
  49513. * @param action The event to perform when triggered
  49514. * @param onlyOnce Specifies if the event should be triggered only once
  49515. */
  49516. function AnimationEvent(
  49517. /** The frame for which the event is triggered **/
  49518. frame,
  49519. /** The event to perform when triggered **/
  49520. action,
  49521. /** Specifies if the event should be triggered only once**/
  49522. onlyOnce) {
  49523. this.frame = frame;
  49524. this.action = action;
  49525. this.onlyOnce = onlyOnce;
  49526. /**
  49527. * Specifies if the animation event is done
  49528. */
  49529. this.isDone = false;
  49530. }
  49531. /** @hidden */
  49532. AnimationEvent.prototype._clone = function () {
  49533. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49534. };
  49535. return AnimationEvent;
  49536. }());
  49537. BABYLON.AnimationEvent = AnimationEvent;
  49538. /**
  49539. * A cursor which tracks a point on a path
  49540. */
  49541. var PathCursor = /** @class */ (function () {
  49542. /**
  49543. * Initializes the path cursor
  49544. * @param path The path to track
  49545. */
  49546. function PathCursor(path) {
  49547. this.path = path;
  49548. /**
  49549. * Stores path cursor callbacks for when an onchange event is triggered
  49550. */
  49551. this._onchange = new Array();
  49552. /**
  49553. * The value of the path cursor
  49554. */
  49555. this.value = 0;
  49556. /**
  49557. * The animation array of the path cursor
  49558. */
  49559. this.animations = new Array();
  49560. }
  49561. /**
  49562. * Gets the cursor point on the path
  49563. * @returns A point on the path cursor at the cursor location
  49564. */
  49565. PathCursor.prototype.getPoint = function () {
  49566. var point = this.path.getPointAtLengthPosition(this.value);
  49567. return new BABYLON.Vector3(point.x, 0, point.y);
  49568. };
  49569. /**
  49570. * Moves the cursor ahead by the step amount
  49571. * @param step The amount to move the cursor forward
  49572. * @returns This path cursor
  49573. */
  49574. PathCursor.prototype.moveAhead = function (step) {
  49575. if (step === void 0) { step = 0.002; }
  49576. this.move(step);
  49577. return this;
  49578. };
  49579. /**
  49580. * Moves the cursor behind by the step amount
  49581. * @param step The amount to move the cursor back
  49582. * @returns This path cursor
  49583. */
  49584. PathCursor.prototype.moveBack = function (step) {
  49585. if (step === void 0) { step = 0.002; }
  49586. this.move(-step);
  49587. return this;
  49588. };
  49589. /**
  49590. * Moves the cursor by the step amount
  49591. * If the step amount is greater than one, an exception is thrown
  49592. * @param step The amount to move the cursor
  49593. * @returns This path cursor
  49594. */
  49595. PathCursor.prototype.move = function (step) {
  49596. if (Math.abs(step) > 1) {
  49597. throw "step size should be less than 1.";
  49598. }
  49599. this.value += step;
  49600. this.ensureLimits();
  49601. this.raiseOnChange();
  49602. return this;
  49603. };
  49604. /**
  49605. * Ensures that the value is limited between zero and one
  49606. * @returns This path cursor
  49607. */
  49608. PathCursor.prototype.ensureLimits = function () {
  49609. while (this.value > 1) {
  49610. this.value -= 1;
  49611. }
  49612. while (this.value < 0) {
  49613. this.value += 1;
  49614. }
  49615. return this;
  49616. };
  49617. /**
  49618. * Runs onchange callbacks on change (used by the animation engine)
  49619. * @returns This path cursor
  49620. */
  49621. PathCursor.prototype.raiseOnChange = function () {
  49622. var _this = this;
  49623. this._onchange.forEach(function (f) { return f(_this); });
  49624. return this;
  49625. };
  49626. /**
  49627. * Executes a function on change
  49628. * @param f A path cursor onchange callback
  49629. * @returns This path cursor
  49630. */
  49631. PathCursor.prototype.onchange = function (f) {
  49632. this._onchange.push(f);
  49633. return this;
  49634. };
  49635. return PathCursor;
  49636. }());
  49637. BABYLON.PathCursor = PathCursor;
  49638. /**
  49639. * Enum for the animation key frame interpolation type
  49640. */
  49641. var AnimationKeyInterpolation;
  49642. (function (AnimationKeyInterpolation) {
  49643. /**
  49644. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49645. */
  49646. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49647. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49648. /**
  49649. * Class used to store any kind of animation
  49650. */
  49651. var Animation = /** @class */ (function () {
  49652. /**
  49653. * Initializes the animation
  49654. * @param name Name of the animation
  49655. * @param targetProperty Property to animate
  49656. * @param framePerSecond The frames per second of the animation
  49657. * @param dataType The data type of the animation
  49658. * @param loopMode The loop mode of the animation
  49659. * @param enableBlendings Specifies if blending should be enabled
  49660. */
  49661. function Animation(
  49662. /**Name of the animation */
  49663. name,
  49664. /**Property to animate */
  49665. targetProperty,
  49666. /**The frames per second of the animation */
  49667. framePerSecond,
  49668. /**The data type of the animation */
  49669. dataType,
  49670. /**The loop mode of the animation */
  49671. loopMode,
  49672. /**Specifies if blending should be enabled */
  49673. enableBlending) {
  49674. this.name = name;
  49675. this.targetProperty = targetProperty;
  49676. this.framePerSecond = framePerSecond;
  49677. this.dataType = dataType;
  49678. this.loopMode = loopMode;
  49679. this.enableBlending = enableBlending;
  49680. /**
  49681. * @hidden Internal use only
  49682. */
  49683. this._runtimeAnimations = new Array();
  49684. /**
  49685. * The set of event that will be linked to this animation
  49686. */
  49687. this._events = new Array();
  49688. /**
  49689. * Stores the blending speed of the animation
  49690. */
  49691. this.blendingSpeed = 0.01;
  49692. /**
  49693. * Stores the animation ranges for the animation
  49694. */
  49695. this._ranges = {};
  49696. this.targetPropertyPath = targetProperty.split(".");
  49697. this.dataType = dataType;
  49698. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49699. }
  49700. /**
  49701. * @hidden Internal use
  49702. */
  49703. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49704. var dataType = undefined;
  49705. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49706. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49707. }
  49708. else if (from instanceof BABYLON.Quaternion) {
  49709. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49710. }
  49711. else if (from instanceof BABYLON.Vector3) {
  49712. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49713. }
  49714. else if (from instanceof BABYLON.Vector2) {
  49715. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49716. }
  49717. else if (from instanceof BABYLON.Color3) {
  49718. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49719. }
  49720. else if (from instanceof BABYLON.Size) {
  49721. dataType = Animation.ANIMATIONTYPE_SIZE;
  49722. }
  49723. if (dataType == undefined) {
  49724. return null;
  49725. }
  49726. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49727. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49728. animation.setKeys(keys);
  49729. if (easingFunction !== undefined) {
  49730. animation.setEasingFunction(easingFunction);
  49731. }
  49732. return animation;
  49733. };
  49734. /**
  49735. * Sets up an animation
  49736. * @param property The property to animate
  49737. * @param animationType The animation type to apply
  49738. * @param framePerSecond The frames per second of the animation
  49739. * @param easingFunction The easing function used in the animation
  49740. * @returns The created animation
  49741. */
  49742. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49743. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49744. animation.setEasingFunction(easingFunction);
  49745. return animation;
  49746. };
  49747. /**
  49748. * Create and start an animation on a node
  49749. * @param name defines the name of the global animation that will be run on all nodes
  49750. * @param node defines the root node where the animation will take place
  49751. * @param targetProperty defines property to animate
  49752. * @param framePerSecond defines the number of frame per second yo use
  49753. * @param totalFrame defines the number of frames in total
  49754. * @param from defines the initial value
  49755. * @param to defines the final value
  49756. * @param loopMode defines which loop mode you want to use (off by default)
  49757. * @param easingFunction defines the easing function to use (linear by default)
  49758. * @param onAnimationEnd defines the callback to call when animation end
  49759. * @returns the animatable created for this animation
  49760. */
  49761. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49762. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49763. if (!animation) {
  49764. return null;
  49765. }
  49766. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49767. };
  49768. /**
  49769. * Create and start an animation on a node and its descendants
  49770. * @param name defines the name of the global animation that will be run on all nodes
  49771. * @param node defines the root node where the animation will take place
  49772. * @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
  49773. * @param targetProperty defines property to animate
  49774. * @param framePerSecond defines the number of frame per second to use
  49775. * @param totalFrame defines the number of frames in total
  49776. * @param from defines the initial value
  49777. * @param to defines the final value
  49778. * @param loopMode defines which loop mode you want to use (off by default)
  49779. * @param easingFunction defines the easing function to use (linear by default)
  49780. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49781. * @returns the list of animatables created for all nodes
  49782. * @example https://www.babylonjs-playground.com/#MH0VLI
  49783. */
  49784. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49785. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49786. if (!animation) {
  49787. return null;
  49788. }
  49789. var scene = node.getScene();
  49790. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49791. };
  49792. /**
  49793. * Creates a new animation, merges it with the existing animations and starts it
  49794. * @param name Name of the animation
  49795. * @param node Node which contains the scene that begins the animations
  49796. * @param targetProperty Specifies which property to animate
  49797. * @param framePerSecond The frames per second of the animation
  49798. * @param totalFrame The total number of frames
  49799. * @param from The frame at the beginning of the animation
  49800. * @param to The frame at the end of the animation
  49801. * @param loopMode Specifies the loop mode of the animation
  49802. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49803. * @param onAnimationEnd Callback to run once the animation is complete
  49804. * @returns Nullable animation
  49805. */
  49806. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49807. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49808. if (!animation) {
  49809. return null;
  49810. }
  49811. node.animations.push(animation);
  49812. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49813. };
  49814. /**
  49815. * Transition property of an host to the target Value
  49816. * @param property The property to transition
  49817. * @param targetValue The target Value of the property
  49818. * @param host The object where the property to animate belongs
  49819. * @param scene Scene used to run the animation
  49820. * @param frameRate Framerate (in frame/s) to use
  49821. * @param transition The transition type we want to use
  49822. * @param duration The duration of the animation, in milliseconds
  49823. * @param onAnimationEnd Callback trigger at the end of the animation
  49824. * @returns Nullable animation
  49825. */
  49826. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49827. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49828. if (duration <= 0) {
  49829. host[property] = targetValue;
  49830. if (onAnimationEnd) {
  49831. onAnimationEnd();
  49832. }
  49833. return null;
  49834. }
  49835. var endFrame = frameRate * (duration / 1000);
  49836. transition.setKeys([{
  49837. frame: 0,
  49838. value: host[property].clone ? host[property].clone() : host[property]
  49839. },
  49840. {
  49841. frame: endFrame,
  49842. value: targetValue
  49843. }]);
  49844. if (!host.animations) {
  49845. host.animations = [];
  49846. }
  49847. host.animations.push(transition);
  49848. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49849. animation.onAnimationEnd = onAnimationEnd;
  49850. return animation;
  49851. };
  49852. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49853. /**
  49854. * Return the array of runtime animations currently using this animation
  49855. */
  49856. get: function () {
  49857. return this._runtimeAnimations;
  49858. },
  49859. enumerable: true,
  49860. configurable: true
  49861. });
  49862. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49863. /**
  49864. * Specifies if any of the runtime animations are currently running
  49865. */
  49866. get: function () {
  49867. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49868. var runtimeAnimation = _a[_i];
  49869. if (!runtimeAnimation.isStopped) {
  49870. return true;
  49871. }
  49872. }
  49873. return false;
  49874. },
  49875. enumerable: true,
  49876. configurable: true
  49877. });
  49878. // Methods
  49879. /**
  49880. * Converts the animation to a string
  49881. * @param fullDetails support for multiple levels of logging within scene loading
  49882. * @returns String form of the animation
  49883. */
  49884. Animation.prototype.toString = function (fullDetails) {
  49885. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49886. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49887. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49888. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49889. if (fullDetails) {
  49890. ret += ", Ranges: {";
  49891. var first = true;
  49892. for (var name in this._ranges) {
  49893. if (first) {
  49894. ret += ", ";
  49895. first = false;
  49896. }
  49897. ret += name;
  49898. }
  49899. ret += "}";
  49900. }
  49901. return ret;
  49902. };
  49903. /**
  49904. * Add an event to this animation
  49905. * @param event Event to add
  49906. */
  49907. Animation.prototype.addEvent = function (event) {
  49908. this._events.push(event);
  49909. };
  49910. /**
  49911. * Remove all events found at the given frame
  49912. * @param frame The frame to remove events from
  49913. */
  49914. Animation.prototype.removeEvents = function (frame) {
  49915. for (var index = 0; index < this._events.length; index++) {
  49916. if (this._events[index].frame === frame) {
  49917. this._events.splice(index, 1);
  49918. index--;
  49919. }
  49920. }
  49921. };
  49922. /**
  49923. * Retrieves all the events from the animation
  49924. * @returns Events from the animation
  49925. */
  49926. Animation.prototype.getEvents = function () {
  49927. return this._events;
  49928. };
  49929. /**
  49930. * Creates an animation range
  49931. * @param name Name of the animation range
  49932. * @param from Starting frame of the animation range
  49933. * @param to Ending frame of the animation
  49934. */
  49935. Animation.prototype.createRange = function (name, from, to) {
  49936. // check name not already in use; could happen for bones after serialized
  49937. if (!this._ranges[name]) {
  49938. this._ranges[name] = new AnimationRange(name, from, to);
  49939. }
  49940. };
  49941. /**
  49942. * Deletes an animation range by name
  49943. * @param name Name of the animation range to delete
  49944. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49945. */
  49946. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49947. if (deleteFrames === void 0) { deleteFrames = true; }
  49948. var range = this._ranges[name];
  49949. if (!range) {
  49950. return;
  49951. }
  49952. if (deleteFrames) {
  49953. var from = range.from;
  49954. var to = range.to;
  49955. // this loop MUST go high to low for multiple splices to work
  49956. for (var key = this._keys.length - 1; key >= 0; key--) {
  49957. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49958. this._keys.splice(key, 1);
  49959. }
  49960. }
  49961. }
  49962. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49963. };
  49964. /**
  49965. * Gets the animation range by name, or null if not defined
  49966. * @param name Name of the animation range
  49967. * @returns Nullable animation range
  49968. */
  49969. Animation.prototype.getRange = function (name) {
  49970. return this._ranges[name];
  49971. };
  49972. /**
  49973. * Gets the key frames from the animation
  49974. * @returns The key frames of the animation
  49975. */
  49976. Animation.prototype.getKeys = function () {
  49977. return this._keys;
  49978. };
  49979. /**
  49980. * Gets the highest frame rate of the animation
  49981. * @returns Highest frame rate of the animation
  49982. */
  49983. Animation.prototype.getHighestFrame = function () {
  49984. var ret = 0;
  49985. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49986. if (ret < this._keys[key].frame) {
  49987. ret = this._keys[key].frame;
  49988. }
  49989. }
  49990. return ret;
  49991. };
  49992. /**
  49993. * Gets the easing function of the animation
  49994. * @returns Easing function of the animation
  49995. */
  49996. Animation.prototype.getEasingFunction = function () {
  49997. return this._easingFunction;
  49998. };
  49999. /**
  50000. * Sets the easing function of the animation
  50001. * @param easingFunction A custom mathematical formula for animation
  50002. */
  50003. Animation.prototype.setEasingFunction = function (easingFunction) {
  50004. this._easingFunction = easingFunction;
  50005. };
  50006. /**
  50007. * Interpolates a scalar linearly
  50008. * @param startValue Start value of the animation curve
  50009. * @param endValue End value of the animation curve
  50010. * @param gradient Scalar amount to interpolate
  50011. * @returns Interpolated scalar value
  50012. */
  50013. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50014. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50015. };
  50016. /**
  50017. * Interpolates a scalar cubically
  50018. * @param startValue Start value of the animation curve
  50019. * @param outTangent End tangent of the animation
  50020. * @param endValue End value of the animation curve
  50021. * @param inTangent Start tangent of the animation curve
  50022. * @param gradient Scalar amount to interpolate
  50023. * @returns Interpolated scalar value
  50024. */
  50025. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50026. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50027. };
  50028. /**
  50029. * Interpolates a quaternion using a spherical linear interpolation
  50030. * @param startValue Start value of the animation curve
  50031. * @param endValue End value of the animation curve
  50032. * @param gradient Scalar amount to interpolate
  50033. * @returns Interpolated quaternion value
  50034. */
  50035. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50036. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50037. };
  50038. /**
  50039. * Interpolates a quaternion cubically
  50040. * @param startValue Start value of the animation curve
  50041. * @param outTangent End tangent of the animation curve
  50042. * @param endValue End value of the animation curve
  50043. * @param inTangent Start tangent of the animation curve
  50044. * @param gradient Scalar amount to interpolate
  50045. * @returns Interpolated quaternion value
  50046. */
  50047. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50048. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50049. };
  50050. /**
  50051. * Interpolates a Vector3 linearl
  50052. * @param startValue Start value of the animation curve
  50053. * @param endValue End value of the animation curve
  50054. * @param gradient Scalar amount to interpolate
  50055. * @returns Interpolated scalar value
  50056. */
  50057. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50058. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50059. };
  50060. /**
  50061. * Interpolates a Vector3 cubically
  50062. * @param startValue Start value of the animation curve
  50063. * @param outTangent End tangent of the animation
  50064. * @param endValue End value of the animation curve
  50065. * @param inTangent Start tangent of the animation curve
  50066. * @param gradient Scalar amount to interpolate
  50067. * @returns InterpolatedVector3 value
  50068. */
  50069. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50070. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50071. };
  50072. /**
  50073. * Interpolates a Vector2 linearly
  50074. * @param startValue Start value of the animation curve
  50075. * @param endValue End value of the animation curve
  50076. * @param gradient Scalar amount to interpolate
  50077. * @returns Interpolated Vector2 value
  50078. */
  50079. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50080. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50081. };
  50082. /**
  50083. * Interpolates a Vector2 cubically
  50084. * @param startValue Start value of the animation curve
  50085. * @param outTangent End tangent of the animation
  50086. * @param endValue End value of the animation curve
  50087. * @param inTangent Start tangent of the animation curve
  50088. * @param gradient Scalar amount to interpolate
  50089. * @returns Interpolated Vector2 value
  50090. */
  50091. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50092. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50093. };
  50094. /**
  50095. * Interpolates a size linearly
  50096. * @param startValue Start value of the animation curve
  50097. * @param endValue End value of the animation curve
  50098. * @param gradient Scalar amount to interpolate
  50099. * @returns Interpolated Size value
  50100. */
  50101. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50102. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50103. };
  50104. /**
  50105. * Interpolates a Color3 linearly
  50106. * @param startValue Start value of the animation curve
  50107. * @param endValue End value of the animation curve
  50108. * @param gradient Scalar amount to interpolate
  50109. * @returns Interpolated Color3 value
  50110. */
  50111. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50112. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50113. };
  50114. /**
  50115. * @hidden Internal use only
  50116. */
  50117. Animation.prototype._getKeyValue = function (value) {
  50118. if (typeof value === "function") {
  50119. return value();
  50120. }
  50121. return value;
  50122. };
  50123. /**
  50124. * @hidden Internal use only
  50125. */
  50126. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50127. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50128. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50129. }
  50130. var keys = this.getKeys();
  50131. // Try to get a hash to find the right key
  50132. 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));
  50133. if (keys[startKeyIndex].frame >= currentFrame) {
  50134. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50135. startKeyIndex--;
  50136. }
  50137. }
  50138. for (var key = startKeyIndex; key < keys.length; key++) {
  50139. var endKey = keys[key + 1];
  50140. if (endKey.frame >= currentFrame) {
  50141. var startKey = keys[key];
  50142. var startValue = this._getKeyValue(startKey.value);
  50143. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50144. return startValue;
  50145. }
  50146. var endValue = this._getKeyValue(endKey.value);
  50147. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50148. var frameDelta = endKey.frame - startKey.frame;
  50149. // gradient : percent of currentFrame between the frame inf and the frame sup
  50150. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50151. // check for easingFunction and correction of gradient
  50152. var easingFunction = this.getEasingFunction();
  50153. if (easingFunction != null) {
  50154. gradient = easingFunction.ease(gradient);
  50155. }
  50156. switch (this.dataType) {
  50157. // Float
  50158. case Animation.ANIMATIONTYPE_FLOAT:
  50159. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50160. switch (loopMode) {
  50161. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50162. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50163. return floatValue;
  50164. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50165. return offsetValue * repeatCount + floatValue;
  50166. }
  50167. break;
  50168. // Quaternion
  50169. case Animation.ANIMATIONTYPE_QUATERNION:
  50170. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50171. switch (loopMode) {
  50172. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50173. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50174. return quatValue;
  50175. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50176. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50177. }
  50178. return quatValue;
  50179. // Vector3
  50180. case Animation.ANIMATIONTYPE_VECTOR3:
  50181. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50182. switch (loopMode) {
  50183. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50184. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50185. return vec3Value;
  50186. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50187. return vec3Value.add(offsetValue.scale(repeatCount));
  50188. }
  50189. // Vector2
  50190. case Animation.ANIMATIONTYPE_VECTOR2:
  50191. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50192. switch (loopMode) {
  50193. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50194. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50195. return vec2Value;
  50196. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50197. return vec2Value.add(offsetValue.scale(repeatCount));
  50198. }
  50199. // Size
  50200. case Animation.ANIMATIONTYPE_SIZE:
  50201. switch (loopMode) {
  50202. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50203. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50204. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50205. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50206. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50207. }
  50208. // Color3
  50209. case Animation.ANIMATIONTYPE_COLOR3:
  50210. switch (loopMode) {
  50211. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50212. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50213. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50214. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50215. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50216. }
  50217. // Matrix
  50218. case Animation.ANIMATIONTYPE_MATRIX:
  50219. switch (loopMode) {
  50220. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50221. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50222. if (Animation.AllowMatricesInterpolation) {
  50223. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50224. }
  50225. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50226. return startValue;
  50227. }
  50228. default:
  50229. break;
  50230. }
  50231. break;
  50232. }
  50233. }
  50234. return this._getKeyValue(keys[keys.length - 1].value);
  50235. };
  50236. /**
  50237. * Defines the function to use to interpolate matrices
  50238. * @param startValue defines the start matrix
  50239. * @param endValue defines the end matrix
  50240. * @param gradient defines the gradient between both matrices
  50241. * @param result defines an optional target matrix where to store the interpolation
  50242. * @returns the interpolated matrix
  50243. */
  50244. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50245. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50246. if (result) {
  50247. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50248. return result;
  50249. }
  50250. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50251. }
  50252. if (result) {
  50253. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50254. return result;
  50255. }
  50256. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50257. };
  50258. /**
  50259. * Makes a copy of the animation
  50260. * @returns Cloned animation
  50261. */
  50262. Animation.prototype.clone = function () {
  50263. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50264. clone.enableBlending = this.enableBlending;
  50265. clone.blendingSpeed = this.blendingSpeed;
  50266. if (this._keys) {
  50267. clone.setKeys(this._keys);
  50268. }
  50269. if (this._ranges) {
  50270. clone._ranges = {};
  50271. for (var name in this._ranges) {
  50272. var range = this._ranges[name];
  50273. if (!range) {
  50274. continue;
  50275. }
  50276. clone._ranges[name] = range.clone();
  50277. }
  50278. }
  50279. return clone;
  50280. };
  50281. /**
  50282. * Sets the key frames of the animation
  50283. * @param values The animation key frames to set
  50284. */
  50285. Animation.prototype.setKeys = function (values) {
  50286. this._keys = values.slice(0);
  50287. };
  50288. /**
  50289. * Serializes the animation to an object
  50290. * @returns Serialized object
  50291. */
  50292. Animation.prototype.serialize = function () {
  50293. var serializationObject = {};
  50294. serializationObject.name = this.name;
  50295. serializationObject.property = this.targetProperty;
  50296. serializationObject.framePerSecond = this.framePerSecond;
  50297. serializationObject.dataType = this.dataType;
  50298. serializationObject.loopBehavior = this.loopMode;
  50299. serializationObject.enableBlending = this.enableBlending;
  50300. serializationObject.blendingSpeed = this.blendingSpeed;
  50301. var dataType = this.dataType;
  50302. serializationObject.keys = [];
  50303. var keys = this.getKeys();
  50304. for (var index = 0; index < keys.length; index++) {
  50305. var animationKey = keys[index];
  50306. var key = {};
  50307. key.frame = animationKey.frame;
  50308. switch (dataType) {
  50309. case Animation.ANIMATIONTYPE_FLOAT:
  50310. key.values = [animationKey.value];
  50311. break;
  50312. case Animation.ANIMATIONTYPE_QUATERNION:
  50313. case Animation.ANIMATIONTYPE_MATRIX:
  50314. case Animation.ANIMATIONTYPE_VECTOR3:
  50315. case Animation.ANIMATIONTYPE_COLOR3:
  50316. key.values = animationKey.value.asArray();
  50317. break;
  50318. }
  50319. serializationObject.keys.push(key);
  50320. }
  50321. serializationObject.ranges = [];
  50322. for (var name in this._ranges) {
  50323. var source = this._ranges[name];
  50324. if (!source) {
  50325. continue;
  50326. }
  50327. var range = {};
  50328. range.name = name;
  50329. range.from = source.from;
  50330. range.to = source.to;
  50331. serializationObject.ranges.push(range);
  50332. }
  50333. return serializationObject;
  50334. };
  50335. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50336. /**
  50337. * Get the float animation type
  50338. */
  50339. get: function () {
  50340. return Animation._ANIMATIONTYPE_FLOAT;
  50341. },
  50342. enumerable: true,
  50343. configurable: true
  50344. });
  50345. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50346. /**
  50347. * Get the Vector3 animation type
  50348. */
  50349. get: function () {
  50350. return Animation._ANIMATIONTYPE_VECTOR3;
  50351. },
  50352. enumerable: true,
  50353. configurable: true
  50354. });
  50355. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50356. /**
  50357. * Get the Vector2 animation type
  50358. */
  50359. get: function () {
  50360. return Animation._ANIMATIONTYPE_VECTOR2;
  50361. },
  50362. enumerable: true,
  50363. configurable: true
  50364. });
  50365. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50366. /**
  50367. * Get the Size animation type
  50368. */
  50369. get: function () {
  50370. return Animation._ANIMATIONTYPE_SIZE;
  50371. },
  50372. enumerable: true,
  50373. configurable: true
  50374. });
  50375. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50376. /**
  50377. * Get the Quaternion animation type
  50378. */
  50379. get: function () {
  50380. return Animation._ANIMATIONTYPE_QUATERNION;
  50381. },
  50382. enumerable: true,
  50383. configurable: true
  50384. });
  50385. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50386. /**
  50387. * Get the Matrix animation type
  50388. */
  50389. get: function () {
  50390. return Animation._ANIMATIONTYPE_MATRIX;
  50391. },
  50392. enumerable: true,
  50393. configurable: true
  50394. });
  50395. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50396. /**
  50397. * Get the Color3 animation type
  50398. */
  50399. get: function () {
  50400. return Animation._ANIMATIONTYPE_COLOR3;
  50401. },
  50402. enumerable: true,
  50403. configurable: true
  50404. });
  50405. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50406. /**
  50407. * Get the Relative Loop Mode
  50408. */
  50409. get: function () {
  50410. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50411. },
  50412. enumerable: true,
  50413. configurable: true
  50414. });
  50415. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50416. /**
  50417. * Get the Cycle Loop Mode
  50418. */
  50419. get: function () {
  50420. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50421. },
  50422. enumerable: true,
  50423. configurable: true
  50424. });
  50425. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50426. /**
  50427. * Get the Constant Loop Mode
  50428. */
  50429. get: function () {
  50430. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50431. },
  50432. enumerable: true,
  50433. configurable: true
  50434. });
  50435. /** @hidden */
  50436. Animation._UniversalLerp = function (left, right, amount) {
  50437. var constructor = left.constructor;
  50438. if (constructor.Lerp) { // Lerp supported
  50439. return constructor.Lerp(left, right, amount);
  50440. }
  50441. else if (constructor.Slerp) { // Slerp supported
  50442. return constructor.Slerp(left, right, amount);
  50443. }
  50444. else if (left.toFixed) { // Number
  50445. return left * (1.0 - amount) + amount * right;
  50446. }
  50447. else { // Blending not supported
  50448. return right;
  50449. }
  50450. };
  50451. /**
  50452. * Parses an animation object and creates an animation
  50453. * @param parsedAnimation Parsed animation object
  50454. * @returns Animation object
  50455. */
  50456. Animation.Parse = function (parsedAnimation) {
  50457. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50458. var dataType = parsedAnimation.dataType;
  50459. var keys = [];
  50460. var data;
  50461. var index;
  50462. if (parsedAnimation.enableBlending) {
  50463. animation.enableBlending = parsedAnimation.enableBlending;
  50464. }
  50465. if (parsedAnimation.blendingSpeed) {
  50466. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50467. }
  50468. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50469. var key = parsedAnimation.keys[index];
  50470. var inTangent;
  50471. var outTangent;
  50472. switch (dataType) {
  50473. case Animation.ANIMATIONTYPE_FLOAT:
  50474. data = key.values[0];
  50475. if (key.values.length >= 1) {
  50476. inTangent = key.values[1];
  50477. }
  50478. if (key.values.length >= 2) {
  50479. outTangent = key.values[2];
  50480. }
  50481. break;
  50482. case Animation.ANIMATIONTYPE_QUATERNION:
  50483. data = BABYLON.Quaternion.FromArray(key.values);
  50484. if (key.values.length >= 8) {
  50485. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50486. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50487. inTangent = _inTangent;
  50488. }
  50489. }
  50490. if (key.values.length >= 12) {
  50491. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50492. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50493. outTangent = _outTangent;
  50494. }
  50495. }
  50496. break;
  50497. case Animation.ANIMATIONTYPE_MATRIX:
  50498. data = BABYLON.Matrix.FromArray(key.values);
  50499. break;
  50500. case Animation.ANIMATIONTYPE_COLOR3:
  50501. data = BABYLON.Color3.FromArray(key.values);
  50502. break;
  50503. case Animation.ANIMATIONTYPE_VECTOR3:
  50504. default:
  50505. data = BABYLON.Vector3.FromArray(key.values);
  50506. break;
  50507. }
  50508. var keyData = {};
  50509. keyData.frame = key.frame;
  50510. keyData.value = data;
  50511. if (inTangent != undefined) {
  50512. keyData.inTangent = inTangent;
  50513. }
  50514. if (outTangent != undefined) {
  50515. keyData.outTangent = outTangent;
  50516. }
  50517. keys.push(keyData);
  50518. }
  50519. animation.setKeys(keys);
  50520. if (parsedAnimation.ranges) {
  50521. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50522. data = parsedAnimation.ranges[index];
  50523. animation.createRange(data.name, data.from, data.to);
  50524. }
  50525. }
  50526. return animation;
  50527. };
  50528. /**
  50529. * Appends the serialized animations from the source animations
  50530. * @param source Source containing the animations
  50531. * @param destination Target to store the animations
  50532. */
  50533. Animation.AppendSerializedAnimations = function (source, destination) {
  50534. if (source.animations) {
  50535. destination.animations = [];
  50536. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50537. var animation = source.animations[animationIndex];
  50538. destination.animations.push(animation.serialize());
  50539. }
  50540. }
  50541. };
  50542. /**
  50543. * Use matrix interpolation instead of using direct key value when animating matrices
  50544. */
  50545. Animation.AllowMatricesInterpolation = false;
  50546. /**
  50547. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50548. */
  50549. Animation.AllowMatrixDecomposeForInterpolation = true;
  50550. // Statics
  50551. /**
  50552. * Float animation type
  50553. */
  50554. Animation._ANIMATIONTYPE_FLOAT = 0;
  50555. /**
  50556. * Vector3 animation type
  50557. */
  50558. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50559. /**
  50560. * Quaternion animation type
  50561. */
  50562. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50563. /**
  50564. * Matrix animation type
  50565. */
  50566. Animation._ANIMATIONTYPE_MATRIX = 3;
  50567. /**
  50568. * Color3 animation type
  50569. */
  50570. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50571. /**
  50572. * Vector2 animation type
  50573. */
  50574. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50575. /**
  50576. * Size animation type
  50577. */
  50578. Animation._ANIMATIONTYPE_SIZE = 6;
  50579. /**
  50580. * Relative Loop Mode
  50581. */
  50582. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50583. /**
  50584. * Cycle Loop Mode
  50585. */
  50586. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50587. /**
  50588. * Constant Loop Mode
  50589. */
  50590. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50591. return Animation;
  50592. }());
  50593. BABYLON.Animation = Animation;
  50594. })(BABYLON || (BABYLON = {}));
  50595. //# sourceMappingURL=babylon.animation.js.map
  50596. var BABYLON;
  50597. (function (BABYLON) {
  50598. /**
  50599. * This class defines the direct association between an animation and a target
  50600. */
  50601. var TargetedAnimation = /** @class */ (function () {
  50602. function TargetedAnimation() {
  50603. }
  50604. return TargetedAnimation;
  50605. }());
  50606. BABYLON.TargetedAnimation = TargetedAnimation;
  50607. /**
  50608. * Use this class to create coordinated animations on multiple targets
  50609. */
  50610. var AnimationGroup = /** @class */ (function () {
  50611. function AnimationGroup(name, scene) {
  50612. if (scene === void 0) { scene = null; }
  50613. this.name = name;
  50614. this._targetedAnimations = new Array();
  50615. this._animatables = new Array();
  50616. this._from = Number.MAX_VALUE;
  50617. this._to = -Number.MAX_VALUE;
  50618. this._speedRatio = 1;
  50619. this.onAnimationEndObservable = new BABYLON.Observable();
  50620. /**
  50621. * This observable will notify when all animations have ended.
  50622. */
  50623. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50624. /**
  50625. * This observable will notify when all animations have paused.
  50626. */
  50627. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50628. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50629. this._scene.animationGroups.push(this);
  50630. }
  50631. Object.defineProperty(AnimationGroup.prototype, "from", {
  50632. /**
  50633. * Gets the first frame
  50634. */
  50635. get: function () {
  50636. return this._from;
  50637. },
  50638. enumerable: true,
  50639. configurable: true
  50640. });
  50641. Object.defineProperty(AnimationGroup.prototype, "to", {
  50642. /**
  50643. * Gets the last frame
  50644. */
  50645. get: function () {
  50646. return this._to;
  50647. },
  50648. enumerable: true,
  50649. configurable: true
  50650. });
  50651. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50652. /**
  50653. * Define if the animations are started
  50654. */
  50655. get: function () {
  50656. return this._isStarted;
  50657. },
  50658. enumerable: true,
  50659. configurable: true
  50660. });
  50661. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50662. /**
  50663. * Gets or sets the speed ratio to use for all animations
  50664. */
  50665. get: function () {
  50666. return this._speedRatio;
  50667. },
  50668. /**
  50669. * Gets or sets the speed ratio to use for all animations
  50670. */
  50671. set: function (value) {
  50672. if (this._speedRatio === value) {
  50673. return;
  50674. }
  50675. this._speedRatio = value;
  50676. for (var index = 0; index < this._animatables.length; index++) {
  50677. var animatable = this._animatables[index];
  50678. animatable.speedRatio = this._speedRatio;
  50679. }
  50680. },
  50681. enumerable: true,
  50682. configurable: true
  50683. });
  50684. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50685. /**
  50686. * Gets the targeted animations for this animation group
  50687. */
  50688. get: function () {
  50689. return this._targetedAnimations;
  50690. },
  50691. enumerable: true,
  50692. configurable: true
  50693. });
  50694. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50695. /**
  50696. * returning the list of animatables controlled by this animation group.
  50697. */
  50698. get: function () {
  50699. return this._animatables;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. /**
  50705. * Add an animation (with its target) in the group
  50706. * @param animation defines the animation we want to add
  50707. * @param target defines the target of the animation
  50708. * @returns the {BABYLON.TargetedAnimation} object
  50709. */
  50710. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50711. var targetedAnimation = {
  50712. animation: animation,
  50713. target: target
  50714. };
  50715. var keys = animation.getKeys();
  50716. if (this._from > keys[0].frame) {
  50717. this._from = keys[0].frame;
  50718. }
  50719. if (this._to < keys[keys.length - 1].frame) {
  50720. this._to = keys[keys.length - 1].frame;
  50721. }
  50722. this._targetedAnimations.push(targetedAnimation);
  50723. return targetedAnimation;
  50724. };
  50725. /**
  50726. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50727. * It can add constant keys at begin or end
  50728. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50729. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50730. */
  50731. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50732. if (beginFrame === void 0) { beginFrame = null; }
  50733. if (endFrame === void 0) { endFrame = null; }
  50734. if (beginFrame == null)
  50735. beginFrame = this._from;
  50736. if (endFrame == null)
  50737. endFrame = this._to;
  50738. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50739. var targetedAnimation = this._targetedAnimations[index];
  50740. var keys = targetedAnimation.animation.getKeys();
  50741. var startKey = keys[0];
  50742. var endKey = keys[keys.length - 1];
  50743. if (startKey.frame > beginFrame) {
  50744. var newKey = {
  50745. frame: beginFrame,
  50746. value: startKey.value,
  50747. inTangent: startKey.inTangent,
  50748. outTangent: startKey.outTangent,
  50749. interpolation: startKey.interpolation
  50750. };
  50751. keys.splice(0, 0, newKey);
  50752. }
  50753. if (endKey.frame < endFrame) {
  50754. var newKey = {
  50755. frame: endFrame,
  50756. value: endKey.value,
  50757. inTangent: endKey.outTangent,
  50758. outTangent: endKey.outTangent,
  50759. interpolation: endKey.interpolation
  50760. };
  50761. keys.push(newKey);
  50762. }
  50763. }
  50764. this._from = beginFrame;
  50765. this._to = endFrame;
  50766. return this;
  50767. };
  50768. /**
  50769. * Start all animations on given targets
  50770. * @param loop defines if animations must loop
  50771. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50772. * @param from defines the from key (optional)
  50773. * @param to defines the to key (optional)
  50774. * @returns the current animation group
  50775. */
  50776. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50777. var _this = this;
  50778. if (loop === void 0) { loop = false; }
  50779. if (speedRatio === void 0) { speedRatio = 1; }
  50780. if (this._isStarted || this._targetedAnimations.length === 0) {
  50781. return this;
  50782. }
  50783. var _loop_1 = function (targetedAnimation) {
  50784. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50785. animatable.onAnimationEnd = function () {
  50786. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50787. _this._checkAnimationGroupEnded(animatable);
  50788. };
  50789. this_1._animatables.push(animatable);
  50790. };
  50791. var this_1 = this;
  50792. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50793. var targetedAnimation = _a[_i];
  50794. _loop_1(targetedAnimation);
  50795. }
  50796. this._speedRatio = speedRatio;
  50797. this._isStarted = true;
  50798. return this;
  50799. };
  50800. /**
  50801. * Pause all animations
  50802. */
  50803. AnimationGroup.prototype.pause = function () {
  50804. if (!this._isStarted) {
  50805. return this;
  50806. }
  50807. for (var index = 0; index < this._animatables.length; index++) {
  50808. var animatable = this._animatables[index];
  50809. animatable.pause();
  50810. }
  50811. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50812. return this;
  50813. };
  50814. /**
  50815. * Play all animations to initial state
  50816. * This function will start() the animations if they were not started or will restart() them if they were paused
  50817. * @param loop defines if animations must loop
  50818. */
  50819. AnimationGroup.prototype.play = function (loop) {
  50820. // only if all animatables are ready and exist
  50821. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50822. if (loop !== undefined) {
  50823. for (var index = 0; index < this._animatables.length; index++) {
  50824. var animatable = this._animatables[index];
  50825. animatable.loopAnimation = loop;
  50826. }
  50827. }
  50828. this.restart();
  50829. }
  50830. else {
  50831. this.stop();
  50832. this.start(loop, this._speedRatio);
  50833. }
  50834. return this;
  50835. };
  50836. /**
  50837. * Reset all animations to initial state
  50838. */
  50839. AnimationGroup.prototype.reset = function () {
  50840. if (!this._isStarted) {
  50841. return this;
  50842. }
  50843. for (var index = 0; index < this._animatables.length; index++) {
  50844. var animatable = this._animatables[index];
  50845. animatable.reset();
  50846. }
  50847. return this;
  50848. };
  50849. /**
  50850. * Restart animations from key 0
  50851. */
  50852. AnimationGroup.prototype.restart = function () {
  50853. if (!this._isStarted) {
  50854. return this;
  50855. }
  50856. for (var index = 0; index < this._animatables.length; index++) {
  50857. var animatable = this._animatables[index];
  50858. animatable.restart();
  50859. }
  50860. return this;
  50861. };
  50862. /**
  50863. * Stop all animations
  50864. */
  50865. AnimationGroup.prototype.stop = function () {
  50866. if (!this._isStarted) {
  50867. return this;
  50868. }
  50869. var list = this._animatables.slice();
  50870. for (var index = 0; index < list.length; index++) {
  50871. list[index].stop();
  50872. }
  50873. this._isStarted = false;
  50874. return this;
  50875. };
  50876. /**
  50877. * Set animation weight for all animatables
  50878. * @param weight defines the weight to use
  50879. * @return the animationGroup
  50880. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50881. */
  50882. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50883. for (var index = 0; index < this._animatables.length; index++) {
  50884. var animatable = this._animatables[index];
  50885. animatable.weight = weight;
  50886. }
  50887. return this;
  50888. };
  50889. /**
  50890. * Synchronize and normalize all animatables with a source animatable
  50891. * @param root defines the root animatable to synchronize with
  50892. * @return the animationGroup
  50893. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50894. */
  50895. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50896. for (var index = 0; index < this._animatables.length; index++) {
  50897. var animatable = this._animatables[index];
  50898. animatable.syncWith(root);
  50899. }
  50900. return this;
  50901. };
  50902. /**
  50903. * Goes to a specific frame in this animation group
  50904. * @param frame the frame number to go to
  50905. * @return the animationGroup
  50906. */
  50907. AnimationGroup.prototype.goToFrame = function (frame) {
  50908. if (!this._isStarted) {
  50909. return this;
  50910. }
  50911. for (var index = 0; index < this._animatables.length; index++) {
  50912. var animatable = this._animatables[index];
  50913. animatable.goToFrame(frame);
  50914. }
  50915. return this;
  50916. };
  50917. /**
  50918. * Dispose all associated resources
  50919. */
  50920. AnimationGroup.prototype.dispose = function () {
  50921. this._targetedAnimations = [];
  50922. this._animatables = [];
  50923. var index = this._scene.animationGroups.indexOf(this);
  50924. if (index > -1) {
  50925. this._scene.animationGroups.splice(index, 1);
  50926. }
  50927. };
  50928. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50929. // animatable should be taken out of the array
  50930. var idx = this._animatables.indexOf(animatable);
  50931. if (idx > -1) {
  50932. this._animatables.splice(idx, 1);
  50933. }
  50934. // all animatables were removed? animation group ended!
  50935. if (this._animatables.length === 0) {
  50936. this._isStarted = false;
  50937. this.onAnimationGroupEndObservable.notifyObservers(this);
  50938. }
  50939. };
  50940. // Statics
  50941. /**
  50942. * Returns a new AnimationGroup object parsed from the source provided.
  50943. * @param parsedAnimationGroup defines the source
  50944. * @param scene defines the scene that will receive the animationGroup
  50945. * @returns a new AnimationGroup
  50946. */
  50947. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  50948. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  50949. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  50950. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  50951. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  50952. var id = targetedAnimation.targetId;
  50953. var targetNode = scene.getNodeByID(id);
  50954. if (targetNode != null)
  50955. animationGroup.addTargetedAnimation(animation, targetNode);
  50956. }
  50957. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  50958. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  50959. return animationGroup;
  50960. };
  50961. /**
  50962. * Returns the string "AnimationGroup"
  50963. * @returns "AnimationGroup"
  50964. */
  50965. AnimationGroup.prototype.getClassName = function () {
  50966. return "AnimationGroup";
  50967. };
  50968. /**
  50969. * Creates a detailled string about the object
  50970. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  50971. * @returns a string representing the object
  50972. */
  50973. AnimationGroup.prototype.toString = function (fullDetails) {
  50974. var ret = "Name: " + this.name;
  50975. ret += ", type: " + this.getClassName();
  50976. if (fullDetails) {
  50977. ret += ", from: " + this._from;
  50978. ret += ", to: " + this._to;
  50979. ret += ", isStarted: " + this._isStarted;
  50980. ret += ", speedRatio: " + this._speedRatio;
  50981. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  50982. ret += ", animatables length: " + this._animatables;
  50983. }
  50984. return ret;
  50985. };
  50986. return AnimationGroup;
  50987. }());
  50988. BABYLON.AnimationGroup = AnimationGroup;
  50989. })(BABYLON || (BABYLON = {}));
  50990. //# sourceMappingURL=babylon.animationGroup.js.map
  50991. var BABYLON;
  50992. (function (BABYLON) {
  50993. // Static values to help the garbage collector
  50994. // Quaternion
  50995. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  50996. // Vector3
  50997. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  50998. // Vector2
  50999. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51000. // Size
  51001. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51002. // Color3
  51003. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51004. /**
  51005. * Defines a runtime animation
  51006. */
  51007. var RuntimeAnimation = /** @class */ (function () {
  51008. /**
  51009. * Create a new RuntimeAnimation object
  51010. * @param target defines the target of the animation
  51011. * @param animation defines the source animation object
  51012. * @param scene defines the hosting scene
  51013. * @param host defines the initiating Animatable
  51014. */
  51015. function RuntimeAnimation(target, animation, scene, host) {
  51016. var _this = this;
  51017. this._events = new Array();
  51018. /**
  51019. * The current frame of the runtime animation
  51020. */
  51021. this._currentFrame = 0;
  51022. /**
  51023. * The original value of the runtime animation
  51024. */
  51025. this._originalValue = new Array();
  51026. /**
  51027. * The offsets cache of the runtime animation
  51028. */
  51029. this._offsetsCache = {};
  51030. /**
  51031. * The high limits cache of the runtime animation
  51032. */
  51033. this._highLimitsCache = {};
  51034. /**
  51035. * Specifies if the runtime animation has been stopped
  51036. */
  51037. this._stopped = false;
  51038. /**
  51039. * The blending factor of the runtime animation
  51040. */
  51041. this._blendingFactor = 0;
  51042. /**
  51043. * The target path of the runtime animation
  51044. */
  51045. this._targetPath = "";
  51046. /**
  51047. * The weight of the runtime animation
  51048. */
  51049. this._weight = 1.0;
  51050. /**
  51051. * The ratio offset of the runtime animation
  51052. */
  51053. this._ratioOffset = 0;
  51054. /**
  51055. * The previous delay of the runtime animation
  51056. */
  51057. this._previousDelay = 0;
  51058. /**
  51059. * The previous ratio of the runtime animation
  51060. */
  51061. this._previousRatio = 0;
  51062. this._animation = animation;
  51063. this._target = target;
  51064. this._scene = scene;
  51065. this._host = host;
  51066. animation._runtimeAnimations.push(this);
  51067. // Cloning events locally
  51068. var events = animation.getEvents();
  51069. if (events && events.length > 0) {
  51070. events.forEach(function (e) {
  51071. _this._events.push(e._clone());
  51072. });
  51073. }
  51074. }
  51075. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51076. /**
  51077. * Gets the current frame of the runtime animation
  51078. */
  51079. get: function () {
  51080. return this._currentFrame;
  51081. },
  51082. enumerable: true,
  51083. configurable: true
  51084. });
  51085. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51086. /**
  51087. * Gets the weight of the runtime animation
  51088. */
  51089. get: function () {
  51090. return this._weight;
  51091. },
  51092. enumerable: true,
  51093. configurable: true
  51094. });
  51095. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51096. /**
  51097. * Gets the current value of the runtime animation
  51098. */
  51099. get: function () {
  51100. return this._currentValue;
  51101. },
  51102. enumerable: true,
  51103. configurable: true
  51104. });
  51105. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51106. /**
  51107. * Gets the target path of the runtime animation
  51108. */
  51109. get: function () {
  51110. return this._targetPath;
  51111. },
  51112. enumerable: true,
  51113. configurable: true
  51114. });
  51115. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51116. /**
  51117. * Gets the actual target of the runtime animation
  51118. */
  51119. get: function () {
  51120. return this._activeTarget;
  51121. },
  51122. enumerable: true,
  51123. configurable: true
  51124. });
  51125. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51126. /**
  51127. * Gets the animation from the runtime animation
  51128. */
  51129. get: function () {
  51130. return this._animation;
  51131. },
  51132. enumerable: true,
  51133. configurable: true
  51134. });
  51135. /**
  51136. * Resets the runtime animation to the beginning
  51137. * @param restoreOriginal defines whether to restore the target property to the original value
  51138. */
  51139. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51140. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51141. if (restoreOriginal) {
  51142. if (this._target instanceof Array) {
  51143. var index = 0;
  51144. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51145. var target = _a[_i];
  51146. if (this._originalValue[index] !== undefined) {
  51147. this._setValue(target, this._originalValue[index], -1);
  51148. }
  51149. index++;
  51150. }
  51151. }
  51152. else {
  51153. if (this._originalValue[0] !== undefined) {
  51154. this._setValue(this._target, this._originalValue[0], -1);
  51155. }
  51156. }
  51157. }
  51158. this._offsetsCache = {};
  51159. this._highLimitsCache = {};
  51160. this._currentFrame = 0;
  51161. this._blendingFactor = 0;
  51162. this._originalValue = new Array();
  51163. // Events
  51164. for (var index = 0; index < this._events.length; index++) {
  51165. this._events[index].isDone = false;
  51166. }
  51167. };
  51168. /**
  51169. * Specifies if the runtime animation is stopped
  51170. * @returns Boolean specifying if the runtime animation is stopped
  51171. */
  51172. RuntimeAnimation.prototype.isStopped = function () {
  51173. return this._stopped;
  51174. };
  51175. /**
  51176. * Disposes of the runtime animation
  51177. */
  51178. RuntimeAnimation.prototype.dispose = function () {
  51179. var index = this._animation.runtimeAnimations.indexOf(this);
  51180. if (index > -1) {
  51181. this._animation.runtimeAnimations.splice(index, 1);
  51182. }
  51183. };
  51184. /**
  51185. * Interpolates the animation from the current frame
  51186. * @param currentFrame The frame to interpolate the animation to
  51187. * @param repeatCount The number of times that the animation should loop
  51188. * @param loopMode The type of looping mode to use
  51189. * @param offsetValue Animation offset value
  51190. * @param highLimitValue The high limit value
  51191. * @returns The interpolated value
  51192. */
  51193. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51194. this._currentFrame = currentFrame;
  51195. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51196. this._workValue = BABYLON.Matrix.Zero();
  51197. }
  51198. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51199. };
  51200. /**
  51201. * Apply the interpolated value to the target
  51202. * @param currentValue defines the value computed by the animation
  51203. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51204. */
  51205. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51206. if (weight === void 0) { weight = 1.0; }
  51207. if (this._target instanceof Array) {
  51208. var index = 0;
  51209. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51210. var target = _a[_i];
  51211. this._setValue(target, currentValue, weight, index);
  51212. index++;
  51213. }
  51214. }
  51215. else {
  51216. this._setValue(this._target, currentValue, weight);
  51217. }
  51218. };
  51219. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51220. if (targetIndex === void 0) { targetIndex = 0; }
  51221. // Set value
  51222. var path;
  51223. var destination;
  51224. var targetPropertyPath = this._animation.targetPropertyPath;
  51225. if (targetPropertyPath.length > 1) {
  51226. var property = target[targetPropertyPath[0]];
  51227. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51228. property = property[targetPropertyPath[index]];
  51229. }
  51230. path = targetPropertyPath[targetPropertyPath.length - 1];
  51231. destination = property;
  51232. }
  51233. else {
  51234. path = targetPropertyPath[0];
  51235. destination = target;
  51236. }
  51237. this._targetPath = path;
  51238. this._activeTarget = destination;
  51239. this._weight = weight;
  51240. if (this._originalValue[targetIndex] === undefined) {
  51241. var originalValue = void 0;
  51242. if (destination.getRestPose && path === "_matrix") { // For bones
  51243. originalValue = destination.getRestPose();
  51244. }
  51245. else {
  51246. originalValue = destination[path];
  51247. }
  51248. if (originalValue && originalValue.clone) {
  51249. this._originalValue[targetIndex] = originalValue.clone();
  51250. }
  51251. else {
  51252. this._originalValue[targetIndex] = originalValue;
  51253. }
  51254. }
  51255. // Blending
  51256. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51257. if (enableBlending && this._blendingFactor <= 1.0) {
  51258. if (!this._originalBlendValue) {
  51259. var originalValue = destination[path];
  51260. if (originalValue.clone) {
  51261. this._originalBlendValue = originalValue.clone();
  51262. }
  51263. else {
  51264. this._originalBlendValue = originalValue;
  51265. }
  51266. }
  51267. if (this._originalBlendValue.m) { // Matrix
  51268. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51269. if (this._currentValue) {
  51270. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51271. }
  51272. else {
  51273. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51274. }
  51275. }
  51276. else {
  51277. if (this._currentValue) {
  51278. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51279. }
  51280. else {
  51281. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51282. }
  51283. }
  51284. }
  51285. else {
  51286. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51287. }
  51288. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51289. this._blendingFactor += blendingSpeed;
  51290. }
  51291. else {
  51292. this._currentValue = currentValue;
  51293. }
  51294. if (weight !== -1.0) {
  51295. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51296. }
  51297. else {
  51298. destination[path] = this._currentValue;
  51299. }
  51300. if (target.markAsDirty) {
  51301. target.markAsDirty(this._animation.targetProperty);
  51302. }
  51303. };
  51304. /**
  51305. * Gets the loop pmode of the runtime animation
  51306. * @returns Loop Mode
  51307. */
  51308. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51309. if (this._target && this._target.animationPropertiesOverride) {
  51310. return this._target.animationPropertiesOverride.loopMode;
  51311. }
  51312. return this._animation.loopMode;
  51313. };
  51314. /**
  51315. * Move the current animation to a given frame
  51316. * @param frame defines the frame to move to
  51317. */
  51318. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51319. var keys = this._animation.getKeys();
  51320. if (frame < keys[0].frame) {
  51321. frame = keys[0].frame;
  51322. }
  51323. else if (frame > keys[keys.length - 1].frame) {
  51324. frame = keys[keys.length - 1].frame;
  51325. }
  51326. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51327. this.setValue(currentValue, -1);
  51328. };
  51329. /**
  51330. * @hidden Internal use only
  51331. */
  51332. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51333. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51334. this._ratioOffset = this._previousRatio - newRatio;
  51335. };
  51336. /**
  51337. * Execute the current animation
  51338. * @param delay defines the delay to add to the current frame
  51339. * @param from defines the lower bound of the animation range
  51340. * @param to defines the upper bound of the animation range
  51341. * @param loop defines if the current animation must loop
  51342. * @param speedRatio defines the current speed ratio
  51343. * @param weight defines the weight of the animation (default is -1 so no weight)
  51344. * @returns a boolean indicating if the animation is running
  51345. */
  51346. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51347. if (weight === void 0) { weight = -1.0; }
  51348. var targetPropertyPath = this._animation.targetPropertyPath;
  51349. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51350. this._stopped = true;
  51351. return false;
  51352. }
  51353. var returnValue = true;
  51354. var keys = this._animation.getKeys();
  51355. // Adding a start key at frame 0 if missing
  51356. if (keys[0].frame !== 0) {
  51357. var newKey = { frame: 0, value: keys[0].value };
  51358. keys.splice(0, 0, newKey);
  51359. }
  51360. // Adding a duplicate key when there is only one key at frame zero
  51361. else if (keys.length === 1) {
  51362. var newKey = { frame: 0.001, value: keys[0].value };
  51363. keys.push(newKey);
  51364. }
  51365. // Check limits
  51366. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51367. from = keys[0].frame;
  51368. }
  51369. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51370. to = keys[keys.length - 1].frame;
  51371. }
  51372. //to and from cannot be the same key
  51373. if (from === to) {
  51374. if (from > keys[0].frame) {
  51375. from--;
  51376. }
  51377. else if (to < keys[keys.length - 1].frame) {
  51378. to++;
  51379. }
  51380. }
  51381. // Compute ratio
  51382. var range = to - from;
  51383. var offsetValue;
  51384. // ratio represents the frame delta between from and to
  51385. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51386. var highLimitValue = 0;
  51387. this._previousDelay = delay;
  51388. this._previousRatio = ratio;
  51389. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51390. returnValue = false;
  51391. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51392. }
  51393. else {
  51394. // Get max value if required
  51395. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51396. var keyOffset = to.toString() + from.toString();
  51397. if (!this._offsetsCache[keyOffset]) {
  51398. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51399. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51400. switch (this._animation.dataType) {
  51401. // Float
  51402. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51403. this._offsetsCache[keyOffset] = toValue - fromValue;
  51404. break;
  51405. // Quaternion
  51406. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51407. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51408. break;
  51409. // Vector3
  51410. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51411. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51412. // Vector2
  51413. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51414. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51415. // Size
  51416. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51417. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51418. // Color3
  51419. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51420. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51421. default:
  51422. break;
  51423. }
  51424. this._highLimitsCache[keyOffset] = toValue;
  51425. }
  51426. highLimitValue = this._highLimitsCache[keyOffset];
  51427. offsetValue = this._offsetsCache[keyOffset];
  51428. }
  51429. }
  51430. if (offsetValue === undefined) {
  51431. switch (this._animation.dataType) {
  51432. // Float
  51433. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51434. offsetValue = 0;
  51435. break;
  51436. // Quaternion
  51437. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51438. offsetValue = _staticOffsetValueQuaternion;
  51439. break;
  51440. // Vector3
  51441. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51442. offsetValue = _staticOffsetValueVector3;
  51443. break;
  51444. // Vector2
  51445. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51446. offsetValue = _staticOffsetValueVector2;
  51447. break;
  51448. // Size
  51449. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51450. offsetValue = _staticOffsetValueSize;
  51451. break;
  51452. // Color3
  51453. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51454. offsetValue = _staticOffsetValueColor3;
  51455. }
  51456. }
  51457. // Compute value
  51458. var repeatCount = (ratio / range) >> 0;
  51459. var currentFrame = returnValue ? from + ratio % range : to;
  51460. // Need to normalize?
  51461. if (this._host && this._host.syncRoot) {
  51462. var syncRoot = this._host.syncRoot;
  51463. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51464. currentFrame = from + (to - from) * hostNormalizedFrame;
  51465. }
  51466. // Reset events if looping
  51467. var events = this._events;
  51468. if (range > 0 && this.currentFrame > currentFrame ||
  51469. range < 0 && this.currentFrame < currentFrame) {
  51470. // Need to reset animation events
  51471. for (var index = 0; index < events.length; index++) {
  51472. if (!events[index].onlyOnce) {
  51473. // reset event, the animation is looping
  51474. events[index].isDone = false;
  51475. }
  51476. }
  51477. }
  51478. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51479. // Set value
  51480. this.setValue(currentValue, weight);
  51481. // Check events
  51482. for (var index = 0; index < events.length; index++) {
  51483. // Make sure current frame has passed event frame and that event frame is within the current range
  51484. // Also, handle both forward and reverse animations
  51485. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51486. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51487. var event = events[index];
  51488. if (!event.isDone) {
  51489. // If event should be done only once, remove it.
  51490. if (event.onlyOnce) {
  51491. events.splice(index, 1);
  51492. index--;
  51493. }
  51494. event.isDone = true;
  51495. event.action(currentFrame);
  51496. } // Don't do anything if the event has already be done.
  51497. }
  51498. }
  51499. if (!returnValue) {
  51500. this._stopped = true;
  51501. }
  51502. return returnValue;
  51503. };
  51504. return RuntimeAnimation;
  51505. }());
  51506. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51507. })(BABYLON || (BABYLON = {}));
  51508. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51509. var BABYLON;
  51510. (function (BABYLON) {
  51511. /**
  51512. * Class used to store an actual running animation
  51513. */
  51514. var Animatable = /** @class */ (function () {
  51515. /**
  51516. * Creates a new Animatable
  51517. * @param scene defines the hosting scene
  51518. * @param target defines the target object
  51519. * @param fromFrame defines the starting frame number (default is 0)
  51520. * @param toFrame defines the ending frame number (default is 100)
  51521. * @param loopAnimation defines if the animation must loop (default is false)
  51522. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51523. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51524. * @param animations defines a group of animation to add to the new Animatable
  51525. */
  51526. function Animatable(scene,
  51527. /** defines the target object */
  51528. target,
  51529. /** defines the starting frame number (default is 0) */
  51530. fromFrame,
  51531. /** defines the ending frame number (default is 100) */
  51532. toFrame,
  51533. /** defines if the animation must loop (default is false) */
  51534. loopAnimation, speedRatio,
  51535. /** defines a callback to call when animation ends if it is not looping */
  51536. onAnimationEnd, animations) {
  51537. if (fromFrame === void 0) { fromFrame = 0; }
  51538. if (toFrame === void 0) { toFrame = 100; }
  51539. if (loopAnimation === void 0) { loopAnimation = false; }
  51540. if (speedRatio === void 0) { speedRatio = 1.0; }
  51541. this.target = target;
  51542. this.fromFrame = fromFrame;
  51543. this.toFrame = toFrame;
  51544. this.loopAnimation = loopAnimation;
  51545. this.onAnimationEnd = onAnimationEnd;
  51546. this._localDelayOffset = null;
  51547. this._pausedDelay = null;
  51548. this._runtimeAnimations = new Array();
  51549. this._paused = false;
  51550. this._speedRatio = 1;
  51551. this._weight = -1.0;
  51552. /**
  51553. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51554. * This will only apply for non looping animation (default is true)
  51555. */
  51556. this.disposeOnEnd = true;
  51557. /**
  51558. * Gets a boolean indicating if the animation has started
  51559. */
  51560. this.animationStarted = false;
  51561. /**
  51562. * Observer raised when the animation ends
  51563. */
  51564. this.onAnimationEndObservable = new BABYLON.Observable();
  51565. this._scene = scene;
  51566. if (animations) {
  51567. this.appendAnimations(target, animations);
  51568. }
  51569. this._speedRatio = speedRatio;
  51570. scene._activeAnimatables.push(this);
  51571. }
  51572. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51573. /**
  51574. * Gets the root Animatable used to synchronize and normalize animations
  51575. */
  51576. get: function () {
  51577. return this._syncRoot;
  51578. },
  51579. enumerable: true,
  51580. configurable: true
  51581. });
  51582. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51583. /**
  51584. * Gets the current frame of the first RuntimeAnimation
  51585. * Used to synchronize Animatables
  51586. */
  51587. get: function () {
  51588. if (this._runtimeAnimations.length === 0) {
  51589. return 0;
  51590. }
  51591. return this._runtimeAnimations[0].currentFrame;
  51592. },
  51593. enumerable: true,
  51594. configurable: true
  51595. });
  51596. Object.defineProperty(Animatable.prototype, "weight", {
  51597. /**
  51598. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51599. */
  51600. get: function () {
  51601. return this._weight;
  51602. },
  51603. set: function (value) {
  51604. if (value === -1) { // -1 is ok and means no weight
  51605. this._weight = -1;
  51606. return;
  51607. }
  51608. // Else weight must be in [0, 1] range
  51609. this._weight = Math.min(Math.max(value, 0), 1.0);
  51610. },
  51611. enumerable: true,
  51612. configurable: true
  51613. });
  51614. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51615. /**
  51616. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51617. */
  51618. get: function () {
  51619. return this._speedRatio;
  51620. },
  51621. set: function (value) {
  51622. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51623. var animation = this._runtimeAnimations[index];
  51624. animation._prepareForSpeedRatioChange(value);
  51625. }
  51626. this._speedRatio = value;
  51627. },
  51628. enumerable: true,
  51629. configurable: true
  51630. });
  51631. // Methods
  51632. /**
  51633. * Synchronize and normalize current Animatable with a source Animatable
  51634. * This is useful when using animation weights and when animations are not of the same length
  51635. * @param root defines the root Animatable to synchronize with
  51636. * @returns the current Animatable
  51637. */
  51638. Animatable.prototype.syncWith = function (root) {
  51639. this._syncRoot = root;
  51640. if (root) {
  51641. // Make sure this animatable will animate after the root
  51642. var index = this._scene._activeAnimatables.indexOf(this);
  51643. if (index > -1) {
  51644. this._scene._activeAnimatables.splice(index, 1);
  51645. this._scene._activeAnimatables.push(this);
  51646. }
  51647. }
  51648. return this;
  51649. };
  51650. /**
  51651. * Gets the list of runtime animations
  51652. * @returns an array of RuntimeAnimation
  51653. */
  51654. Animatable.prototype.getAnimations = function () {
  51655. return this._runtimeAnimations;
  51656. };
  51657. /**
  51658. * Adds more animations to the current animatable
  51659. * @param target defines the target of the animations
  51660. * @param animations defines the new animations to add
  51661. */
  51662. Animatable.prototype.appendAnimations = function (target, animations) {
  51663. for (var index = 0; index < animations.length; index++) {
  51664. var animation = animations[index];
  51665. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51666. }
  51667. };
  51668. /**
  51669. * Gets the source animation for a specific property
  51670. * @param property defines the propertyu to look for
  51671. * @returns null or the source animation for the given property
  51672. */
  51673. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51674. var runtimeAnimations = this._runtimeAnimations;
  51675. for (var index = 0; index < runtimeAnimations.length; index++) {
  51676. if (runtimeAnimations[index].animation.targetProperty === property) {
  51677. return runtimeAnimations[index].animation;
  51678. }
  51679. }
  51680. return null;
  51681. };
  51682. /**
  51683. * Gets the runtime animation for a specific property
  51684. * @param property defines the propertyu to look for
  51685. * @returns null or the runtime animation for the given property
  51686. */
  51687. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51688. var runtimeAnimations = this._runtimeAnimations;
  51689. for (var index = 0; index < runtimeAnimations.length; index++) {
  51690. if (runtimeAnimations[index].animation.targetProperty === property) {
  51691. return runtimeAnimations[index];
  51692. }
  51693. }
  51694. return null;
  51695. };
  51696. /**
  51697. * Resets the animatable to its original state
  51698. */
  51699. Animatable.prototype.reset = function () {
  51700. var runtimeAnimations = this._runtimeAnimations;
  51701. for (var index = 0; index < runtimeAnimations.length; index++) {
  51702. runtimeAnimations[index].reset(true);
  51703. }
  51704. this._localDelayOffset = null;
  51705. this._pausedDelay = null;
  51706. };
  51707. /**
  51708. * Allows the animatable to blend with current running animations
  51709. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51710. * @param blendingSpeed defines the blending speed to use
  51711. */
  51712. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51713. var runtimeAnimations = this._runtimeAnimations;
  51714. for (var index = 0; index < runtimeAnimations.length; index++) {
  51715. runtimeAnimations[index].animation.enableBlending = true;
  51716. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51717. }
  51718. };
  51719. /**
  51720. * Disable animation blending
  51721. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51722. */
  51723. Animatable.prototype.disableBlending = function () {
  51724. var runtimeAnimations = this._runtimeAnimations;
  51725. for (var index = 0; index < runtimeAnimations.length; index++) {
  51726. runtimeAnimations[index].animation.enableBlending = false;
  51727. }
  51728. };
  51729. /**
  51730. * Jump directly to a given frame
  51731. * @param frame defines the frame to jump to
  51732. */
  51733. Animatable.prototype.goToFrame = function (frame) {
  51734. var runtimeAnimations = this._runtimeAnimations;
  51735. if (runtimeAnimations[0]) {
  51736. var fps = runtimeAnimations[0].animation.framePerSecond;
  51737. var currentFrame = runtimeAnimations[0].currentFrame;
  51738. var adjustTime = frame - currentFrame;
  51739. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51740. if (this._localDelayOffset === null) {
  51741. this._localDelayOffset = 0;
  51742. }
  51743. this._localDelayOffset -= delay;
  51744. }
  51745. for (var index = 0; index < runtimeAnimations.length; index++) {
  51746. runtimeAnimations[index].goToFrame(frame);
  51747. }
  51748. };
  51749. /**
  51750. * Pause the animation
  51751. */
  51752. Animatable.prototype.pause = function () {
  51753. if (this._paused) {
  51754. return;
  51755. }
  51756. this._paused = true;
  51757. };
  51758. /**
  51759. * Restart the animation
  51760. */
  51761. Animatable.prototype.restart = function () {
  51762. this._paused = false;
  51763. };
  51764. Animatable.prototype._raiseOnAnimationEnd = function () {
  51765. if (this.onAnimationEnd) {
  51766. this.onAnimationEnd();
  51767. }
  51768. this.onAnimationEndObservable.notifyObservers(this);
  51769. };
  51770. /**
  51771. * Stop and delete the current animation
  51772. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51773. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51774. */
  51775. Animatable.prototype.stop = function (animationName, targetMask) {
  51776. if (animationName || targetMask) {
  51777. var idx = this._scene._activeAnimatables.indexOf(this);
  51778. if (idx > -1) {
  51779. var runtimeAnimations = this._runtimeAnimations;
  51780. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51781. var runtimeAnimation = runtimeAnimations[index];
  51782. if (animationName && runtimeAnimation.animation.name != animationName) {
  51783. continue;
  51784. }
  51785. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51786. continue;
  51787. }
  51788. runtimeAnimation.dispose();
  51789. runtimeAnimations.splice(index, 1);
  51790. }
  51791. if (runtimeAnimations.length == 0) {
  51792. this._scene._activeAnimatables.splice(idx, 1);
  51793. this._raiseOnAnimationEnd();
  51794. }
  51795. }
  51796. }
  51797. else {
  51798. var index = this._scene._activeAnimatables.indexOf(this);
  51799. if (index > -1) {
  51800. this._scene._activeAnimatables.splice(index, 1);
  51801. var runtimeAnimations = this._runtimeAnimations;
  51802. for (var index = 0; index < runtimeAnimations.length; index++) {
  51803. runtimeAnimations[index].dispose();
  51804. }
  51805. this._raiseOnAnimationEnd();
  51806. }
  51807. }
  51808. };
  51809. /**
  51810. * Wait asynchronously for the animation to end
  51811. * @returns a promise which will be fullfilled when the animation ends
  51812. */
  51813. Animatable.prototype.waitAsync = function () {
  51814. var _this = this;
  51815. return new Promise(function (resolve, reject) {
  51816. _this.onAnimationEndObservable.add(function () {
  51817. resolve(_this);
  51818. }, undefined, undefined, _this, true);
  51819. });
  51820. };
  51821. /** @hidden */
  51822. Animatable.prototype._animate = function (delay) {
  51823. if (this._paused) {
  51824. this.animationStarted = false;
  51825. if (this._pausedDelay === null) {
  51826. this._pausedDelay = delay;
  51827. }
  51828. return true;
  51829. }
  51830. if (this._localDelayOffset === null) {
  51831. this._localDelayOffset = delay;
  51832. this._pausedDelay = null;
  51833. }
  51834. else if (this._pausedDelay !== null) {
  51835. this._localDelayOffset += delay - this._pausedDelay;
  51836. this._pausedDelay = null;
  51837. }
  51838. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51839. return true;
  51840. }
  51841. // Animating
  51842. var running = false;
  51843. var runtimeAnimations = this._runtimeAnimations;
  51844. var index;
  51845. for (index = 0; index < runtimeAnimations.length; index++) {
  51846. var animation = runtimeAnimations[index];
  51847. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51848. running = running || isRunning;
  51849. }
  51850. this.animationStarted = running;
  51851. if (!running) {
  51852. if (this.disposeOnEnd) {
  51853. // Remove from active animatables
  51854. index = this._scene._activeAnimatables.indexOf(this);
  51855. this._scene._activeAnimatables.splice(index, 1);
  51856. // Dispose all runtime animations
  51857. for (index = 0; index < runtimeAnimations.length; index++) {
  51858. runtimeAnimations[index].dispose();
  51859. }
  51860. }
  51861. this._raiseOnAnimationEnd();
  51862. if (this.disposeOnEnd) {
  51863. this.onAnimationEnd = null;
  51864. this.onAnimationEndObservable.clear();
  51865. }
  51866. }
  51867. return running;
  51868. };
  51869. return Animatable;
  51870. }());
  51871. BABYLON.Animatable = Animatable;
  51872. })(BABYLON || (BABYLON = {}));
  51873. //# sourceMappingURL=babylon.animatable.js.map
  51874. var BABYLON;
  51875. (function (BABYLON) {
  51876. var EasingFunction = /** @class */ (function () {
  51877. function EasingFunction() {
  51878. // Properties
  51879. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51880. }
  51881. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51882. get: function () {
  51883. return EasingFunction._EASINGMODE_EASEIN;
  51884. },
  51885. enumerable: true,
  51886. configurable: true
  51887. });
  51888. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51889. get: function () {
  51890. return EasingFunction._EASINGMODE_EASEOUT;
  51891. },
  51892. enumerable: true,
  51893. configurable: true
  51894. });
  51895. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51896. get: function () {
  51897. return EasingFunction._EASINGMODE_EASEINOUT;
  51898. },
  51899. enumerable: true,
  51900. configurable: true
  51901. });
  51902. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51903. var n = Math.min(Math.max(easingMode, 0), 2);
  51904. this._easingMode = n;
  51905. };
  51906. EasingFunction.prototype.getEasingMode = function () {
  51907. return this._easingMode;
  51908. };
  51909. EasingFunction.prototype.easeInCore = function (gradient) {
  51910. throw new Error('You must implement this method');
  51911. };
  51912. EasingFunction.prototype.ease = function (gradient) {
  51913. switch (this._easingMode) {
  51914. case EasingFunction.EASINGMODE_EASEIN:
  51915. return this.easeInCore(gradient);
  51916. case EasingFunction.EASINGMODE_EASEOUT:
  51917. return (1 - this.easeInCore(1 - gradient));
  51918. }
  51919. if (gradient >= 0.5) {
  51920. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51921. }
  51922. return (this.easeInCore(gradient * 2) * 0.5);
  51923. };
  51924. //Statics
  51925. EasingFunction._EASINGMODE_EASEIN = 0;
  51926. EasingFunction._EASINGMODE_EASEOUT = 1;
  51927. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51928. return EasingFunction;
  51929. }());
  51930. BABYLON.EasingFunction = EasingFunction;
  51931. var CircleEase = /** @class */ (function (_super) {
  51932. __extends(CircleEase, _super);
  51933. function CircleEase() {
  51934. return _super !== null && _super.apply(this, arguments) || this;
  51935. }
  51936. CircleEase.prototype.easeInCore = function (gradient) {
  51937. gradient = Math.max(0, Math.min(1, gradient));
  51938. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51939. };
  51940. return CircleEase;
  51941. }(EasingFunction));
  51942. BABYLON.CircleEase = CircleEase;
  51943. var BackEase = /** @class */ (function (_super) {
  51944. __extends(BackEase, _super);
  51945. function BackEase(amplitude) {
  51946. if (amplitude === void 0) { amplitude = 1; }
  51947. var _this = _super.call(this) || this;
  51948. _this.amplitude = amplitude;
  51949. return _this;
  51950. }
  51951. BackEase.prototype.easeInCore = function (gradient) {
  51952. var num = Math.max(0, this.amplitude);
  51953. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51954. };
  51955. return BackEase;
  51956. }(EasingFunction));
  51957. BABYLON.BackEase = BackEase;
  51958. var BounceEase = /** @class */ (function (_super) {
  51959. __extends(BounceEase, _super);
  51960. function BounceEase(bounces, bounciness) {
  51961. if (bounces === void 0) { bounces = 3; }
  51962. if (bounciness === void 0) { bounciness = 2; }
  51963. var _this = _super.call(this) || this;
  51964. _this.bounces = bounces;
  51965. _this.bounciness = bounciness;
  51966. return _this;
  51967. }
  51968. BounceEase.prototype.easeInCore = function (gradient) {
  51969. var y = Math.max(0.0, this.bounces);
  51970. var bounciness = this.bounciness;
  51971. if (bounciness <= 1.0) {
  51972. bounciness = 1.001;
  51973. }
  51974. var num9 = Math.pow(bounciness, y);
  51975. var num5 = 1.0 - bounciness;
  51976. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51977. var num15 = gradient * num4;
  51978. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51979. var num3 = Math.floor(num65);
  51980. var num13 = num3 + 1.0;
  51981. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51982. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51983. var num7 = (num8 + num12) * 0.5;
  51984. var num6 = gradient - num7;
  51985. var num2 = num7 - num8;
  51986. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51987. };
  51988. return BounceEase;
  51989. }(EasingFunction));
  51990. BABYLON.BounceEase = BounceEase;
  51991. var CubicEase = /** @class */ (function (_super) {
  51992. __extends(CubicEase, _super);
  51993. function CubicEase() {
  51994. return _super !== null && _super.apply(this, arguments) || this;
  51995. }
  51996. CubicEase.prototype.easeInCore = function (gradient) {
  51997. return (gradient * gradient * gradient);
  51998. };
  51999. return CubicEase;
  52000. }(EasingFunction));
  52001. BABYLON.CubicEase = CubicEase;
  52002. var ElasticEase = /** @class */ (function (_super) {
  52003. __extends(ElasticEase, _super);
  52004. function ElasticEase(oscillations, springiness) {
  52005. if (oscillations === void 0) { oscillations = 3; }
  52006. if (springiness === void 0) { springiness = 3; }
  52007. var _this = _super.call(this) || this;
  52008. _this.oscillations = oscillations;
  52009. _this.springiness = springiness;
  52010. return _this;
  52011. }
  52012. ElasticEase.prototype.easeInCore = function (gradient) {
  52013. var num2;
  52014. var num3 = Math.max(0.0, this.oscillations);
  52015. var num = Math.max(0.0, this.springiness);
  52016. if (num == 0) {
  52017. num2 = gradient;
  52018. }
  52019. else {
  52020. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52021. }
  52022. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52023. };
  52024. return ElasticEase;
  52025. }(EasingFunction));
  52026. BABYLON.ElasticEase = ElasticEase;
  52027. var ExponentialEase = /** @class */ (function (_super) {
  52028. __extends(ExponentialEase, _super);
  52029. function ExponentialEase(exponent) {
  52030. if (exponent === void 0) { exponent = 2; }
  52031. var _this = _super.call(this) || this;
  52032. _this.exponent = exponent;
  52033. return _this;
  52034. }
  52035. ExponentialEase.prototype.easeInCore = function (gradient) {
  52036. if (this.exponent <= 0) {
  52037. return gradient;
  52038. }
  52039. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52040. };
  52041. return ExponentialEase;
  52042. }(EasingFunction));
  52043. BABYLON.ExponentialEase = ExponentialEase;
  52044. var PowerEase = /** @class */ (function (_super) {
  52045. __extends(PowerEase, _super);
  52046. function PowerEase(power) {
  52047. if (power === void 0) { power = 2; }
  52048. var _this = _super.call(this) || this;
  52049. _this.power = power;
  52050. return _this;
  52051. }
  52052. PowerEase.prototype.easeInCore = function (gradient) {
  52053. var y = Math.max(0.0, this.power);
  52054. return Math.pow(gradient, y);
  52055. };
  52056. return PowerEase;
  52057. }(EasingFunction));
  52058. BABYLON.PowerEase = PowerEase;
  52059. var QuadraticEase = /** @class */ (function (_super) {
  52060. __extends(QuadraticEase, _super);
  52061. function QuadraticEase() {
  52062. return _super !== null && _super.apply(this, arguments) || this;
  52063. }
  52064. QuadraticEase.prototype.easeInCore = function (gradient) {
  52065. return (gradient * gradient);
  52066. };
  52067. return QuadraticEase;
  52068. }(EasingFunction));
  52069. BABYLON.QuadraticEase = QuadraticEase;
  52070. var QuarticEase = /** @class */ (function (_super) {
  52071. __extends(QuarticEase, _super);
  52072. function QuarticEase() {
  52073. return _super !== null && _super.apply(this, arguments) || this;
  52074. }
  52075. QuarticEase.prototype.easeInCore = function (gradient) {
  52076. return (gradient * gradient * gradient * gradient);
  52077. };
  52078. return QuarticEase;
  52079. }(EasingFunction));
  52080. BABYLON.QuarticEase = QuarticEase;
  52081. var QuinticEase = /** @class */ (function (_super) {
  52082. __extends(QuinticEase, _super);
  52083. function QuinticEase() {
  52084. return _super !== null && _super.apply(this, arguments) || this;
  52085. }
  52086. QuinticEase.prototype.easeInCore = function (gradient) {
  52087. return (gradient * gradient * gradient * gradient * gradient);
  52088. };
  52089. return QuinticEase;
  52090. }(EasingFunction));
  52091. BABYLON.QuinticEase = QuinticEase;
  52092. var SineEase = /** @class */ (function (_super) {
  52093. __extends(SineEase, _super);
  52094. function SineEase() {
  52095. return _super !== null && _super.apply(this, arguments) || this;
  52096. }
  52097. SineEase.prototype.easeInCore = function (gradient) {
  52098. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52099. };
  52100. return SineEase;
  52101. }(EasingFunction));
  52102. BABYLON.SineEase = SineEase;
  52103. var BezierCurveEase = /** @class */ (function (_super) {
  52104. __extends(BezierCurveEase, _super);
  52105. function BezierCurveEase(x1, y1, x2, y2) {
  52106. if (x1 === void 0) { x1 = 0; }
  52107. if (y1 === void 0) { y1 = 0; }
  52108. if (x2 === void 0) { x2 = 1; }
  52109. if (y2 === void 0) { y2 = 1; }
  52110. var _this = _super.call(this) || this;
  52111. _this.x1 = x1;
  52112. _this.y1 = y1;
  52113. _this.x2 = x2;
  52114. _this.y2 = y2;
  52115. return _this;
  52116. }
  52117. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52118. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52119. };
  52120. return BezierCurveEase;
  52121. }(EasingFunction));
  52122. BABYLON.BezierCurveEase = BezierCurveEase;
  52123. })(BABYLON || (BABYLON = {}));
  52124. //# sourceMappingURL=babylon.easing.js.map
  52125. var BABYLON;
  52126. (function (BABYLON) {
  52127. /**
  52128. * A Condition applied to an Action
  52129. */
  52130. var Condition = /** @class */ (function () {
  52131. /**
  52132. * Creates a new Condition
  52133. * @param actionManager the manager of the action the condition is applied to
  52134. */
  52135. function Condition(actionManager) {
  52136. this._actionManager = actionManager;
  52137. }
  52138. /**
  52139. * Check if the current condition is valid
  52140. * @returns a boolean
  52141. */
  52142. Condition.prototype.isValid = function () {
  52143. return true;
  52144. };
  52145. /**
  52146. * Internal only
  52147. * @hidden
  52148. */
  52149. Condition.prototype._getProperty = function (propertyPath) {
  52150. return this._actionManager._getProperty(propertyPath);
  52151. };
  52152. /**
  52153. * Internal only
  52154. * @hidden
  52155. */
  52156. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52157. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52158. };
  52159. /**
  52160. * Serialize placeholder for child classes
  52161. * @returns the serialized object
  52162. */
  52163. Condition.prototype.serialize = function () {
  52164. };
  52165. /**
  52166. * Internal only
  52167. * @hidden
  52168. */
  52169. Condition.prototype._serialize = function (serializedCondition) {
  52170. return {
  52171. type: 2,
  52172. children: [],
  52173. name: serializedCondition.name,
  52174. properties: serializedCondition.properties
  52175. };
  52176. };
  52177. return Condition;
  52178. }());
  52179. BABYLON.Condition = Condition;
  52180. /**
  52181. * Defines specific conditional operators as extensions of Condition
  52182. */
  52183. var ValueCondition = /** @class */ (function (_super) {
  52184. __extends(ValueCondition, _super);
  52185. /**
  52186. * Creates a new ValueCondition
  52187. * @param actionManager manager for the action the condition applies to
  52188. * @param target for the action
  52189. * @param propertyPath path to specify the property of the target the conditional operator uses
  52190. * @param value the value compared by the conditional operator against the current value of the property
  52191. * @param operator the conditional operator, default ValueCondition.IsEqual
  52192. */
  52193. function ValueCondition(actionManager, target,
  52194. /** path to specify the property of the target the conditional operator uses */
  52195. propertyPath,
  52196. /** the value compared by the conditional operator against the current value of the property */
  52197. value,
  52198. /** the conditional operator, default ValueCondition.IsEqual */
  52199. operator) {
  52200. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52201. var _this = _super.call(this, actionManager) || this;
  52202. _this.propertyPath = propertyPath;
  52203. _this.value = value;
  52204. _this.operator = operator;
  52205. _this._target = target;
  52206. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52207. _this._property = _this._getProperty(_this.propertyPath);
  52208. return _this;
  52209. }
  52210. Object.defineProperty(ValueCondition, "IsEqual", {
  52211. /**
  52212. * returns the number for IsEqual
  52213. */
  52214. get: function () {
  52215. return ValueCondition._IsEqual;
  52216. },
  52217. enumerable: true,
  52218. configurable: true
  52219. });
  52220. Object.defineProperty(ValueCondition, "IsDifferent", {
  52221. /**
  52222. * Returns the number for IsDifferent
  52223. */
  52224. get: function () {
  52225. return ValueCondition._IsDifferent;
  52226. },
  52227. enumerable: true,
  52228. configurable: true
  52229. });
  52230. Object.defineProperty(ValueCondition, "IsGreater", {
  52231. /**
  52232. * Returns the number for IsGreater
  52233. */
  52234. get: function () {
  52235. return ValueCondition._IsGreater;
  52236. },
  52237. enumerable: true,
  52238. configurable: true
  52239. });
  52240. Object.defineProperty(ValueCondition, "IsLesser", {
  52241. /**
  52242. * Returns the number for IsLesser
  52243. */
  52244. get: function () {
  52245. return ValueCondition._IsLesser;
  52246. },
  52247. enumerable: true,
  52248. configurable: true
  52249. });
  52250. /**
  52251. * Compares the given value with the property value for the specified conditional operator
  52252. * @returns the result of the comparison
  52253. */
  52254. ValueCondition.prototype.isValid = function () {
  52255. switch (this.operator) {
  52256. case ValueCondition.IsGreater:
  52257. return this._effectiveTarget[this._property] > this.value;
  52258. case ValueCondition.IsLesser:
  52259. return this._effectiveTarget[this._property] < this.value;
  52260. case ValueCondition.IsEqual:
  52261. case ValueCondition.IsDifferent:
  52262. var check;
  52263. if (this.value.equals) {
  52264. check = this.value.equals(this._effectiveTarget[this._property]);
  52265. }
  52266. else {
  52267. check = this.value === this._effectiveTarget[this._property];
  52268. }
  52269. return this.operator === ValueCondition.IsEqual ? check : !check;
  52270. }
  52271. return false;
  52272. };
  52273. /**
  52274. * Serialize the ValueCondition into a JSON compatible object
  52275. * @returns serialization object
  52276. */
  52277. ValueCondition.prototype.serialize = function () {
  52278. return this._serialize({
  52279. name: "ValueCondition",
  52280. properties: [
  52281. BABYLON.Action._GetTargetProperty(this._target),
  52282. { name: "propertyPath", value: this.propertyPath },
  52283. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52284. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52285. ]
  52286. });
  52287. };
  52288. /**
  52289. * Gets the name of the conditional operator for the ValueCondition
  52290. * @param operator the conditional operator
  52291. * @returns the name
  52292. */
  52293. ValueCondition.GetOperatorName = function (operator) {
  52294. switch (operator) {
  52295. case ValueCondition._IsEqual: return "IsEqual";
  52296. case ValueCondition._IsDifferent: return "IsDifferent";
  52297. case ValueCondition._IsGreater: return "IsGreater";
  52298. case ValueCondition._IsLesser: return "IsLesser";
  52299. default: return "";
  52300. }
  52301. };
  52302. /**
  52303. * Internal only
  52304. * @hidden
  52305. */
  52306. ValueCondition._IsEqual = 0;
  52307. /**
  52308. * Internal only
  52309. * @hidden
  52310. */
  52311. ValueCondition._IsDifferent = 1;
  52312. /**
  52313. * Internal only
  52314. * @hidden
  52315. */
  52316. ValueCondition._IsGreater = 2;
  52317. /**
  52318. * Internal only
  52319. * @hidden
  52320. */
  52321. ValueCondition._IsLesser = 3;
  52322. return ValueCondition;
  52323. }(Condition));
  52324. BABYLON.ValueCondition = ValueCondition;
  52325. /**
  52326. * Defines a predicate condition as an extension of Condition
  52327. */
  52328. var PredicateCondition = /** @class */ (function (_super) {
  52329. __extends(PredicateCondition, _super);
  52330. /**
  52331. * Creates a new PredicateCondition
  52332. * @param actionManager manager for the action the condition applies to
  52333. * @param predicate defines the predicate function used to validate the condition
  52334. */
  52335. function PredicateCondition(actionManager,
  52336. /** defines the predicate function used to validate the condition */
  52337. predicate) {
  52338. var _this = _super.call(this, actionManager) || this;
  52339. _this.predicate = predicate;
  52340. return _this;
  52341. }
  52342. /**
  52343. * @returns the validity of the predicate condition
  52344. */
  52345. PredicateCondition.prototype.isValid = function () {
  52346. return this.predicate();
  52347. };
  52348. return PredicateCondition;
  52349. }(Condition));
  52350. BABYLON.PredicateCondition = PredicateCondition;
  52351. /**
  52352. * Defines a state condition as an extension of Condition
  52353. */
  52354. var StateCondition = /** @class */ (function (_super) {
  52355. __extends(StateCondition, _super);
  52356. /**
  52357. * Creates a new StateCondition
  52358. * @param actionManager manager for the action the condition applies to
  52359. * @param target of the condition
  52360. * @param value to compare with target state
  52361. */
  52362. function StateCondition(actionManager, target, value) {
  52363. var _this = _super.call(this, actionManager) || this;
  52364. _this.value = value;
  52365. _this._target = target;
  52366. return _this;
  52367. }
  52368. /**
  52369. * @returns the validity of the state
  52370. */
  52371. StateCondition.prototype.isValid = function () {
  52372. return this._target.state === this.value;
  52373. };
  52374. /**
  52375. * Serialize the StateCondition into a JSON compatible object
  52376. * @returns serialization object
  52377. */
  52378. StateCondition.prototype.serialize = function () {
  52379. return this._serialize({
  52380. name: "StateCondition",
  52381. properties: [
  52382. BABYLON.Action._GetTargetProperty(this._target),
  52383. { name: "value", value: this.value }
  52384. ]
  52385. });
  52386. };
  52387. return StateCondition;
  52388. }(Condition));
  52389. BABYLON.StateCondition = StateCondition;
  52390. })(BABYLON || (BABYLON = {}));
  52391. //# sourceMappingURL=babylon.condition.js.map
  52392. var BABYLON;
  52393. (function (BABYLON) {
  52394. /**
  52395. * The action to be carried out following a trigger
  52396. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52397. */
  52398. var Action = /** @class */ (function () {
  52399. /**
  52400. * Creates a new Action
  52401. * @param triggerOptions the trigger, with or without parameters, for the action
  52402. * @param condition an optional determinant of action
  52403. */
  52404. function Action(
  52405. /** the trigger, with or without parameters, for the action */
  52406. triggerOptions, condition) {
  52407. this.triggerOptions = triggerOptions;
  52408. /**
  52409. * An event triggered prior to action being executed.
  52410. */
  52411. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52412. if (triggerOptions.parameter) {
  52413. this.trigger = triggerOptions.trigger;
  52414. this._triggerParameter = triggerOptions.parameter;
  52415. }
  52416. else if (triggerOptions.trigger) {
  52417. this.trigger = triggerOptions.trigger;
  52418. }
  52419. else {
  52420. this.trigger = triggerOptions;
  52421. }
  52422. this._nextActiveAction = this;
  52423. this._condition = condition;
  52424. }
  52425. /**
  52426. * Internal only
  52427. * @hidden
  52428. */
  52429. Action.prototype._prepare = function () {
  52430. };
  52431. /**
  52432. * Gets the trigger parameters
  52433. * @returns the trigger parameters
  52434. */
  52435. Action.prototype.getTriggerParameter = function () {
  52436. return this._triggerParameter;
  52437. };
  52438. /**
  52439. * Internal only - executes current action event
  52440. * @hidden
  52441. */
  52442. Action.prototype._executeCurrent = function (evt) {
  52443. if (this._nextActiveAction._condition) {
  52444. var condition = this._nextActiveAction._condition;
  52445. var currentRenderId = this._actionManager.getScene().getRenderId();
  52446. // We cache the current evaluation for the current frame
  52447. if (condition._evaluationId === currentRenderId) {
  52448. if (!condition._currentResult) {
  52449. return;
  52450. }
  52451. }
  52452. else {
  52453. condition._evaluationId = currentRenderId;
  52454. if (!condition.isValid()) {
  52455. condition._currentResult = false;
  52456. return;
  52457. }
  52458. condition._currentResult = true;
  52459. }
  52460. }
  52461. this.onBeforeExecuteObservable.notifyObservers(this);
  52462. this._nextActiveAction.execute(evt);
  52463. this.skipToNextActiveAction();
  52464. };
  52465. /**
  52466. * Execute placeholder for child classes
  52467. * @param evt optional action event
  52468. */
  52469. Action.prototype.execute = function (evt) {
  52470. };
  52471. /**
  52472. * Skips to next active action
  52473. */
  52474. Action.prototype.skipToNextActiveAction = function () {
  52475. if (this._nextActiveAction._child) {
  52476. if (!this._nextActiveAction._child._actionManager) {
  52477. this._nextActiveAction._child._actionManager = this._actionManager;
  52478. }
  52479. this._nextActiveAction = this._nextActiveAction._child;
  52480. }
  52481. else {
  52482. this._nextActiveAction = this;
  52483. }
  52484. };
  52485. /**
  52486. * Adds action to chain of actions, may be a DoNothingAction
  52487. * @param action defines the next action to execute
  52488. * @returns The action passed in
  52489. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52490. */
  52491. Action.prototype.then = function (action) {
  52492. this._child = action;
  52493. action._actionManager = this._actionManager;
  52494. action._prepare();
  52495. return action;
  52496. };
  52497. /**
  52498. * Internal only
  52499. * @hidden
  52500. */
  52501. Action.prototype._getProperty = function (propertyPath) {
  52502. return this._actionManager._getProperty(propertyPath);
  52503. };
  52504. /**
  52505. * Internal only
  52506. * @hidden
  52507. */
  52508. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52509. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52510. };
  52511. /**
  52512. * Serialize placeholder for child classes
  52513. * @param parent of child
  52514. * @returns the serialized object
  52515. */
  52516. Action.prototype.serialize = function (parent) {
  52517. };
  52518. /**
  52519. * Internal only called by serialize
  52520. * @hidden
  52521. */
  52522. Action.prototype._serialize = function (serializedAction, parent) {
  52523. var serializationObject = {
  52524. type: 1,
  52525. children: [],
  52526. name: serializedAction.name,
  52527. properties: serializedAction.properties || []
  52528. };
  52529. // Serialize child
  52530. if (this._child) {
  52531. this._child.serialize(serializationObject);
  52532. }
  52533. // Check if "this" has a condition
  52534. if (this._condition) {
  52535. var serializedCondition = this._condition.serialize();
  52536. serializedCondition.children.push(serializationObject);
  52537. if (parent) {
  52538. parent.children.push(serializedCondition);
  52539. }
  52540. return serializedCondition;
  52541. }
  52542. if (parent) {
  52543. parent.children.push(serializationObject);
  52544. }
  52545. return serializationObject;
  52546. };
  52547. /**
  52548. * Internal only
  52549. * @hidden
  52550. */
  52551. Action._SerializeValueAsString = function (value) {
  52552. if (typeof value === "number") {
  52553. return value.toString();
  52554. }
  52555. if (typeof value === "boolean") {
  52556. return value ? "true" : "false";
  52557. }
  52558. if (value instanceof BABYLON.Vector2) {
  52559. return value.x + ", " + value.y;
  52560. }
  52561. if (value instanceof BABYLON.Vector3) {
  52562. return value.x + ", " + value.y + ", " + value.z;
  52563. }
  52564. if (value instanceof BABYLON.Color3) {
  52565. return value.r + ", " + value.g + ", " + value.b;
  52566. }
  52567. if (value instanceof BABYLON.Color4) {
  52568. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52569. }
  52570. return value; // string
  52571. };
  52572. /**
  52573. * Internal only
  52574. * @hidden
  52575. */
  52576. Action._GetTargetProperty = function (target) {
  52577. return {
  52578. name: "target",
  52579. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52580. : target instanceof BABYLON.Light ? "LightProperties"
  52581. : target instanceof BABYLON.Camera ? "CameraProperties"
  52582. : "SceneProperties",
  52583. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52584. };
  52585. };
  52586. return Action;
  52587. }());
  52588. BABYLON.Action = Action;
  52589. })(BABYLON || (BABYLON = {}));
  52590. //# sourceMappingURL=babylon.action.js.map
  52591. var BABYLON;
  52592. (function (BABYLON) {
  52593. /**
  52594. * ActionEvent is the event being sent when an action is triggered.
  52595. */
  52596. var ActionEvent = /** @class */ (function () {
  52597. /**
  52598. * Creates a new ActionEvent
  52599. * @param source The mesh or sprite that triggered the action
  52600. * @param pointerX The X mouse cursor position at the time of the event
  52601. * @param pointerY The Y mouse cursor position at the time of the event
  52602. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52603. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52604. * @param additionalData additional data for the event
  52605. */
  52606. function ActionEvent(
  52607. /** The mesh or sprite that triggered the action */
  52608. source,
  52609. /** The X mouse cursor position at the time of the event */
  52610. pointerX,
  52611. /** The Y mouse cursor position at the time of the event */
  52612. pointerY,
  52613. /** The mesh that is currently pointed at (can be null) */
  52614. meshUnderPointer,
  52615. /** the original (browser) event that triggered the ActionEvent */
  52616. sourceEvent,
  52617. /** additional data for the event */
  52618. additionalData) {
  52619. this.source = source;
  52620. this.pointerX = pointerX;
  52621. this.pointerY = pointerY;
  52622. this.meshUnderPointer = meshUnderPointer;
  52623. this.sourceEvent = sourceEvent;
  52624. this.additionalData = additionalData;
  52625. }
  52626. /**
  52627. * Helper function to auto-create an ActionEvent from a source mesh.
  52628. * @param source The source mesh that triggered the event
  52629. * @param evt The original (browser) event
  52630. * @param additionalData additional data for the event
  52631. * @returns the new ActionEvent
  52632. */
  52633. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52634. var scene = source.getScene();
  52635. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52636. };
  52637. /**
  52638. * Helper function to auto-create an ActionEvent from a source sprite
  52639. * @param source The source sprite that triggered the event
  52640. * @param scene Scene associated with the sprite
  52641. * @param evt The original (browser) event
  52642. * @param additionalData additional data for the event
  52643. * @returns the new ActionEvent
  52644. */
  52645. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52646. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52647. };
  52648. /**
  52649. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52650. * @param scene the scene where the event occurred
  52651. * @param evt The original (browser) event
  52652. * @returns the new ActionEvent
  52653. */
  52654. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52655. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52656. };
  52657. /**
  52658. * Helper function to auto-create an ActionEvent from a primitive
  52659. * @param prim defines the target primitive
  52660. * @param pointerPos defines the pointer position
  52661. * @param evt The original (browser) event
  52662. * @param additionalData additional data for the event
  52663. * @returns the new ActionEvent
  52664. */
  52665. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52666. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52667. };
  52668. return ActionEvent;
  52669. }());
  52670. BABYLON.ActionEvent = ActionEvent;
  52671. /**
  52672. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52673. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52674. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52675. */
  52676. var ActionManager = /** @class */ (function () {
  52677. /**
  52678. * Creates a new action manager
  52679. * @param scene defines the hosting scene
  52680. */
  52681. function ActionManager(scene) {
  52682. // Members
  52683. /** Gets the list of actions */
  52684. this.actions = new Array();
  52685. /** Gets the cursor to use when hovering items */
  52686. this.hoverCursor = '';
  52687. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52688. scene.actionManagers.push(this);
  52689. }
  52690. Object.defineProperty(ActionManager, "NothingTrigger", {
  52691. /**
  52692. * Nothing
  52693. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52694. */
  52695. get: function () {
  52696. return ActionManager._NothingTrigger;
  52697. },
  52698. enumerable: true,
  52699. configurable: true
  52700. });
  52701. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52702. /**
  52703. * On pick
  52704. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52705. */
  52706. get: function () {
  52707. return ActionManager._OnPickTrigger;
  52708. },
  52709. enumerable: true,
  52710. configurable: true
  52711. });
  52712. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52713. /**
  52714. * On left pick
  52715. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52716. */
  52717. get: function () {
  52718. return ActionManager._OnLeftPickTrigger;
  52719. },
  52720. enumerable: true,
  52721. configurable: true
  52722. });
  52723. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52724. /**
  52725. * On right pick
  52726. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52727. */
  52728. get: function () {
  52729. return ActionManager._OnRightPickTrigger;
  52730. },
  52731. enumerable: true,
  52732. configurable: true
  52733. });
  52734. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52735. /**
  52736. * On center pick
  52737. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52738. */
  52739. get: function () {
  52740. return ActionManager._OnCenterPickTrigger;
  52741. },
  52742. enumerable: true,
  52743. configurable: true
  52744. });
  52745. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52746. /**
  52747. * On pick down
  52748. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52749. */
  52750. get: function () {
  52751. return ActionManager._OnPickDownTrigger;
  52752. },
  52753. enumerable: true,
  52754. configurable: true
  52755. });
  52756. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52757. /**
  52758. * On double pick
  52759. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52760. */
  52761. get: function () {
  52762. return ActionManager._OnDoublePickTrigger;
  52763. },
  52764. enumerable: true,
  52765. configurable: true
  52766. });
  52767. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52768. /**
  52769. * On pick up
  52770. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52771. */
  52772. get: function () {
  52773. return ActionManager._OnPickUpTrigger;
  52774. },
  52775. enumerable: true,
  52776. configurable: true
  52777. });
  52778. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52779. /**
  52780. * On pick out.
  52781. * This trigger will only be raised if you also declared a OnPickDown
  52782. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52783. */
  52784. get: function () {
  52785. return ActionManager._OnPickOutTrigger;
  52786. },
  52787. enumerable: true,
  52788. configurable: true
  52789. });
  52790. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52791. /**
  52792. * On long press
  52793. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52794. */
  52795. get: function () {
  52796. return ActionManager._OnLongPressTrigger;
  52797. },
  52798. enumerable: true,
  52799. configurable: true
  52800. });
  52801. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52802. /**
  52803. * On pointer over
  52804. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52805. */
  52806. get: function () {
  52807. return ActionManager._OnPointerOverTrigger;
  52808. },
  52809. enumerable: true,
  52810. configurable: true
  52811. });
  52812. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52813. /**
  52814. * On pointer out
  52815. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52816. */
  52817. get: function () {
  52818. return ActionManager._OnPointerOutTrigger;
  52819. },
  52820. enumerable: true,
  52821. configurable: true
  52822. });
  52823. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52824. /**
  52825. * On every frame
  52826. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52827. */
  52828. get: function () {
  52829. return ActionManager._OnEveryFrameTrigger;
  52830. },
  52831. enumerable: true,
  52832. configurable: true
  52833. });
  52834. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52835. /**
  52836. * On intersection enter
  52837. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52838. */
  52839. get: function () {
  52840. return ActionManager._OnIntersectionEnterTrigger;
  52841. },
  52842. enumerable: true,
  52843. configurable: true
  52844. });
  52845. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52846. /**
  52847. * On intersection exit
  52848. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52849. */
  52850. get: function () {
  52851. return ActionManager._OnIntersectionExitTrigger;
  52852. },
  52853. enumerable: true,
  52854. configurable: true
  52855. });
  52856. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52857. /**
  52858. * On key down
  52859. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52860. */
  52861. get: function () {
  52862. return ActionManager._OnKeyDownTrigger;
  52863. },
  52864. enumerable: true,
  52865. configurable: true
  52866. });
  52867. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52868. /**
  52869. * On key up
  52870. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52871. */
  52872. get: function () {
  52873. return ActionManager._OnKeyUpTrigger;
  52874. },
  52875. enumerable: true,
  52876. configurable: true
  52877. });
  52878. // Methods
  52879. /**
  52880. * Releases all associated resources
  52881. */
  52882. ActionManager.prototype.dispose = function () {
  52883. var index = this._scene.actionManagers.indexOf(this);
  52884. for (var i = 0; i < this.actions.length; i++) {
  52885. var action = this.actions[i];
  52886. ActionManager.Triggers[action.trigger]--;
  52887. if (ActionManager.Triggers[action.trigger] === 0) {
  52888. delete ActionManager.Triggers[action.trigger];
  52889. }
  52890. }
  52891. if (index > -1) {
  52892. this._scene.actionManagers.splice(index, 1);
  52893. }
  52894. };
  52895. /**
  52896. * Gets hosting scene
  52897. * @returns the hosting scene
  52898. */
  52899. ActionManager.prototype.getScene = function () {
  52900. return this._scene;
  52901. };
  52902. /**
  52903. * Does this action manager handles actions of any of the given triggers
  52904. * @param triggers defines the triggers to be tested
  52905. * @return a boolean indicating whether one (or more) of the triggers is handled
  52906. */
  52907. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52908. for (var index = 0; index < this.actions.length; index++) {
  52909. var action = this.actions[index];
  52910. if (triggers.indexOf(action.trigger) > -1) {
  52911. return true;
  52912. }
  52913. }
  52914. return false;
  52915. };
  52916. /**
  52917. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52918. * speed.
  52919. * @param triggerA defines the trigger to be tested
  52920. * @param triggerB defines the trigger to be tested
  52921. * @return a boolean indicating whether one (or more) of the triggers is handled
  52922. */
  52923. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  52924. for (var index = 0; index < this.actions.length; index++) {
  52925. var action = this.actions[index];
  52926. if (triggerA == action.trigger || triggerB == action.trigger) {
  52927. return true;
  52928. }
  52929. }
  52930. return false;
  52931. };
  52932. /**
  52933. * Does this action manager handles actions of a given trigger
  52934. * @param trigger defines the trigger to be tested
  52935. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52936. * @return whether the trigger is handled
  52937. */
  52938. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52939. for (var index = 0; index < this.actions.length; index++) {
  52940. var action = this.actions[index];
  52941. if (action.trigger === trigger) {
  52942. if (parameterPredicate) {
  52943. if (parameterPredicate(action.getTriggerParameter())) {
  52944. return true;
  52945. }
  52946. }
  52947. else {
  52948. return true;
  52949. }
  52950. }
  52951. }
  52952. return false;
  52953. };
  52954. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52955. /**
  52956. * Does this action manager has pointer triggers
  52957. */
  52958. get: function () {
  52959. for (var index = 0; index < this.actions.length; index++) {
  52960. var action = this.actions[index];
  52961. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52962. return true;
  52963. }
  52964. }
  52965. return false;
  52966. },
  52967. enumerable: true,
  52968. configurable: true
  52969. });
  52970. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52971. /**
  52972. * Does this action manager has pick triggers
  52973. */
  52974. get: function () {
  52975. for (var index = 0; index < this.actions.length; index++) {
  52976. var action = this.actions[index];
  52977. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52978. return true;
  52979. }
  52980. }
  52981. return false;
  52982. },
  52983. enumerable: true,
  52984. configurable: true
  52985. });
  52986. Object.defineProperty(ActionManager, "HasTriggers", {
  52987. /**
  52988. * Does exist one action manager with at least one trigger
  52989. **/
  52990. get: function () {
  52991. for (var t in ActionManager.Triggers) {
  52992. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52993. return true;
  52994. }
  52995. }
  52996. return false;
  52997. },
  52998. enumerable: true,
  52999. configurable: true
  53000. });
  53001. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53002. /**
  53003. * Does exist one action manager with at least one pick trigger
  53004. **/
  53005. get: function () {
  53006. for (var t in ActionManager.Triggers) {
  53007. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53008. var t_int = parseInt(t);
  53009. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53010. return true;
  53011. }
  53012. }
  53013. }
  53014. return false;
  53015. },
  53016. enumerable: true,
  53017. configurable: true
  53018. });
  53019. /**
  53020. * Does exist one action manager that handles actions of a given trigger
  53021. * @param trigger defines the trigger to be tested
  53022. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53023. **/
  53024. ActionManager.HasSpecificTrigger = function (trigger) {
  53025. for (var t in ActionManager.Triggers) {
  53026. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53027. var t_int = parseInt(t);
  53028. if (t_int === trigger) {
  53029. return true;
  53030. }
  53031. }
  53032. }
  53033. return false;
  53034. };
  53035. /**
  53036. * Registers an action to this action manager
  53037. * @param action defines the action to be registered
  53038. * @return the action amended (prepared) after registration
  53039. */
  53040. ActionManager.prototype.registerAction = function (action) {
  53041. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53042. if (this.getScene().actionManager !== this) {
  53043. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53044. return null;
  53045. }
  53046. }
  53047. this.actions.push(action);
  53048. if (ActionManager.Triggers[action.trigger]) {
  53049. ActionManager.Triggers[action.trigger]++;
  53050. }
  53051. else {
  53052. ActionManager.Triggers[action.trigger] = 1;
  53053. }
  53054. action._actionManager = this;
  53055. action._prepare();
  53056. return action;
  53057. };
  53058. /**
  53059. * Unregisters an action to this action manager
  53060. * @param action defines the action to be unregistered
  53061. * @return a boolean indicating whether the action has been unregistered
  53062. */
  53063. ActionManager.prototype.unregisterAction = function (action) {
  53064. var index = this.actions.indexOf(action);
  53065. if (index !== -1) {
  53066. this.actions.splice(index, 1);
  53067. ActionManager.Triggers[action.trigger] -= 1;
  53068. if (ActionManager.Triggers[action.trigger] === 0) {
  53069. delete ActionManager.Triggers[action.trigger];
  53070. }
  53071. delete action._actionManager;
  53072. return true;
  53073. }
  53074. return false;
  53075. };
  53076. /**
  53077. * Process a specific trigger
  53078. * @param trigger defines the trigger to process
  53079. * @param evt defines the event details to be processed
  53080. */
  53081. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53082. for (var index = 0; index < this.actions.length; index++) {
  53083. var action = this.actions[index];
  53084. if (action.trigger === trigger) {
  53085. if (evt) {
  53086. if (trigger === ActionManager.OnKeyUpTrigger
  53087. || trigger === ActionManager.OnKeyDownTrigger) {
  53088. var parameter = action.getTriggerParameter();
  53089. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53090. if (!parameter.toLowerCase) {
  53091. continue;
  53092. }
  53093. var lowerCase = parameter.toLowerCase();
  53094. if (lowerCase !== evt.sourceEvent.key) {
  53095. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53096. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53097. if (actualkey !== lowerCase) {
  53098. continue;
  53099. }
  53100. }
  53101. }
  53102. }
  53103. }
  53104. action._executeCurrent(evt);
  53105. }
  53106. }
  53107. };
  53108. /** @hidden */
  53109. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53110. var properties = propertyPath.split(".");
  53111. for (var index = 0; index < properties.length - 1; index++) {
  53112. target = target[properties[index]];
  53113. }
  53114. return target;
  53115. };
  53116. /** @hidden */
  53117. ActionManager.prototype._getProperty = function (propertyPath) {
  53118. var properties = propertyPath.split(".");
  53119. return properties[properties.length - 1];
  53120. };
  53121. /**
  53122. * Serialize this manager to a JSON object
  53123. * @param name defines the property name to store this manager
  53124. * @returns a JSON representation of this manager
  53125. */
  53126. ActionManager.prototype.serialize = function (name) {
  53127. var root = {
  53128. children: new Array(),
  53129. name: name,
  53130. type: 3,
  53131. properties: new Array() // Empty for root but required
  53132. };
  53133. for (var i = 0; i < this.actions.length; i++) {
  53134. var triggerObject = {
  53135. type: 0,
  53136. children: new Array(),
  53137. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53138. properties: new Array()
  53139. };
  53140. var triggerOptions = this.actions[i].triggerOptions;
  53141. if (triggerOptions && typeof triggerOptions !== "number") {
  53142. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53143. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53144. }
  53145. else {
  53146. var parameter = {};
  53147. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53148. if (triggerOptions.parameter.mesh) {
  53149. parameter._meshId = triggerOptions.parameter.mesh.id;
  53150. }
  53151. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53152. }
  53153. }
  53154. // Serialize child action, recursively
  53155. this.actions[i].serialize(triggerObject);
  53156. // Add serialized trigger
  53157. root.children.push(triggerObject);
  53158. }
  53159. return root;
  53160. };
  53161. /**
  53162. * Creates a new ActionManager from a JSON data
  53163. * @param parsedActions defines the JSON data to read from
  53164. * @param object defines the hosting mesh
  53165. * @param scene defines the hosting scene
  53166. */
  53167. ActionManager.Parse = function (parsedActions, object, scene) {
  53168. var actionManager = new ActionManager(scene);
  53169. if (object === null)
  53170. scene.actionManager = actionManager;
  53171. else
  53172. object.actionManager = actionManager;
  53173. // instanciate a new object
  53174. var instanciate = function (name, params) {
  53175. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53176. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53177. newInstance.constructor.apply(newInstance, params);
  53178. return newInstance;
  53179. };
  53180. var parseParameter = function (name, value, target, propertyPath) {
  53181. if (propertyPath === null) {
  53182. // String, boolean or float
  53183. var floatValue = parseFloat(value);
  53184. if (value === "true" || value === "false")
  53185. return value === "true";
  53186. else
  53187. return isNaN(floatValue) ? value : floatValue;
  53188. }
  53189. var effectiveTarget = propertyPath.split(".");
  53190. var values = value.split(",");
  53191. // Get effective Target
  53192. for (var i = 0; i < effectiveTarget.length; i++) {
  53193. target = target[effectiveTarget[i]];
  53194. }
  53195. // Return appropriate value with its type
  53196. if (typeof (target) === "boolean")
  53197. return values[0] === "true";
  53198. if (typeof (target) === "string")
  53199. return values[0];
  53200. // Parameters with multiple values such as Vector3 etc.
  53201. var split = new Array();
  53202. for (var i = 0; i < values.length; i++)
  53203. split.push(parseFloat(values[i]));
  53204. if (target instanceof BABYLON.Vector3)
  53205. return BABYLON.Vector3.FromArray(split);
  53206. if (target instanceof BABYLON.Vector4)
  53207. return BABYLON.Vector4.FromArray(split);
  53208. if (target instanceof BABYLON.Color3)
  53209. return BABYLON.Color3.FromArray(split);
  53210. if (target instanceof BABYLON.Color4)
  53211. return BABYLON.Color4.FromArray(split);
  53212. return parseFloat(values[0]);
  53213. };
  53214. // traverse graph per trigger
  53215. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53216. if (combineArray === void 0) { combineArray = null; }
  53217. if (parsedAction.detached)
  53218. return;
  53219. var parameters = new Array();
  53220. var target = null;
  53221. var propertyPath = null;
  53222. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53223. // Parameters
  53224. if (parsedAction.type === 2)
  53225. parameters.push(actionManager);
  53226. else
  53227. parameters.push(trigger);
  53228. if (combine) {
  53229. var actions = new Array();
  53230. for (var j = 0; j < parsedAction.combine.length; j++) {
  53231. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53232. }
  53233. parameters.push(actions);
  53234. }
  53235. else {
  53236. for (var i = 0; i < parsedAction.properties.length; i++) {
  53237. var value = parsedAction.properties[i].value;
  53238. var name = parsedAction.properties[i].name;
  53239. var targetType = parsedAction.properties[i].targetType;
  53240. if (name === "target")
  53241. if (targetType !== null && targetType === "SceneProperties")
  53242. value = target = scene;
  53243. else
  53244. value = target = scene.getNodeByName(value);
  53245. else if (name === "parent")
  53246. value = scene.getNodeByName(value);
  53247. else if (name === "sound")
  53248. value = scene.getSoundByName(value);
  53249. else if (name !== "propertyPath") {
  53250. if (parsedAction.type === 2 && name === "operator")
  53251. value = BABYLON.ValueCondition[value];
  53252. else
  53253. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53254. }
  53255. else {
  53256. propertyPath = value;
  53257. }
  53258. parameters.push(value);
  53259. }
  53260. }
  53261. if (combineArray === null) {
  53262. parameters.push(condition);
  53263. }
  53264. else {
  53265. parameters.push(null);
  53266. }
  53267. // If interpolate value action
  53268. if (parsedAction.name === "InterpolateValueAction") {
  53269. var param = parameters[parameters.length - 2];
  53270. parameters[parameters.length - 1] = param;
  53271. parameters[parameters.length - 2] = condition;
  53272. }
  53273. // Action or condition(s) and not CombineAction
  53274. var newAction = instanciate(parsedAction.name, parameters);
  53275. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53276. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53277. if (action)
  53278. action.then(nothing);
  53279. else
  53280. actionManager.registerAction(nothing);
  53281. action = nothing;
  53282. }
  53283. if (combineArray === null) {
  53284. if (newAction instanceof BABYLON.Condition) {
  53285. condition = newAction;
  53286. newAction = action;
  53287. }
  53288. else {
  53289. condition = null;
  53290. if (action)
  53291. action.then(newAction);
  53292. else
  53293. actionManager.registerAction(newAction);
  53294. }
  53295. }
  53296. else {
  53297. combineArray.push(newAction);
  53298. }
  53299. for (var i = 0; i < parsedAction.children.length; i++)
  53300. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53301. };
  53302. // triggers
  53303. for (var i = 0; i < parsedActions.children.length; i++) {
  53304. var triggerParams;
  53305. var trigger = parsedActions.children[i];
  53306. if (trigger.properties.length > 0) {
  53307. var param = trigger.properties[0].value;
  53308. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53309. if (value._meshId) {
  53310. value.mesh = scene.getMeshByID(value._meshId);
  53311. }
  53312. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53313. }
  53314. else
  53315. triggerParams = ActionManager[trigger.name];
  53316. for (var j = 0; j < trigger.children.length; j++) {
  53317. if (!trigger.detached)
  53318. traverse(trigger.children[j], triggerParams, null, null);
  53319. }
  53320. }
  53321. };
  53322. /**
  53323. * Get a trigger name by index
  53324. * @param trigger defines the trigger index
  53325. * @returns a trigger name
  53326. */
  53327. ActionManager.GetTriggerName = function (trigger) {
  53328. switch (trigger) {
  53329. case 0: return "NothingTrigger";
  53330. case 1: return "OnPickTrigger";
  53331. case 2: return "OnLeftPickTrigger";
  53332. case 3: return "OnRightPickTrigger";
  53333. case 4: return "OnCenterPickTrigger";
  53334. case 5: return "OnPickDownTrigger";
  53335. case 6: return "OnPickUpTrigger";
  53336. case 7: return "OnLongPressTrigger";
  53337. case 8: return "OnPointerOverTrigger";
  53338. case 9: return "OnPointerOutTrigger";
  53339. case 10: return "OnEveryFrameTrigger";
  53340. case 11: return "OnIntersectionEnterTrigger";
  53341. case 12: return "OnIntersectionExitTrigger";
  53342. case 13: return "OnKeyDownTrigger";
  53343. case 14: return "OnKeyUpTrigger";
  53344. case 15: return "OnPickOutTrigger";
  53345. default: return "";
  53346. }
  53347. };
  53348. // Statics
  53349. ActionManager._NothingTrigger = 0;
  53350. ActionManager._OnPickTrigger = 1;
  53351. ActionManager._OnLeftPickTrigger = 2;
  53352. ActionManager._OnRightPickTrigger = 3;
  53353. ActionManager._OnCenterPickTrigger = 4;
  53354. ActionManager._OnPickDownTrigger = 5;
  53355. ActionManager._OnDoublePickTrigger = 6;
  53356. ActionManager._OnPickUpTrigger = 7;
  53357. ActionManager._OnLongPressTrigger = 8;
  53358. ActionManager._OnPointerOverTrigger = 9;
  53359. ActionManager._OnPointerOutTrigger = 10;
  53360. ActionManager._OnEveryFrameTrigger = 11;
  53361. ActionManager._OnIntersectionEnterTrigger = 12;
  53362. ActionManager._OnIntersectionExitTrigger = 13;
  53363. ActionManager._OnKeyDownTrigger = 14;
  53364. ActionManager._OnKeyUpTrigger = 15;
  53365. ActionManager._OnPickOutTrigger = 16;
  53366. /** Gets the list of active triggers */
  53367. ActionManager.Triggers = {};
  53368. return ActionManager;
  53369. }());
  53370. BABYLON.ActionManager = ActionManager;
  53371. })(BABYLON || (BABYLON = {}));
  53372. //# sourceMappingURL=babylon.actionManager.js.map
  53373. var BABYLON;
  53374. (function (BABYLON) {
  53375. var InterpolateValueAction = /** @class */ (function (_super) {
  53376. __extends(InterpolateValueAction, _super);
  53377. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53378. if (duration === void 0) { duration = 1000; }
  53379. var _this = _super.call(this, triggerOptions, condition) || this;
  53380. _this.propertyPath = propertyPath;
  53381. _this.value = value;
  53382. _this.duration = duration;
  53383. _this.stopOtherAnimations = stopOtherAnimations;
  53384. _this.onInterpolationDone = onInterpolationDone;
  53385. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53386. _this._target = _this._effectiveTarget = target;
  53387. return _this;
  53388. }
  53389. /** @hidden */
  53390. InterpolateValueAction.prototype._prepare = function () {
  53391. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53392. this._property = this._getProperty(this.propertyPath);
  53393. };
  53394. InterpolateValueAction.prototype.execute = function () {
  53395. var _this = this;
  53396. var scene = this._actionManager.getScene();
  53397. var keys = [
  53398. {
  53399. frame: 0,
  53400. value: this._effectiveTarget[this._property]
  53401. }, {
  53402. frame: 100,
  53403. value: this.value
  53404. }
  53405. ];
  53406. var dataType;
  53407. if (typeof this.value === "number") {
  53408. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53409. }
  53410. else if (this.value instanceof BABYLON.Color3) {
  53411. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53412. }
  53413. else if (this.value instanceof BABYLON.Vector3) {
  53414. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53415. }
  53416. else if (this.value instanceof BABYLON.Matrix) {
  53417. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53418. }
  53419. else if (this.value instanceof BABYLON.Quaternion) {
  53420. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53421. }
  53422. else {
  53423. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53424. return;
  53425. }
  53426. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53427. animation.setKeys(keys);
  53428. if (this.stopOtherAnimations) {
  53429. scene.stopAnimation(this._effectiveTarget);
  53430. }
  53431. var wrapper = function () {
  53432. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53433. if (_this.onInterpolationDone) {
  53434. _this.onInterpolationDone();
  53435. }
  53436. };
  53437. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53438. };
  53439. InterpolateValueAction.prototype.serialize = function (parent) {
  53440. return _super.prototype._serialize.call(this, {
  53441. name: "InterpolateValueAction",
  53442. properties: [
  53443. BABYLON.Action._GetTargetProperty(this._target),
  53444. { name: "propertyPath", value: this.propertyPath },
  53445. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53446. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53447. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53448. ]
  53449. }, parent);
  53450. };
  53451. return InterpolateValueAction;
  53452. }(BABYLON.Action));
  53453. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53454. })(BABYLON || (BABYLON = {}));
  53455. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53456. var BABYLON;
  53457. (function (BABYLON) {
  53458. var SwitchBooleanAction = /** @class */ (function (_super) {
  53459. __extends(SwitchBooleanAction, _super);
  53460. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53461. var _this = _super.call(this, triggerOptions, condition) || this;
  53462. _this.propertyPath = propertyPath;
  53463. _this._target = _this._effectiveTarget = target;
  53464. return _this;
  53465. }
  53466. /** @hidden */
  53467. SwitchBooleanAction.prototype._prepare = function () {
  53468. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53469. this._property = this._getProperty(this.propertyPath);
  53470. };
  53471. SwitchBooleanAction.prototype.execute = function () {
  53472. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53473. };
  53474. SwitchBooleanAction.prototype.serialize = function (parent) {
  53475. return _super.prototype._serialize.call(this, {
  53476. name: "SwitchBooleanAction",
  53477. properties: [
  53478. BABYLON.Action._GetTargetProperty(this._target),
  53479. { name: "propertyPath", value: this.propertyPath }
  53480. ]
  53481. }, parent);
  53482. };
  53483. return SwitchBooleanAction;
  53484. }(BABYLON.Action));
  53485. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53486. var SetStateAction = /** @class */ (function (_super) {
  53487. __extends(SetStateAction, _super);
  53488. function SetStateAction(triggerOptions, target, value, condition) {
  53489. var _this = _super.call(this, triggerOptions, condition) || this;
  53490. _this.value = value;
  53491. _this._target = target;
  53492. return _this;
  53493. }
  53494. SetStateAction.prototype.execute = function () {
  53495. this._target.state = this.value;
  53496. };
  53497. SetStateAction.prototype.serialize = function (parent) {
  53498. return _super.prototype._serialize.call(this, {
  53499. name: "SetStateAction",
  53500. properties: [
  53501. BABYLON.Action._GetTargetProperty(this._target),
  53502. { name: "value", value: this.value }
  53503. ]
  53504. }, parent);
  53505. };
  53506. return SetStateAction;
  53507. }(BABYLON.Action));
  53508. BABYLON.SetStateAction = SetStateAction;
  53509. var SetValueAction = /** @class */ (function (_super) {
  53510. __extends(SetValueAction, _super);
  53511. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53512. var _this = _super.call(this, triggerOptions, condition) || this;
  53513. _this.propertyPath = propertyPath;
  53514. _this.value = value;
  53515. _this._target = _this._effectiveTarget = target;
  53516. return _this;
  53517. }
  53518. /** @hidden */
  53519. SetValueAction.prototype._prepare = function () {
  53520. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53521. this._property = this._getProperty(this.propertyPath);
  53522. };
  53523. SetValueAction.prototype.execute = function () {
  53524. this._effectiveTarget[this._property] = this.value;
  53525. if (this._target.markAsDirty) {
  53526. this._target.markAsDirty(this._property);
  53527. }
  53528. };
  53529. SetValueAction.prototype.serialize = function (parent) {
  53530. return _super.prototype._serialize.call(this, {
  53531. name: "SetValueAction",
  53532. properties: [
  53533. BABYLON.Action._GetTargetProperty(this._target),
  53534. { name: "propertyPath", value: this.propertyPath },
  53535. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53536. ]
  53537. }, parent);
  53538. };
  53539. return SetValueAction;
  53540. }(BABYLON.Action));
  53541. BABYLON.SetValueAction = SetValueAction;
  53542. var IncrementValueAction = /** @class */ (function (_super) {
  53543. __extends(IncrementValueAction, _super);
  53544. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53545. var _this = _super.call(this, triggerOptions, condition) || this;
  53546. _this.propertyPath = propertyPath;
  53547. _this.value = value;
  53548. _this._target = _this._effectiveTarget = target;
  53549. return _this;
  53550. }
  53551. /** @hidden */
  53552. IncrementValueAction.prototype._prepare = function () {
  53553. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53554. this._property = this._getProperty(this.propertyPath);
  53555. if (typeof this._effectiveTarget[this._property] !== "number") {
  53556. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53557. }
  53558. };
  53559. IncrementValueAction.prototype.execute = function () {
  53560. this._effectiveTarget[this._property] += this.value;
  53561. if (this._target.markAsDirty) {
  53562. this._target.markAsDirty(this._property);
  53563. }
  53564. };
  53565. IncrementValueAction.prototype.serialize = function (parent) {
  53566. return _super.prototype._serialize.call(this, {
  53567. name: "IncrementValueAction",
  53568. properties: [
  53569. BABYLON.Action._GetTargetProperty(this._target),
  53570. { name: "propertyPath", value: this.propertyPath },
  53571. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53572. ]
  53573. }, parent);
  53574. };
  53575. return IncrementValueAction;
  53576. }(BABYLON.Action));
  53577. BABYLON.IncrementValueAction = IncrementValueAction;
  53578. var PlayAnimationAction = /** @class */ (function (_super) {
  53579. __extends(PlayAnimationAction, _super);
  53580. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53581. var _this = _super.call(this, triggerOptions, condition) || this;
  53582. _this.from = from;
  53583. _this.to = to;
  53584. _this.loop = loop;
  53585. _this._target = target;
  53586. return _this;
  53587. }
  53588. /** @hidden */
  53589. PlayAnimationAction.prototype._prepare = function () {
  53590. };
  53591. PlayAnimationAction.prototype.execute = function () {
  53592. var scene = this._actionManager.getScene();
  53593. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53594. };
  53595. PlayAnimationAction.prototype.serialize = function (parent) {
  53596. return _super.prototype._serialize.call(this, {
  53597. name: "PlayAnimationAction",
  53598. properties: [
  53599. BABYLON.Action._GetTargetProperty(this._target),
  53600. { name: "from", value: String(this.from) },
  53601. { name: "to", value: String(this.to) },
  53602. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53603. ]
  53604. }, parent);
  53605. };
  53606. return PlayAnimationAction;
  53607. }(BABYLON.Action));
  53608. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53609. var StopAnimationAction = /** @class */ (function (_super) {
  53610. __extends(StopAnimationAction, _super);
  53611. function StopAnimationAction(triggerOptions, target, condition) {
  53612. var _this = _super.call(this, triggerOptions, condition) || this;
  53613. _this._target = target;
  53614. return _this;
  53615. }
  53616. /** @hidden */
  53617. StopAnimationAction.prototype._prepare = function () {
  53618. };
  53619. StopAnimationAction.prototype.execute = function () {
  53620. var scene = this._actionManager.getScene();
  53621. scene.stopAnimation(this._target);
  53622. };
  53623. StopAnimationAction.prototype.serialize = function (parent) {
  53624. return _super.prototype._serialize.call(this, {
  53625. name: "StopAnimationAction",
  53626. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53627. }, parent);
  53628. };
  53629. return StopAnimationAction;
  53630. }(BABYLON.Action));
  53631. BABYLON.StopAnimationAction = StopAnimationAction;
  53632. var DoNothingAction = /** @class */ (function (_super) {
  53633. __extends(DoNothingAction, _super);
  53634. function DoNothingAction(triggerOptions, condition) {
  53635. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53636. return _super.call(this, triggerOptions, condition) || this;
  53637. }
  53638. DoNothingAction.prototype.execute = function () {
  53639. };
  53640. DoNothingAction.prototype.serialize = function (parent) {
  53641. return _super.prototype._serialize.call(this, {
  53642. name: "DoNothingAction",
  53643. properties: []
  53644. }, parent);
  53645. };
  53646. return DoNothingAction;
  53647. }(BABYLON.Action));
  53648. BABYLON.DoNothingAction = DoNothingAction;
  53649. var CombineAction = /** @class */ (function (_super) {
  53650. __extends(CombineAction, _super);
  53651. function CombineAction(triggerOptions, children, condition) {
  53652. var _this = _super.call(this, triggerOptions, condition) || this;
  53653. _this.children = children;
  53654. return _this;
  53655. }
  53656. /** @hidden */
  53657. CombineAction.prototype._prepare = function () {
  53658. for (var index = 0; index < this.children.length; index++) {
  53659. this.children[index]._actionManager = this._actionManager;
  53660. this.children[index]._prepare();
  53661. }
  53662. };
  53663. CombineAction.prototype.execute = function (evt) {
  53664. for (var index = 0; index < this.children.length; index++) {
  53665. this.children[index].execute(evt);
  53666. }
  53667. };
  53668. CombineAction.prototype.serialize = function (parent) {
  53669. var serializationObject = _super.prototype._serialize.call(this, {
  53670. name: "CombineAction",
  53671. properties: [],
  53672. combine: []
  53673. }, parent);
  53674. for (var i = 0; i < this.children.length; i++) {
  53675. serializationObject.combine.push(this.children[i].serialize(null));
  53676. }
  53677. return serializationObject;
  53678. };
  53679. return CombineAction;
  53680. }(BABYLON.Action));
  53681. BABYLON.CombineAction = CombineAction;
  53682. var ExecuteCodeAction = /** @class */ (function (_super) {
  53683. __extends(ExecuteCodeAction, _super);
  53684. function ExecuteCodeAction(triggerOptions, func, condition) {
  53685. var _this = _super.call(this, triggerOptions, condition) || this;
  53686. _this.func = func;
  53687. return _this;
  53688. }
  53689. ExecuteCodeAction.prototype.execute = function (evt) {
  53690. this.func(evt);
  53691. };
  53692. return ExecuteCodeAction;
  53693. }(BABYLON.Action));
  53694. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53695. var SetParentAction = /** @class */ (function (_super) {
  53696. __extends(SetParentAction, _super);
  53697. function SetParentAction(triggerOptions, target, parent, condition) {
  53698. var _this = _super.call(this, triggerOptions, condition) || this;
  53699. _this._target = target;
  53700. _this._parent = parent;
  53701. return _this;
  53702. }
  53703. /** @hidden */
  53704. SetParentAction.prototype._prepare = function () {
  53705. };
  53706. SetParentAction.prototype.execute = function () {
  53707. if (this._target.parent === this._parent) {
  53708. return;
  53709. }
  53710. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53711. invertParentWorldMatrix.invert();
  53712. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53713. this._target.parent = this._parent;
  53714. };
  53715. SetParentAction.prototype.serialize = function (parent) {
  53716. return _super.prototype._serialize.call(this, {
  53717. name: "SetParentAction",
  53718. properties: [
  53719. BABYLON.Action._GetTargetProperty(this._target),
  53720. BABYLON.Action._GetTargetProperty(this._parent),
  53721. ]
  53722. }, parent);
  53723. };
  53724. return SetParentAction;
  53725. }(BABYLON.Action));
  53726. BABYLON.SetParentAction = SetParentAction;
  53727. var PlaySoundAction = /** @class */ (function (_super) {
  53728. __extends(PlaySoundAction, _super);
  53729. function PlaySoundAction(triggerOptions, sound, condition) {
  53730. var _this = _super.call(this, triggerOptions, condition) || this;
  53731. _this._sound = sound;
  53732. return _this;
  53733. }
  53734. /** @hidden */
  53735. PlaySoundAction.prototype._prepare = function () {
  53736. };
  53737. PlaySoundAction.prototype.execute = function () {
  53738. if (this._sound !== undefined)
  53739. this._sound.play();
  53740. };
  53741. PlaySoundAction.prototype.serialize = function (parent) {
  53742. return _super.prototype._serialize.call(this, {
  53743. name: "PlaySoundAction",
  53744. properties: [{ name: "sound", value: this._sound.name }]
  53745. }, parent);
  53746. };
  53747. return PlaySoundAction;
  53748. }(BABYLON.Action));
  53749. BABYLON.PlaySoundAction = PlaySoundAction;
  53750. var StopSoundAction = /** @class */ (function (_super) {
  53751. __extends(StopSoundAction, _super);
  53752. function StopSoundAction(triggerOptions, sound, condition) {
  53753. var _this = _super.call(this, triggerOptions, condition) || this;
  53754. _this._sound = sound;
  53755. return _this;
  53756. }
  53757. /** @hidden */
  53758. StopSoundAction.prototype._prepare = function () {
  53759. };
  53760. StopSoundAction.prototype.execute = function () {
  53761. if (this._sound !== undefined)
  53762. this._sound.stop();
  53763. };
  53764. StopSoundAction.prototype.serialize = function (parent) {
  53765. return _super.prototype._serialize.call(this, {
  53766. name: "StopSoundAction",
  53767. properties: [{ name: "sound", value: this._sound.name }]
  53768. }, parent);
  53769. };
  53770. return StopSoundAction;
  53771. }(BABYLON.Action));
  53772. BABYLON.StopSoundAction = StopSoundAction;
  53773. })(BABYLON || (BABYLON = {}));
  53774. //# sourceMappingURL=babylon.directActions.js.map
  53775. var BABYLON;
  53776. (function (BABYLON) {
  53777. var SpriteManager = /** @class */ (function () {
  53778. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53779. if (epsilon === void 0) { epsilon = 0.01; }
  53780. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53781. this.name = name;
  53782. this.sprites = new Array();
  53783. this.renderingGroupId = 0;
  53784. this.layerMask = 0x0FFFFFFF;
  53785. this.fogEnabled = true;
  53786. this.isPickable = false;
  53787. /**
  53788. * An event triggered when the manager is disposed.
  53789. */
  53790. this.onDisposeObservable = new BABYLON.Observable();
  53791. this._vertexBuffers = {};
  53792. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53793. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53794. }
  53795. this._capacity = capacity;
  53796. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53797. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53798. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53799. if (cellSize.width && cellSize.height) {
  53800. this.cellWidth = cellSize.width;
  53801. this.cellHeight = cellSize.height;
  53802. }
  53803. else if (cellSize !== undefined) {
  53804. this.cellWidth = cellSize;
  53805. this.cellHeight = cellSize;
  53806. }
  53807. else {
  53808. return;
  53809. }
  53810. this._epsilon = epsilon;
  53811. this._scene = scene;
  53812. this._scene.spriteManagers.push(this);
  53813. var indices = [];
  53814. var index = 0;
  53815. for (var count = 0; count < capacity; count++) {
  53816. indices.push(index);
  53817. indices.push(index + 1);
  53818. indices.push(index + 2);
  53819. indices.push(index);
  53820. indices.push(index + 2);
  53821. indices.push(index + 3);
  53822. index += 4;
  53823. }
  53824. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53825. // VBO
  53826. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53827. this._vertexData = new Float32Array(capacity * 16 * 4);
  53828. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53829. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53830. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53831. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53832. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53833. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53834. this._vertexBuffers["options"] = options;
  53835. this._vertexBuffers["cellInfo"] = cellInfo;
  53836. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53837. // Effects
  53838. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53839. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53840. }
  53841. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53842. set: function (callback) {
  53843. if (this._onDisposeObserver) {
  53844. this.onDisposeObservable.remove(this._onDisposeObserver);
  53845. }
  53846. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53847. },
  53848. enumerable: true,
  53849. configurable: true
  53850. });
  53851. Object.defineProperty(SpriteManager.prototype, "texture", {
  53852. get: function () {
  53853. return this._spriteTexture;
  53854. },
  53855. set: function (value) {
  53856. this._spriteTexture = value;
  53857. },
  53858. enumerable: true,
  53859. configurable: true
  53860. });
  53861. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53862. var arrayOffset = index * 16;
  53863. if (offsetX === 0)
  53864. offsetX = this._epsilon;
  53865. else if (offsetX === 1)
  53866. offsetX = 1 - this._epsilon;
  53867. if (offsetY === 0)
  53868. offsetY = this._epsilon;
  53869. else if (offsetY === 1)
  53870. offsetY = 1 - this._epsilon;
  53871. this._vertexData[arrayOffset] = sprite.position.x;
  53872. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53873. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53874. this._vertexData[arrayOffset + 3] = sprite.angle;
  53875. this._vertexData[arrayOffset + 4] = sprite.width;
  53876. this._vertexData[arrayOffset + 5] = sprite.height;
  53877. this._vertexData[arrayOffset + 6] = offsetX;
  53878. this._vertexData[arrayOffset + 7] = offsetY;
  53879. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53880. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53881. var offset = (sprite.cellIndex / rowSize) >> 0;
  53882. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53883. this._vertexData[arrayOffset + 11] = offset;
  53884. // Color
  53885. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53886. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53887. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53888. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53889. };
  53890. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53891. var count = Math.min(this._capacity, this.sprites.length);
  53892. var min = BABYLON.Vector3.Zero();
  53893. var max = BABYLON.Vector3.Zero();
  53894. var distance = Number.MAX_VALUE;
  53895. var currentSprite = null;
  53896. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53897. var cameraView = camera.getViewMatrix();
  53898. for (var index = 0; index < count; index++) {
  53899. var sprite = this.sprites[index];
  53900. if (!sprite) {
  53901. continue;
  53902. }
  53903. if (predicate) {
  53904. if (!predicate(sprite)) {
  53905. continue;
  53906. }
  53907. }
  53908. else if (!sprite.isPickable) {
  53909. continue;
  53910. }
  53911. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53912. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53913. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53914. if (ray.intersectsBoxMinMax(min, max)) {
  53915. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53916. if (distance > currentDistance) {
  53917. distance = currentDistance;
  53918. currentSprite = sprite;
  53919. if (fastCheck) {
  53920. break;
  53921. }
  53922. }
  53923. }
  53924. }
  53925. if (currentSprite) {
  53926. var result = new BABYLON.PickingInfo();
  53927. result.hit = true;
  53928. result.pickedSprite = currentSprite;
  53929. result.distance = distance;
  53930. return result;
  53931. }
  53932. return null;
  53933. };
  53934. SpriteManager.prototype.render = function () {
  53935. // Check
  53936. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53937. return;
  53938. var engine = this._scene.getEngine();
  53939. var baseSize = this._spriteTexture.getBaseSize();
  53940. // Sprites
  53941. var deltaTime = engine.getDeltaTime();
  53942. var max = Math.min(this._capacity, this.sprites.length);
  53943. var rowSize = baseSize.width / this.cellWidth;
  53944. var offset = 0;
  53945. for (var index = 0; index < max; index++) {
  53946. var sprite = this.sprites[index];
  53947. if (!sprite || !sprite.isVisible) {
  53948. continue;
  53949. }
  53950. sprite._animate(deltaTime);
  53951. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53952. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53953. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53954. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53955. }
  53956. this._buffer.update(this._vertexData);
  53957. // Render
  53958. var effect = this._effectBase;
  53959. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53960. effect = this._effectFog;
  53961. }
  53962. engine.enableEffect(effect);
  53963. var viewMatrix = this._scene.getViewMatrix();
  53964. effect.setTexture("diffuseSampler", this._spriteTexture);
  53965. effect.setMatrix("view", viewMatrix);
  53966. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53967. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53968. // Fog
  53969. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53970. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53971. effect.setColor3("vFogColor", this._scene.fogColor);
  53972. }
  53973. // VBOs
  53974. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53975. // Draw order
  53976. engine.setDepthFunctionToLessOrEqual();
  53977. effect.setBool("alphaTest", true);
  53978. engine.setColorWrite(false);
  53979. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53980. engine.setColorWrite(true);
  53981. effect.setBool("alphaTest", false);
  53982. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53983. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53984. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53985. };
  53986. SpriteManager.prototype.dispose = function () {
  53987. if (this._buffer) {
  53988. this._buffer.dispose();
  53989. this._buffer = null;
  53990. }
  53991. if (this._indexBuffer) {
  53992. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53993. this._indexBuffer = null;
  53994. }
  53995. if (this._spriteTexture) {
  53996. this._spriteTexture.dispose();
  53997. this._spriteTexture = null;
  53998. }
  53999. // Remove from scene
  54000. var index = this._scene.spriteManagers.indexOf(this);
  54001. this._scene.spriteManagers.splice(index, 1);
  54002. // Callback
  54003. this.onDisposeObservable.notifyObservers(this);
  54004. this.onDisposeObservable.clear();
  54005. };
  54006. return SpriteManager;
  54007. }());
  54008. BABYLON.SpriteManager = SpriteManager;
  54009. })(BABYLON || (BABYLON = {}));
  54010. //# sourceMappingURL=babylon.spriteManager.js.map
  54011. var BABYLON;
  54012. (function (BABYLON) {
  54013. var Sprite = /** @class */ (function () {
  54014. function Sprite(name, manager) {
  54015. this.name = name;
  54016. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54017. this.width = 1.0;
  54018. this.height = 1.0;
  54019. this.angle = 0;
  54020. this.cellIndex = 0;
  54021. this.invertU = 0;
  54022. this.invertV = 0;
  54023. this.animations = new Array();
  54024. this.isPickable = false;
  54025. this._animationStarted = false;
  54026. this._loopAnimation = false;
  54027. this._fromIndex = 0;
  54028. this._toIndex = 0;
  54029. this._delay = 0;
  54030. this._direction = 1;
  54031. this._time = 0;
  54032. /**
  54033. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54034. */
  54035. this.isVisible = true;
  54036. this._manager = manager;
  54037. this._manager.sprites.push(this);
  54038. this.position = BABYLON.Vector3.Zero();
  54039. }
  54040. Object.defineProperty(Sprite.prototype, "size", {
  54041. get: function () {
  54042. return this.width;
  54043. },
  54044. set: function (value) {
  54045. this.width = value;
  54046. this.height = value;
  54047. },
  54048. enumerable: true,
  54049. configurable: true
  54050. });
  54051. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54052. this._fromIndex = from;
  54053. this._toIndex = to;
  54054. this._loopAnimation = loop;
  54055. this._delay = delay;
  54056. this._animationStarted = true;
  54057. this._direction = from < to ? 1 : -1;
  54058. this.cellIndex = from;
  54059. this._time = 0;
  54060. this._onAnimationEnd = onAnimationEnd;
  54061. };
  54062. Sprite.prototype.stopAnimation = function () {
  54063. this._animationStarted = false;
  54064. };
  54065. /** @hidden */
  54066. Sprite.prototype._animate = function (deltaTime) {
  54067. if (!this._animationStarted)
  54068. return;
  54069. this._time += deltaTime;
  54070. if (this._time > this._delay) {
  54071. this._time = this._time % this._delay;
  54072. this.cellIndex += this._direction;
  54073. if (this.cellIndex > this._toIndex) {
  54074. if (this._loopAnimation) {
  54075. this.cellIndex = this._fromIndex;
  54076. }
  54077. else {
  54078. this.cellIndex = this._toIndex;
  54079. this._animationStarted = false;
  54080. if (this._onAnimationEnd) {
  54081. this._onAnimationEnd();
  54082. }
  54083. if (this.disposeWhenFinishedAnimating) {
  54084. this.dispose();
  54085. }
  54086. }
  54087. }
  54088. }
  54089. };
  54090. Sprite.prototype.dispose = function () {
  54091. for (var i = 0; i < this._manager.sprites.length; i++) {
  54092. if (this._manager.sprites[i] == this) {
  54093. this._manager.sprites.splice(i, 1);
  54094. }
  54095. }
  54096. };
  54097. return Sprite;
  54098. }());
  54099. BABYLON.Sprite = Sprite;
  54100. })(BABYLON || (BABYLON = {}));
  54101. //# sourceMappingURL=babylon.sprite.js.map
  54102. var BABYLON;
  54103. (function (BABYLON) {
  54104. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54105. if (!BABYLON.PickingInfo) {
  54106. return null;
  54107. }
  54108. var pickingInfo = null;
  54109. if (!camera) {
  54110. if (!this.activeCamera) {
  54111. return null;
  54112. }
  54113. camera = this.activeCamera;
  54114. }
  54115. if (this.spriteManagers.length > 0) {
  54116. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  54117. var spriteManager = this.spriteManagers[spriteIndex];
  54118. if (!spriteManager.isPickable) {
  54119. continue;
  54120. }
  54121. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  54122. if (!result || !result.hit)
  54123. continue;
  54124. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  54125. continue;
  54126. pickingInfo = result;
  54127. if (fastCheck) {
  54128. break;
  54129. }
  54130. }
  54131. }
  54132. return pickingInfo || new BABYLON.PickingInfo();
  54133. };
  54134. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  54135. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  54136. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54137. };
  54138. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  54139. if (!this._tempSpritePickingRay) {
  54140. return null;
  54141. }
  54142. if (!camera) {
  54143. if (!this.activeCamera) {
  54144. return null;
  54145. }
  54146. camera = this.activeCamera;
  54147. }
  54148. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  54149. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54150. };
  54151. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  54152. if (this._pointerOverSprite === sprite) {
  54153. return;
  54154. }
  54155. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54156. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54157. }
  54158. this._pointerOverSprite = sprite;
  54159. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54160. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54161. }
  54162. };
  54163. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  54164. return this._pointerOverSprite;
  54165. };
  54166. /**
  54167. * Defines the sprite scene component responsible to manage sprites
  54168. * in a given scene.
  54169. */
  54170. var SpriteSceneComponent = /** @class */ (function () {
  54171. /**
  54172. * Creates a new instance of the component for the given scene
  54173. * @param scene Defines the scene to register the component in
  54174. */
  54175. function SpriteSceneComponent(scene) {
  54176. /**
  54177. * The component name helpfull to identify the component in the list of scene components.
  54178. */
  54179. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  54180. this.scene = scene;
  54181. this.scene.spriteManagers = new Array();
  54182. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  54183. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  54184. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  54185. this._spritePredicate = function (sprite) {
  54186. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  54187. };
  54188. }
  54189. /**
  54190. * Registers the component in a given scene
  54191. */
  54192. SpriteSceneComponent.prototype.register = function () {
  54193. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  54194. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  54195. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  54196. };
  54197. /**
  54198. * Rebuilds the elements related to this component in case of
  54199. * context lost for instance.
  54200. */
  54201. SpriteSceneComponent.prototype.rebuild = function () {
  54202. /** Nothing to do for sprites */
  54203. };
  54204. /**
  54205. * Disposes the component and the associated ressources.
  54206. */
  54207. SpriteSceneComponent.prototype.dispose = function () {
  54208. this.scene.onBeforeSpritesRenderingObservable.clear();
  54209. this.scene.onAfterSpritesRenderingObservable.clear();
  54210. var spriteManagers = this.scene.spriteManagers;
  54211. while (spriteManagers.length) {
  54212. spriteManagers[0].dispose();
  54213. }
  54214. };
  54215. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  54216. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  54217. if (result) {
  54218. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  54219. }
  54220. return result;
  54221. };
  54222. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  54223. var scene = this.scene;
  54224. if (isMeshPicked) {
  54225. scene.setPointerOverSprite(null);
  54226. }
  54227. else {
  54228. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  54229. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54230. scene.setPointerOverSprite(pickResult.pickedSprite);
  54231. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  54232. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  54233. }
  54234. else {
  54235. canvas.style.cursor = scene.hoverCursor;
  54236. }
  54237. }
  54238. else {
  54239. scene.setPointerOverSprite(null);
  54240. }
  54241. }
  54242. return pickResult;
  54243. };
  54244. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54245. var scene = this.scene;
  54246. scene._pickedDownSprite = null;
  54247. if (scene.spriteManagers.length > 0) {
  54248. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54249. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54250. if (pickResult.pickedSprite.actionManager) {
  54251. scene._pickedDownSprite = pickResult.pickedSprite;
  54252. switch (evt.button) {
  54253. case 0:
  54254. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54255. break;
  54256. case 1:
  54257. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54258. break;
  54259. case 2:
  54260. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54261. break;
  54262. }
  54263. if (pickResult.pickedSprite.actionManager) {
  54264. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54265. }
  54266. }
  54267. }
  54268. }
  54269. return pickResult;
  54270. };
  54271. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54272. var scene = this.scene;
  54273. if (scene.spriteManagers.length > 0) {
  54274. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54275. if (spritePickResult) {
  54276. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  54277. if (spritePickResult.pickedSprite.actionManager) {
  54278. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54279. if (spritePickResult.pickedSprite.actionManager) {
  54280. if (!this.scene._isPointerSwiping()) {
  54281. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54282. }
  54283. }
  54284. }
  54285. }
  54286. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54287. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54288. }
  54289. }
  54290. }
  54291. return pickResult;
  54292. };
  54293. return SpriteSceneComponent;
  54294. }());
  54295. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54296. })(BABYLON || (BABYLON = {}));
  54297. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54298. var BABYLON;
  54299. (function (BABYLON) {
  54300. var IntersectionInfo = /** @class */ (function () {
  54301. function IntersectionInfo(bu, bv, distance) {
  54302. this.bu = bu;
  54303. this.bv = bv;
  54304. this.distance = distance;
  54305. this.faceId = 0;
  54306. this.subMeshId = 0;
  54307. }
  54308. return IntersectionInfo;
  54309. }());
  54310. BABYLON.IntersectionInfo = IntersectionInfo;
  54311. /**
  54312. * Information about the result of picking within a scene
  54313. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54314. */
  54315. var PickingInfo = /** @class */ (function () {
  54316. function PickingInfo() {
  54317. /**
  54318. * If the pick collided with an object
  54319. */
  54320. this.hit = false;
  54321. /**
  54322. * Distance away where the pick collided
  54323. */
  54324. this.distance = 0;
  54325. /**
  54326. * The location of pick collision
  54327. */
  54328. this.pickedPoint = null;
  54329. /**
  54330. * The mesh corresponding the the pick collision
  54331. */
  54332. this.pickedMesh = null;
  54333. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54334. this.bu = 0;
  54335. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54336. this.bv = 0;
  54337. /** The id of the face on the mesh that was picked */
  54338. this.faceId = -1;
  54339. /** Id of the the submesh that was picked */
  54340. this.subMeshId = 0;
  54341. /** If a sprite was picked, this will be the sprite the pick collided with */
  54342. this.pickedSprite = null;
  54343. /**
  54344. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54345. */
  54346. this.originMesh = null;
  54347. /**
  54348. * The ray that was used to perform the picking.
  54349. */
  54350. this.ray = null;
  54351. }
  54352. /**
  54353. * Gets the normal correspodning to the face the pick collided with
  54354. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54355. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54356. * @returns The normal correspodning to the face the pick collided with
  54357. */
  54358. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54359. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54360. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54361. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54362. return null;
  54363. }
  54364. var indices = this.pickedMesh.getIndices();
  54365. if (!indices) {
  54366. return null;
  54367. }
  54368. var result;
  54369. if (useVerticesNormals) {
  54370. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54371. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54372. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54373. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54374. normal0 = normal0.scale(this.bu);
  54375. normal1 = normal1.scale(this.bv);
  54376. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54377. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54378. }
  54379. else {
  54380. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54381. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54382. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54383. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54384. var p1p2 = vertex1.subtract(vertex2);
  54385. var p3p2 = vertex3.subtract(vertex2);
  54386. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54387. }
  54388. if (useWorldCoordinates) {
  54389. var wm = this.pickedMesh.getWorldMatrix();
  54390. if (this.pickedMesh.nonUniformScaling) {
  54391. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54392. wm = BABYLON.Tmp.Matrix[0];
  54393. wm.setTranslationFromFloats(0, 0, 0);
  54394. wm.invert();
  54395. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54396. wm = BABYLON.Tmp.Matrix[1];
  54397. }
  54398. result = BABYLON.Vector3.TransformNormal(result, wm);
  54399. }
  54400. result.normalize();
  54401. return result;
  54402. };
  54403. /**
  54404. * Gets the texture coordinates of where the pick occured
  54405. * @returns the vector containing the coordnates of the texture
  54406. */
  54407. PickingInfo.prototype.getTextureCoordinates = function () {
  54408. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54409. return null;
  54410. }
  54411. var indices = this.pickedMesh.getIndices();
  54412. if (!indices) {
  54413. return null;
  54414. }
  54415. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54416. if (!uvs) {
  54417. return null;
  54418. }
  54419. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54420. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54421. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54422. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54423. uv1 = uv1.scale(this.bu);
  54424. uv2 = uv2.scale(this.bv);
  54425. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54426. };
  54427. return PickingInfo;
  54428. }());
  54429. BABYLON.PickingInfo = PickingInfo;
  54430. })(BABYLON || (BABYLON = {}));
  54431. //# sourceMappingURL=babylon.pickingInfo.js.map
  54432. var BABYLON;
  54433. (function (BABYLON) {
  54434. var Ray = /** @class */ (function () {
  54435. function Ray(origin, direction, length) {
  54436. if (length === void 0) { length = Number.MAX_VALUE; }
  54437. this.origin = origin;
  54438. this.direction = direction;
  54439. this.length = length;
  54440. }
  54441. // Methods
  54442. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54443. var d = 0.0;
  54444. var maxValue = Number.MAX_VALUE;
  54445. var inv;
  54446. var min;
  54447. var max;
  54448. var temp;
  54449. if (Math.abs(this.direction.x) < 0.0000001) {
  54450. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54451. return false;
  54452. }
  54453. }
  54454. else {
  54455. inv = 1.0 / this.direction.x;
  54456. min = (minimum.x - this.origin.x) * inv;
  54457. max = (maximum.x - this.origin.x) * inv;
  54458. if (max === -Infinity) {
  54459. max = Infinity;
  54460. }
  54461. if (min > max) {
  54462. temp = min;
  54463. min = max;
  54464. max = temp;
  54465. }
  54466. d = Math.max(min, d);
  54467. maxValue = Math.min(max, maxValue);
  54468. if (d > maxValue) {
  54469. return false;
  54470. }
  54471. }
  54472. if (Math.abs(this.direction.y) < 0.0000001) {
  54473. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54474. return false;
  54475. }
  54476. }
  54477. else {
  54478. inv = 1.0 / this.direction.y;
  54479. min = (minimum.y - this.origin.y) * inv;
  54480. max = (maximum.y - this.origin.y) * inv;
  54481. if (max === -Infinity) {
  54482. max = Infinity;
  54483. }
  54484. if (min > max) {
  54485. temp = min;
  54486. min = max;
  54487. max = temp;
  54488. }
  54489. d = Math.max(min, d);
  54490. maxValue = Math.min(max, maxValue);
  54491. if (d > maxValue) {
  54492. return false;
  54493. }
  54494. }
  54495. if (Math.abs(this.direction.z) < 0.0000001) {
  54496. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54497. return false;
  54498. }
  54499. }
  54500. else {
  54501. inv = 1.0 / this.direction.z;
  54502. min = (minimum.z - this.origin.z) * inv;
  54503. max = (maximum.z - this.origin.z) * inv;
  54504. if (max === -Infinity) {
  54505. max = Infinity;
  54506. }
  54507. if (min > max) {
  54508. temp = min;
  54509. min = max;
  54510. max = temp;
  54511. }
  54512. d = Math.max(min, d);
  54513. maxValue = Math.min(max, maxValue);
  54514. if (d > maxValue) {
  54515. return false;
  54516. }
  54517. }
  54518. return true;
  54519. };
  54520. Ray.prototype.intersectsBox = function (box) {
  54521. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54522. };
  54523. Ray.prototype.intersectsSphere = function (sphere) {
  54524. var x = sphere.center.x - this.origin.x;
  54525. var y = sphere.center.y - this.origin.y;
  54526. var z = sphere.center.z - this.origin.z;
  54527. var pyth = (x * x) + (y * y) + (z * z);
  54528. var rr = sphere.radius * sphere.radius;
  54529. if (pyth <= rr) {
  54530. return true;
  54531. }
  54532. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54533. if (dot < 0.0) {
  54534. return false;
  54535. }
  54536. var temp = pyth - (dot * dot);
  54537. return temp <= rr;
  54538. };
  54539. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54540. if (!this._edge1) {
  54541. this._edge1 = BABYLON.Vector3.Zero();
  54542. this._edge2 = BABYLON.Vector3.Zero();
  54543. this._pvec = BABYLON.Vector3.Zero();
  54544. this._tvec = BABYLON.Vector3.Zero();
  54545. this._qvec = BABYLON.Vector3.Zero();
  54546. }
  54547. vertex1.subtractToRef(vertex0, this._edge1);
  54548. vertex2.subtractToRef(vertex0, this._edge2);
  54549. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54550. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54551. if (det === 0) {
  54552. return null;
  54553. }
  54554. var invdet = 1 / det;
  54555. this.origin.subtractToRef(vertex0, this._tvec);
  54556. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54557. if (bu < 0 || bu > 1.0) {
  54558. return null;
  54559. }
  54560. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54561. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54562. if (bv < 0 || bu + bv > 1.0) {
  54563. return null;
  54564. }
  54565. //check if the distance is longer than the predefined length.
  54566. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54567. if (distance > this.length) {
  54568. return null;
  54569. }
  54570. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54571. };
  54572. Ray.prototype.intersectsPlane = function (plane) {
  54573. var distance;
  54574. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54575. if (Math.abs(result1) < 9.99999997475243E-07) {
  54576. return null;
  54577. }
  54578. else {
  54579. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54580. distance = (-plane.d - result2) / result1;
  54581. if (distance < 0.0) {
  54582. if (distance < -9.99999997475243E-07) {
  54583. return null;
  54584. }
  54585. else {
  54586. return 0;
  54587. }
  54588. }
  54589. return distance;
  54590. }
  54591. };
  54592. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54593. var tm = BABYLON.Tmp.Matrix[0];
  54594. mesh.getWorldMatrix().invertToRef(tm);
  54595. if (this._tmpRay) {
  54596. Ray.TransformToRef(this, tm, this._tmpRay);
  54597. }
  54598. else {
  54599. this._tmpRay = Ray.Transform(this, tm);
  54600. }
  54601. return mesh.intersects(this._tmpRay, fastCheck);
  54602. };
  54603. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54604. if (results) {
  54605. results.length = 0;
  54606. }
  54607. else {
  54608. results = [];
  54609. }
  54610. for (var i = 0; i < meshes.length; i++) {
  54611. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54612. if (pickInfo.hit) {
  54613. results.push(pickInfo);
  54614. }
  54615. }
  54616. results.sort(this._comparePickingInfo);
  54617. return results;
  54618. };
  54619. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54620. if (pickingInfoA.distance < pickingInfoB.distance) {
  54621. return -1;
  54622. }
  54623. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54624. return 1;
  54625. }
  54626. else {
  54627. return 0;
  54628. }
  54629. };
  54630. /**
  54631. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54632. * @param sega the first point of the segment to test the intersection against
  54633. * @param segb the second point of the segment to test the intersection against
  54634. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54635. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54636. */
  54637. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54638. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54639. var u = segb.subtract(sega);
  54640. var v = rsegb.subtract(this.origin);
  54641. var w = sega.subtract(this.origin);
  54642. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54643. var b = BABYLON.Vector3.Dot(u, v);
  54644. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54645. var d = BABYLON.Vector3.Dot(u, w);
  54646. var e = BABYLON.Vector3.Dot(v, w);
  54647. var D = a * c - b * b; // always >= 0
  54648. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54649. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54650. // compute the line parameters of the two closest points
  54651. if (D < Ray.smallnum) { // the lines are almost parallel
  54652. sN = 0.0; // force using point P0 on segment S1
  54653. sD = 1.0; // to prevent possible division by 0.0 later
  54654. tN = e;
  54655. tD = c;
  54656. }
  54657. else { // get the closest points on the infinite lines
  54658. sN = (b * e - c * d);
  54659. tN = (a * e - b * d);
  54660. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54661. sN = 0.0;
  54662. tN = e;
  54663. tD = c;
  54664. }
  54665. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54666. sN = sD;
  54667. tN = e + b;
  54668. tD = c;
  54669. }
  54670. }
  54671. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54672. tN = 0.0;
  54673. // recompute sc for this edge
  54674. if (-d < 0.0) {
  54675. sN = 0.0;
  54676. }
  54677. else if (-d > a)
  54678. sN = sD;
  54679. else {
  54680. sN = -d;
  54681. sD = a;
  54682. }
  54683. }
  54684. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54685. tN = tD;
  54686. // recompute sc for this edge
  54687. if ((-d + b) < 0.0) {
  54688. sN = 0;
  54689. }
  54690. else if ((-d + b) > a) {
  54691. sN = sD;
  54692. }
  54693. else {
  54694. sN = (-d + b);
  54695. sD = a;
  54696. }
  54697. }
  54698. // finally do the division to get sc and tc
  54699. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54700. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54701. // get the difference of the two closest points
  54702. var qtc = v.multiplyByFloats(tc, tc, tc);
  54703. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54704. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54705. if (isIntersected) {
  54706. return qtc.length();
  54707. }
  54708. return -1;
  54709. };
  54710. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54711. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54712. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54713. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54714. this.direction.normalize();
  54715. return this;
  54716. };
  54717. // Statics
  54718. Ray.Zero = function () {
  54719. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54720. };
  54721. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54722. var result = Ray.Zero();
  54723. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54724. };
  54725. /**
  54726. * 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
  54727. * transformed to the given world matrix.
  54728. * @param origin The origin point
  54729. * @param end The end point
  54730. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54731. */
  54732. Ray.CreateNewFromTo = function (origin, end, world) {
  54733. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54734. var direction = end.subtract(origin);
  54735. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54736. direction.normalize();
  54737. return Ray.Transform(new Ray(origin, direction, length), world);
  54738. };
  54739. Ray.Transform = function (ray, matrix) {
  54740. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54741. Ray.TransformToRef(ray, matrix, result);
  54742. return result;
  54743. };
  54744. Ray.TransformToRef = function (ray, matrix, result) {
  54745. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54746. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54747. result.length = ray.length;
  54748. var dir = result.direction;
  54749. var len = dir.length();
  54750. if (!(len === 0 || len === 1)) {
  54751. var num = 1.0 / len;
  54752. dir.x *= num;
  54753. dir.y *= num;
  54754. dir.z *= num;
  54755. result.length *= len;
  54756. }
  54757. };
  54758. Ray.smallnum = 0.00000001;
  54759. Ray.rayl = 10e8;
  54760. return Ray;
  54761. }());
  54762. BABYLON.Ray = Ray;
  54763. })(BABYLON || (BABYLON = {}));
  54764. //# sourceMappingURL=babylon.ray.js.map
  54765. var BABYLON;
  54766. (function (BABYLON) {
  54767. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54768. if (boxMin.x > sphereCenter.x + sphereRadius)
  54769. return false;
  54770. if (sphereCenter.x - sphereRadius > boxMax.x)
  54771. return false;
  54772. if (boxMin.y > sphereCenter.y + sphereRadius)
  54773. return false;
  54774. if (sphereCenter.y - sphereRadius > boxMax.y)
  54775. return false;
  54776. if (boxMin.z > sphereCenter.z + sphereRadius)
  54777. return false;
  54778. if (sphereCenter.z - sphereRadius > boxMax.z)
  54779. return false;
  54780. return true;
  54781. };
  54782. var getLowestRoot = (function () {
  54783. var result = { root: 0, found: false };
  54784. return function (a, b, c, maxR) {
  54785. result.root = 0;
  54786. result.found = false;
  54787. var determinant = b * b - 4.0 * a * c;
  54788. if (determinant < 0)
  54789. return result;
  54790. var sqrtD = Math.sqrt(determinant);
  54791. var r1 = (-b - sqrtD) / (2.0 * a);
  54792. var r2 = (-b + sqrtD) / (2.0 * a);
  54793. if (r1 > r2) {
  54794. var temp = r2;
  54795. r2 = r1;
  54796. r1 = temp;
  54797. }
  54798. if (r1 > 0 && r1 < maxR) {
  54799. result.root = r1;
  54800. result.found = true;
  54801. return result;
  54802. }
  54803. if (r2 > 0 && r2 < maxR) {
  54804. result.root = r2;
  54805. result.found = true;
  54806. return result;
  54807. }
  54808. return result;
  54809. };
  54810. })();
  54811. var Collider = /** @class */ (function () {
  54812. function Collider() {
  54813. this._collisionPoint = BABYLON.Vector3.Zero();
  54814. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54815. this._tempVector = BABYLON.Vector3.Zero();
  54816. this._tempVector2 = BABYLON.Vector3.Zero();
  54817. this._tempVector3 = BABYLON.Vector3.Zero();
  54818. this._tempVector4 = BABYLON.Vector3.Zero();
  54819. this._edge = BABYLON.Vector3.Zero();
  54820. this._baseToVertex = BABYLON.Vector3.Zero();
  54821. this._destinationPoint = BABYLON.Vector3.Zero();
  54822. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54823. this._displacementVector = BABYLON.Vector3.Zero();
  54824. /** @hidden */
  54825. this._radius = BABYLON.Vector3.One();
  54826. /** @hidden */
  54827. this._retry = 0;
  54828. /** @hidden */
  54829. this._basePointWorld = BABYLON.Vector3.Zero();
  54830. this._velocityWorld = BABYLON.Vector3.Zero();
  54831. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54832. this._collisionMask = -1;
  54833. }
  54834. Object.defineProperty(Collider.prototype, "collisionMask", {
  54835. get: function () {
  54836. return this._collisionMask;
  54837. },
  54838. set: function (mask) {
  54839. this._collisionMask = !isNaN(mask) ? mask : -1;
  54840. },
  54841. enumerable: true,
  54842. configurable: true
  54843. });
  54844. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54845. /**
  54846. * Gets the plane normal used to compute the sliding response (in local space)
  54847. */
  54848. get: function () {
  54849. return this._slidePlaneNormal;
  54850. },
  54851. enumerable: true,
  54852. configurable: true
  54853. });
  54854. // Methods
  54855. /** @hidden */
  54856. Collider.prototype._initialize = function (source, dir, e) {
  54857. this._velocity = dir;
  54858. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54859. this._basePoint = source;
  54860. source.multiplyToRef(this._radius, this._basePointWorld);
  54861. dir.multiplyToRef(this._radius, this._velocityWorld);
  54862. this._velocityWorldLength = this._velocityWorld.length();
  54863. this._epsilon = e;
  54864. this.collisionFound = false;
  54865. };
  54866. /** @hidden */
  54867. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54868. pa.subtractToRef(point, this._tempVector);
  54869. pb.subtractToRef(point, this._tempVector2);
  54870. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54871. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54872. if (d < 0)
  54873. return false;
  54874. pc.subtractToRef(point, this._tempVector3);
  54875. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54876. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54877. if (d < 0)
  54878. return false;
  54879. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54880. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54881. return d >= 0;
  54882. };
  54883. /** @hidden */
  54884. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54885. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54886. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54887. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54888. return false;
  54889. }
  54890. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54891. return false;
  54892. return true;
  54893. };
  54894. /** @hidden */
  54895. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54896. var t0;
  54897. var embeddedInPlane = false;
  54898. //defensive programming, actually not needed.
  54899. if (!trianglePlaneArray) {
  54900. trianglePlaneArray = [];
  54901. }
  54902. if (!trianglePlaneArray[faceIndex]) {
  54903. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54904. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54905. }
  54906. var trianglePlane = trianglePlaneArray[faceIndex];
  54907. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54908. return;
  54909. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54910. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54911. if (normalDotVelocity == 0) {
  54912. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54913. return;
  54914. embeddedInPlane = true;
  54915. t0 = 0;
  54916. }
  54917. else {
  54918. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54919. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54920. if (t0 > t1) {
  54921. var temp = t1;
  54922. t1 = t0;
  54923. t0 = temp;
  54924. }
  54925. if (t0 > 1.0 || t1 < 0.0)
  54926. return;
  54927. if (t0 < 0)
  54928. t0 = 0;
  54929. if (t0 > 1.0)
  54930. t0 = 1.0;
  54931. }
  54932. this._collisionPoint.copyFromFloats(0, 0, 0);
  54933. var found = false;
  54934. var t = 1.0;
  54935. if (!embeddedInPlane) {
  54936. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54937. this._velocity.scaleToRef(t0, this._tempVector);
  54938. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54939. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54940. found = true;
  54941. t = t0;
  54942. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54943. }
  54944. }
  54945. if (!found) {
  54946. var velocitySquaredLength = this._velocity.lengthSquared();
  54947. var a = velocitySquaredLength;
  54948. this._basePoint.subtractToRef(p1, this._tempVector);
  54949. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54950. var c = this._tempVector.lengthSquared() - 1.0;
  54951. var lowestRoot = getLowestRoot(a, b, c, t);
  54952. if (lowestRoot.found) {
  54953. t = lowestRoot.root;
  54954. found = true;
  54955. this._collisionPoint.copyFrom(p1);
  54956. }
  54957. this._basePoint.subtractToRef(p2, this._tempVector);
  54958. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54959. c = this._tempVector.lengthSquared() - 1.0;
  54960. lowestRoot = getLowestRoot(a, b, c, t);
  54961. if (lowestRoot.found) {
  54962. t = lowestRoot.root;
  54963. found = true;
  54964. this._collisionPoint.copyFrom(p2);
  54965. }
  54966. this._basePoint.subtractToRef(p3, this._tempVector);
  54967. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54968. c = this._tempVector.lengthSquared() - 1.0;
  54969. lowestRoot = getLowestRoot(a, b, c, t);
  54970. if (lowestRoot.found) {
  54971. t = lowestRoot.root;
  54972. found = true;
  54973. this._collisionPoint.copyFrom(p3);
  54974. }
  54975. p2.subtractToRef(p1, this._edge);
  54976. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54977. var edgeSquaredLength = this._edge.lengthSquared();
  54978. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54979. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54980. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54981. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54982. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54983. lowestRoot = getLowestRoot(a, b, c, t);
  54984. if (lowestRoot.found) {
  54985. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54986. if (f >= 0.0 && f <= 1.0) {
  54987. t = lowestRoot.root;
  54988. found = true;
  54989. this._edge.scaleInPlace(f);
  54990. p1.addToRef(this._edge, this._collisionPoint);
  54991. }
  54992. }
  54993. p3.subtractToRef(p2, this._edge);
  54994. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54995. edgeSquaredLength = this._edge.lengthSquared();
  54996. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54997. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54998. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54999. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55000. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55001. lowestRoot = getLowestRoot(a, b, c, t);
  55002. if (lowestRoot.found) {
  55003. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55004. if (f >= 0.0 && f <= 1.0) {
  55005. t = lowestRoot.root;
  55006. found = true;
  55007. this._edge.scaleInPlace(f);
  55008. p2.addToRef(this._edge, this._collisionPoint);
  55009. }
  55010. }
  55011. p1.subtractToRef(p3, this._edge);
  55012. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55013. edgeSquaredLength = this._edge.lengthSquared();
  55014. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55015. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55016. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55017. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55018. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55019. lowestRoot = getLowestRoot(a, b, c, t);
  55020. if (lowestRoot.found) {
  55021. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55022. if (f >= 0.0 && f <= 1.0) {
  55023. t = lowestRoot.root;
  55024. found = true;
  55025. this._edge.scaleInPlace(f);
  55026. p3.addToRef(this._edge, this._collisionPoint);
  55027. }
  55028. }
  55029. }
  55030. if (found) {
  55031. var distToCollision = t * this._velocity.length();
  55032. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55033. if (!this.intersectionPoint) {
  55034. this.intersectionPoint = this._collisionPoint.clone();
  55035. }
  55036. else {
  55037. this.intersectionPoint.copyFrom(this._collisionPoint);
  55038. }
  55039. this._nearestDistance = distToCollision;
  55040. this.collisionFound = true;
  55041. }
  55042. }
  55043. };
  55044. /** @hidden */
  55045. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55046. for (var i = indexStart; i < indexEnd; i += 3) {
  55047. var p1 = pts[indices[i] - decal];
  55048. var p2 = pts[indices[i + 1] - decal];
  55049. var p3 = pts[indices[i + 2] - decal];
  55050. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55051. }
  55052. };
  55053. /** @hidden */
  55054. Collider.prototype._getResponse = function (pos, vel) {
  55055. pos.addToRef(vel, this._destinationPoint);
  55056. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55057. this._basePoint.addToRef(vel, pos);
  55058. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55059. this._slidePlaneNormal.normalize();
  55060. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55061. pos.addInPlace(this._displacementVector);
  55062. this.intersectionPoint.addInPlace(this._displacementVector);
  55063. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55064. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55065. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55066. };
  55067. return Collider;
  55068. }());
  55069. BABYLON.Collider = Collider;
  55070. })(BABYLON || (BABYLON = {}));
  55071. //# sourceMappingURL=babylon.collider.js.map
  55072. var BABYLON;
  55073. (function (BABYLON) {
  55074. //WebWorker code will be inserted to this variable.
  55075. BABYLON.CollisionWorker = "";
  55076. /** Defines supported task for worker process */
  55077. var WorkerTaskType;
  55078. (function (WorkerTaskType) {
  55079. /** Initialization */
  55080. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55081. /** Update of geometry */
  55082. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55083. /** Evaluate collision */
  55084. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55085. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55086. /** Defines kind of replies returned by worker */
  55087. var WorkerReplyType;
  55088. (function (WorkerReplyType) {
  55089. /** Success */
  55090. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55091. /** Unkown error */
  55092. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55093. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55094. var CollisionCoordinatorWorker = /** @class */ (function () {
  55095. function CollisionCoordinatorWorker() {
  55096. var _this = this;
  55097. this._scaledPosition = BABYLON.Vector3.Zero();
  55098. this._scaledVelocity = BABYLON.Vector3.Zero();
  55099. this.onMeshUpdated = function (transformNode) {
  55100. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55101. };
  55102. this.onGeometryUpdated = function (geometry) {
  55103. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55104. };
  55105. this._afterRender = function () {
  55106. if (!_this._init)
  55107. return;
  55108. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55109. return;
  55110. }
  55111. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55112. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55113. if (_this._runningUpdated > 4) {
  55114. return;
  55115. }
  55116. ++_this._runningUpdated;
  55117. var payload = {
  55118. updatedMeshes: _this._addUpdateMeshesList,
  55119. updatedGeometries: _this._addUpdateGeometriesList,
  55120. removedGeometries: _this._toRemoveGeometryArray,
  55121. removedMeshes: _this._toRemoveMeshesArray
  55122. };
  55123. var message = {
  55124. payload: payload,
  55125. taskType: WorkerTaskType.UPDATE
  55126. };
  55127. var serializable = [];
  55128. for (var id in payload.updatedGeometries) {
  55129. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55130. //prepare transferables
  55131. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55132. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55133. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55134. }
  55135. }
  55136. _this._worker.postMessage(message, serializable);
  55137. _this._addUpdateMeshesList = {};
  55138. _this._addUpdateGeometriesList = {};
  55139. _this._toRemoveGeometryArray = [];
  55140. _this._toRemoveMeshesArray = [];
  55141. };
  55142. this._onMessageFromWorker = function (e) {
  55143. var returnData = e.data;
  55144. if (returnData.error != WorkerReplyType.SUCCESS) {
  55145. //TODO what errors can be returned from the worker?
  55146. BABYLON.Tools.Warn("error returned from worker!");
  55147. return;
  55148. }
  55149. switch (returnData.taskType) {
  55150. case WorkerTaskType.INIT:
  55151. _this._init = true;
  55152. //Update the worked with ALL of the scene's current state
  55153. _this._scene.meshes.forEach(function (mesh) {
  55154. _this.onMeshAdded(mesh);
  55155. });
  55156. _this._scene.getGeometries().forEach(function (geometry) {
  55157. _this.onGeometryAdded(geometry);
  55158. });
  55159. break;
  55160. case WorkerTaskType.UPDATE:
  55161. _this._runningUpdated--;
  55162. break;
  55163. case WorkerTaskType.COLLIDE:
  55164. var returnPayload = returnData.payload;
  55165. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55166. return;
  55167. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55168. if (callback) {
  55169. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55170. if (mesh) {
  55171. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55172. }
  55173. }
  55174. //cleanup
  55175. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55176. break;
  55177. }
  55178. };
  55179. this._collisionsCallbackArray = [];
  55180. this._init = false;
  55181. this._runningUpdated = 0;
  55182. this._addUpdateMeshesList = {};
  55183. this._addUpdateGeometriesList = {};
  55184. this._toRemoveGeometryArray = [];
  55185. this._toRemoveMeshesArray = [];
  55186. }
  55187. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55188. if (!this._init)
  55189. return;
  55190. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55191. return;
  55192. position.divideToRef(collider._radius, this._scaledPosition);
  55193. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55194. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55195. var payload = {
  55196. collider: {
  55197. position: this._scaledPosition.asArray(),
  55198. velocity: this._scaledVelocity.asArray(),
  55199. radius: collider._radius.asArray()
  55200. },
  55201. collisionId: collisionIndex,
  55202. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55203. maximumRetry: maximumRetry
  55204. };
  55205. var message = {
  55206. payload: payload,
  55207. taskType: WorkerTaskType.COLLIDE
  55208. };
  55209. this._worker.postMessage(message);
  55210. };
  55211. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55212. this._scene = scene;
  55213. this._scene.registerAfterRender(this._afterRender);
  55214. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55215. this._worker = new Worker(workerUrl);
  55216. this._worker.onmessage = this._onMessageFromWorker;
  55217. var message = {
  55218. payload: {},
  55219. taskType: WorkerTaskType.INIT
  55220. };
  55221. this._worker.postMessage(message);
  55222. };
  55223. CollisionCoordinatorWorker.prototype.destroy = function () {
  55224. this._scene.unregisterAfterRender(this._afterRender);
  55225. this._worker.terminate();
  55226. };
  55227. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55228. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55229. this.onMeshUpdated(mesh);
  55230. };
  55231. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55232. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55233. };
  55234. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55235. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55236. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55237. this.onGeometryUpdated(geometry);
  55238. };
  55239. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55240. this._toRemoveGeometryArray.push(geometry.id);
  55241. };
  55242. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55243. var submeshes = [];
  55244. if (mesh.subMeshes) {
  55245. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55246. var boundingInfo = sm.getBoundingInfo();
  55247. return {
  55248. position: idx,
  55249. verticesStart: sm.verticesStart,
  55250. verticesCount: sm.verticesCount,
  55251. indexStart: sm.indexStart,
  55252. indexCount: sm.indexCount,
  55253. hasMaterial: !!sm.getMaterial(),
  55254. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55255. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55256. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55257. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55258. };
  55259. });
  55260. }
  55261. var geometryId = null;
  55262. if (mesh instanceof BABYLON.Mesh) {
  55263. var geometry = mesh.geometry;
  55264. geometryId = geometry ? geometry.id : null;
  55265. }
  55266. else if (mesh instanceof BABYLON.InstancedMesh) {
  55267. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55268. geometryId = geometry ? geometry.id : null;
  55269. }
  55270. var boundingInfo = mesh.getBoundingInfo();
  55271. return {
  55272. uniqueId: mesh.uniqueId,
  55273. id: mesh.id,
  55274. name: mesh.name,
  55275. geometryId: geometryId,
  55276. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55277. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55278. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55279. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55280. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55281. subMeshes: submeshes,
  55282. checkCollisions: mesh.checkCollisions
  55283. };
  55284. };
  55285. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55286. return {
  55287. id: geometry.id,
  55288. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55289. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55290. indices: new Uint32Array(geometry.getIndices() || []),
  55291. };
  55292. };
  55293. return CollisionCoordinatorWorker;
  55294. }());
  55295. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55296. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55297. function CollisionCoordinatorLegacy() {
  55298. this._scaledPosition = BABYLON.Vector3.Zero();
  55299. this._scaledVelocity = BABYLON.Vector3.Zero();
  55300. this._finalPosition = BABYLON.Vector3.Zero();
  55301. }
  55302. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55303. position.divideToRef(collider._radius, this._scaledPosition);
  55304. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55305. collider.collidedMesh = null;
  55306. collider._retry = 0;
  55307. collider._initialVelocity = this._scaledVelocity;
  55308. collider._initialPosition = this._scaledPosition;
  55309. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55310. this._finalPosition.multiplyInPlace(collider._radius);
  55311. //run the callback
  55312. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55313. };
  55314. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55315. this._scene = scene;
  55316. };
  55317. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55318. //Legacy need no destruction method.
  55319. };
  55320. //No update in legacy mode
  55321. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55322. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55323. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55324. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55325. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55326. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55327. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55328. if (excludedMesh === void 0) { excludedMesh = null; }
  55329. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55330. if (collider._retry >= maximumRetry) {
  55331. finalPosition.copyFrom(position);
  55332. return;
  55333. }
  55334. // Check if this is a mesh else camera or -1
  55335. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55336. collider._initialize(position, velocity, closeDistance);
  55337. // Check all meshes
  55338. for (var index = 0; index < this._scene.meshes.length; index++) {
  55339. var mesh = this._scene.meshes[index];
  55340. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55341. mesh._checkCollision(collider);
  55342. }
  55343. }
  55344. if (!collider.collisionFound) {
  55345. position.addToRef(velocity, finalPosition);
  55346. return;
  55347. }
  55348. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55349. collider._getResponse(position, velocity);
  55350. }
  55351. if (velocity.length() <= closeDistance) {
  55352. finalPosition.copyFrom(position);
  55353. return;
  55354. }
  55355. collider._retry++;
  55356. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55357. };
  55358. return CollisionCoordinatorLegacy;
  55359. }());
  55360. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55361. })(BABYLON || (BABYLON = {}));
  55362. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55363. var BABYLON;
  55364. (function (BABYLON) {
  55365. /**
  55366. * A particle represents one of the element emitted by a particle system.
  55367. * This is mainly define by its coordinates, direction, velocity and age.
  55368. */
  55369. var Particle = /** @class */ (function () {
  55370. /**
  55371. * Creates a new instance Particle
  55372. * @param particleSystem the particle system the particle belongs to
  55373. */
  55374. function Particle(
  55375. /**
  55376. * The particle system the particle belongs to.
  55377. */
  55378. particleSystem) {
  55379. this.particleSystem = particleSystem;
  55380. /**
  55381. * The world position of the particle in the scene.
  55382. */
  55383. this.position = BABYLON.Vector3.Zero();
  55384. /**
  55385. * The world direction of the particle in the scene.
  55386. */
  55387. this.direction = BABYLON.Vector3.Zero();
  55388. /**
  55389. * The color of the particle.
  55390. */
  55391. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55392. /**
  55393. * The color change of the particle per step.
  55394. */
  55395. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55396. /**
  55397. * Defines how long will the life of the particle be.
  55398. */
  55399. this.lifeTime = 1.0;
  55400. /**
  55401. * The current age of the particle.
  55402. */
  55403. this.age = 0;
  55404. /**
  55405. * The current size of the particle.
  55406. */
  55407. this.size = 0;
  55408. /**
  55409. * The current scale of the particle.
  55410. */
  55411. this.scale = new BABYLON.Vector2(1, 1);
  55412. /**
  55413. * The current angle of the particle.
  55414. */
  55415. this.angle = 0;
  55416. /**
  55417. * Defines how fast is the angle changing.
  55418. */
  55419. this.angularSpeed = 0;
  55420. /**
  55421. * Defines the cell index used by the particle to be rendered from a sprite.
  55422. */
  55423. this.cellIndex = 0;
  55424. /** @hidden */
  55425. this._attachedSubEmitters = null;
  55426. /** @hidden */
  55427. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55428. /** @hidden */
  55429. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55430. /** @hidden */
  55431. this._currentSize1 = 0;
  55432. /** @hidden */
  55433. this._currentSize2 = 0;
  55434. /** @hidden */
  55435. this._currentAngularSpeed1 = 0;
  55436. /** @hidden */
  55437. this._currentAngularSpeed2 = 0;
  55438. /** @hidden */
  55439. this._currentVelocity1 = 0;
  55440. /** @hidden */
  55441. this._currentVelocity2 = 0;
  55442. /** @hidden */
  55443. this._currentLimitVelocity1 = 0;
  55444. /** @hidden */
  55445. this._currentLimitVelocity2 = 0;
  55446. /** @hidden */
  55447. this._currentDrag1 = 0;
  55448. /** @hidden */
  55449. this._currentDrag2 = 0;
  55450. this.id = Particle._Count++;
  55451. if (!this.particleSystem.isAnimationSheetEnabled) {
  55452. return;
  55453. }
  55454. this.updateCellInfoFromSystem();
  55455. }
  55456. Particle.prototype.updateCellInfoFromSystem = function () {
  55457. this.cellIndex = this.particleSystem.startSpriteCellID;
  55458. };
  55459. /**
  55460. * Defines how the sprite cell index is updated for the particle
  55461. */
  55462. Particle.prototype.updateCellIndex = function () {
  55463. var offsetAge = this.age;
  55464. if (this.particleSystem.spriteRandomStartCell) {
  55465. if (this._randomCellOffset === undefined) {
  55466. this._randomCellOffset = Math.random() * this.lifeTime;
  55467. }
  55468. offsetAge += this._randomCellOffset;
  55469. }
  55470. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55471. var ratio = BABYLON.Scalar.Clamp(((offsetAge * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55472. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55473. };
  55474. /** @hidden */
  55475. Particle.prototype._reset = function () {
  55476. this.age = 0;
  55477. this._currentColorGradient = null;
  55478. this._currentSizeGradient = null;
  55479. this._currentAngularSpeedGradient = null;
  55480. this._currentVelocityGradient = null;
  55481. this._currentLimitVelocityGradient = null;
  55482. this._currentDragGradient = null;
  55483. this.cellIndex = this.particleSystem.startSpriteCellID;
  55484. this._randomCellOffset = undefined;
  55485. };
  55486. /**
  55487. * Copy the properties of particle to another one.
  55488. * @param other the particle to copy the information to.
  55489. */
  55490. Particle.prototype.copyTo = function (other) {
  55491. other.position.copyFrom(this.position);
  55492. if (this._initialDirection) {
  55493. if (other._initialDirection) {
  55494. other._initialDirection.copyFrom(this._initialDirection);
  55495. }
  55496. else {
  55497. other._initialDirection = this._initialDirection.clone();
  55498. }
  55499. }
  55500. else {
  55501. other._initialDirection = null;
  55502. }
  55503. other.direction.copyFrom(this.direction);
  55504. other.color.copyFrom(this.color);
  55505. other.colorStep.copyFrom(this.colorStep);
  55506. other.lifeTime = this.lifeTime;
  55507. other.age = this.age;
  55508. other._randomCellOffset = undefined;
  55509. other.size = this.size;
  55510. other.scale.copyFrom(this.scale);
  55511. other.angle = this.angle;
  55512. other.angularSpeed = this.angularSpeed;
  55513. other.particleSystem = this.particleSystem;
  55514. other.cellIndex = this.cellIndex;
  55515. other.id = this.id;
  55516. other._attachedSubEmitters = this._attachedSubEmitters;
  55517. if (this._currentColorGradient) {
  55518. other._currentColorGradient = this._currentColorGradient;
  55519. other._currentColor1.copyFrom(this._currentColor1);
  55520. other._currentColor2.copyFrom(this._currentColor2);
  55521. }
  55522. if (this._currentSizeGradient) {
  55523. other._currentSizeGradient = this._currentSizeGradient;
  55524. other._currentSize1 = this._currentSize1;
  55525. other._currentSize2 = this._currentSize2;
  55526. }
  55527. if (this._currentAngularSpeedGradient) {
  55528. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55529. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55530. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55531. }
  55532. if (this._currentVelocityGradient) {
  55533. other._currentVelocityGradient = this._currentVelocityGradient;
  55534. other._currentVelocity1 = this._currentVelocity1;
  55535. other._currentVelocity2 = this._currentVelocity2;
  55536. }
  55537. if (this._currentLimitVelocityGradient) {
  55538. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55539. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55540. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55541. }
  55542. if (this._currentDragGradient) {
  55543. other._currentDragGradient = this._currentDragGradient;
  55544. other._currentDrag1 = this._currentDrag1;
  55545. other._currentDrag2 = this._currentDrag2;
  55546. }
  55547. if (this.particleSystem.isAnimationSheetEnabled) {
  55548. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55549. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55550. }
  55551. if (this.particleSystem.useRampGradients) {
  55552. other.remapData.copyFrom(this.remapData);
  55553. }
  55554. };
  55555. Particle._Count = 0;
  55556. return Particle;
  55557. }());
  55558. BABYLON.Particle = Particle;
  55559. })(BABYLON || (BABYLON = {}));
  55560. //# sourceMappingURL=babylon.particle.js.map
  55561. var BABYLON;
  55562. (function (BABYLON) {
  55563. /**
  55564. * This represents the base class for particle system in Babylon.
  55565. * 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.
  55566. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55567. * @example https://doc.babylonjs.com/babylon101/particles
  55568. */
  55569. var BaseParticleSystem = /** @class */ (function () {
  55570. /**
  55571. * Instantiates a particle system.
  55572. * 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.
  55573. * @param name The name of the particle system
  55574. */
  55575. function BaseParticleSystem(name) {
  55576. /**
  55577. * List of animations used by the particle system.
  55578. */
  55579. this.animations = [];
  55580. /**
  55581. * The rendering group used by the Particle system to chose when to render.
  55582. */
  55583. this.renderingGroupId = 0;
  55584. /**
  55585. * The emitter represents the Mesh or position we are attaching the particle system to.
  55586. */
  55587. this.emitter = null;
  55588. /**
  55589. * The maximum number of particles to emit per frame
  55590. */
  55591. this.emitRate = 10;
  55592. /**
  55593. * If you want to launch only a few particles at once, that can be done, as well.
  55594. */
  55595. this.manualEmitCount = -1;
  55596. /**
  55597. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55598. */
  55599. this.updateSpeed = 0.01;
  55600. /**
  55601. * The amount of time the particle system is running (depends of the overall update speed).
  55602. */
  55603. this.targetStopDuration = 0;
  55604. /**
  55605. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55606. */
  55607. this.disposeOnStop = false;
  55608. /**
  55609. * Minimum power of emitting particles.
  55610. */
  55611. this.minEmitPower = 1;
  55612. /**
  55613. * Maximum power of emitting particles.
  55614. */
  55615. this.maxEmitPower = 1;
  55616. /**
  55617. * Minimum life time of emitting particles.
  55618. */
  55619. this.minLifeTime = 1;
  55620. /**
  55621. * Maximum life time of emitting particles.
  55622. */
  55623. this.maxLifeTime = 1;
  55624. /**
  55625. * Minimum Size of emitting particles.
  55626. */
  55627. this.minSize = 1;
  55628. /**
  55629. * Maximum Size of emitting particles.
  55630. */
  55631. this.maxSize = 1;
  55632. /**
  55633. * Minimum scale of emitting particles on X axis.
  55634. */
  55635. this.minScaleX = 1;
  55636. /**
  55637. * Maximum scale of emitting particles on X axis.
  55638. */
  55639. this.maxScaleX = 1;
  55640. /**
  55641. * Minimum scale of emitting particles on Y axis.
  55642. */
  55643. this.minScaleY = 1;
  55644. /**
  55645. * Maximum scale of emitting particles on Y axis.
  55646. */
  55647. this.maxScaleY = 1;
  55648. /**
  55649. * Gets or sets the minimal initial rotation in radians.
  55650. */
  55651. this.minInitialRotation = 0;
  55652. /**
  55653. * Gets or sets the maximal initial rotation in radians.
  55654. */
  55655. this.maxInitialRotation = 0;
  55656. /**
  55657. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55658. */
  55659. this.minAngularSpeed = 0;
  55660. /**
  55661. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55662. */
  55663. this.maxAngularSpeed = 0;
  55664. /**
  55665. * The layer mask we are rendering the particles through.
  55666. */
  55667. this.layerMask = 0x0FFFFFFF;
  55668. /**
  55669. * This can help using your own shader to render the particle system.
  55670. * The according effect will be created
  55671. */
  55672. this.customShader = null;
  55673. /**
  55674. * By default particle system starts as soon as they are created. This prevents the
  55675. * automatic start to happen and let you decide when to start emitting particles.
  55676. */
  55677. this.preventAutoStart = false;
  55678. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55679. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55680. /**
  55681. * Callback triggered when the particle animation is ending.
  55682. */
  55683. this.onAnimationEnd = null;
  55684. /**
  55685. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55686. */
  55687. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55688. /**
  55689. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55690. * to override the particles.
  55691. */
  55692. this.forceDepthWrite = false;
  55693. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55694. this.preWarmCycles = 0;
  55695. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55696. this.preWarmStepOffset = 1;
  55697. /**
  55698. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55699. */
  55700. this.spriteCellChangeSpeed = 1;
  55701. /**
  55702. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55703. */
  55704. this.startSpriteCellID = 0;
  55705. /**
  55706. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55707. */
  55708. this.endSpriteCellID = 0;
  55709. /**
  55710. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55711. */
  55712. this.spriteCellWidth = 0;
  55713. /**
  55714. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55715. */
  55716. this.spriteCellHeight = 0;
  55717. /**
  55718. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55719. */
  55720. this.spriteRandomStartCell = false;
  55721. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55722. this.translationPivot = new BABYLON.Vector2(0, 0);
  55723. /**
  55724. * You can use gravity if you want to give an orientation to your particles.
  55725. */
  55726. this.gravity = BABYLON.Vector3.Zero();
  55727. this._colorGradients = null;
  55728. this._sizeGradients = null;
  55729. this._lifeTimeGradients = null;
  55730. this._angularSpeedGradients = null;
  55731. this._velocityGradients = null;
  55732. this._limitVelocityGradients = null;
  55733. this._dragGradients = null;
  55734. this._emitRateGradients = null;
  55735. this._startSizeGradients = null;
  55736. this._rampGradients = null;
  55737. this._colorRemapGradients = null;
  55738. this._alphaRemapGradients = null;
  55739. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55740. this.limitVelocityDamping = 0.4;
  55741. /**
  55742. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55743. */
  55744. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55745. /**
  55746. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55747. */
  55748. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55749. /**
  55750. * Color the particle will have at the end of its lifetime
  55751. */
  55752. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55753. /**
  55754. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55755. */
  55756. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55757. /**
  55758. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55759. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55760. */
  55761. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55762. this._isBillboardBased = true;
  55763. /**
  55764. * Local cache of defines for image processing.
  55765. */
  55766. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55767. this.id = name;
  55768. this.name = name;
  55769. }
  55770. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55771. /**
  55772. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55773. */
  55774. get: function () {
  55775. return this._isAnimationSheetEnabled;
  55776. },
  55777. set: function (value) {
  55778. if (this._isAnimationSheetEnabled == value) {
  55779. return;
  55780. }
  55781. this._isAnimationSheetEnabled = value;
  55782. this._reset();
  55783. },
  55784. enumerable: true,
  55785. configurable: true
  55786. });
  55787. /**
  55788. * Get hosting scene
  55789. * @returns the scene
  55790. */
  55791. BaseParticleSystem.prototype.getScene = function () {
  55792. return this._scene;
  55793. };
  55794. /**
  55795. * Gets the current list of drag gradients.
  55796. * You must use addDragGradient and removeDragGradient to udpate this list
  55797. * @returns the list of drag gradients
  55798. */
  55799. BaseParticleSystem.prototype.getDragGradients = function () {
  55800. return this._dragGradients;
  55801. };
  55802. /**
  55803. * Gets the current list of limit velocity gradients.
  55804. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55805. * @returns the list of limit velocity gradients
  55806. */
  55807. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55808. return this._limitVelocityGradients;
  55809. };
  55810. /**
  55811. * Gets the current list of color gradients.
  55812. * You must use addColorGradient and removeColorGradient to udpate this list
  55813. * @returns the list of color gradients
  55814. */
  55815. BaseParticleSystem.prototype.getColorGradients = function () {
  55816. return this._colorGradients;
  55817. };
  55818. /**
  55819. * Gets the current list of size gradients.
  55820. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55821. * @returns the list of size gradients
  55822. */
  55823. BaseParticleSystem.prototype.getSizeGradients = function () {
  55824. return this._sizeGradients;
  55825. };
  55826. /**
  55827. * Gets the current list of color remap gradients.
  55828. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  55829. * @returns the list of color remap gradients
  55830. */
  55831. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  55832. return this._colorRemapGradients;
  55833. };
  55834. /**
  55835. * Gets the current list of alpha remap gradients.
  55836. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  55837. * @returns the list of alpha remap gradients
  55838. */
  55839. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  55840. return this._alphaRemapGradients;
  55841. };
  55842. /**
  55843. * Gets the current list of life time gradients.
  55844. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55845. * @returns the list of life time gradients
  55846. */
  55847. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55848. return this._lifeTimeGradients;
  55849. };
  55850. /**
  55851. * Gets the current list of angular speed gradients.
  55852. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55853. * @returns the list of angular speed gradients
  55854. */
  55855. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55856. return this._angularSpeedGradients;
  55857. };
  55858. /**
  55859. * Gets the current list of velocity gradients.
  55860. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55861. * @returns the list of velocity gradients
  55862. */
  55863. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55864. return this._velocityGradients;
  55865. };
  55866. /**
  55867. * Gets the current list of start size gradients.
  55868. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55869. * @returns the list of start size gradients
  55870. */
  55871. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55872. return this._startSizeGradients;
  55873. };
  55874. /**
  55875. * Gets the current list of emit rate gradients.
  55876. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55877. * @returns the list of emit rate gradients
  55878. */
  55879. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55880. return this._emitRateGradients;
  55881. };
  55882. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55883. /**
  55884. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55885. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55886. */
  55887. get: function () {
  55888. if (this.particleEmitterType.direction1) {
  55889. return this.particleEmitterType.direction1;
  55890. }
  55891. return BABYLON.Vector3.Zero();
  55892. },
  55893. set: function (value) {
  55894. if (this.particleEmitterType.direction1) {
  55895. this.particleEmitterType.direction1 = value;
  55896. }
  55897. },
  55898. enumerable: true,
  55899. configurable: true
  55900. });
  55901. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55902. /**
  55903. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55904. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55905. */
  55906. get: function () {
  55907. if (this.particleEmitterType.direction2) {
  55908. return this.particleEmitterType.direction2;
  55909. }
  55910. return BABYLON.Vector3.Zero();
  55911. },
  55912. set: function (value) {
  55913. if (this.particleEmitterType.direction2) {
  55914. this.particleEmitterType.direction2 = value;
  55915. }
  55916. },
  55917. enumerable: true,
  55918. configurable: true
  55919. });
  55920. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55921. /**
  55922. * 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.
  55923. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55924. */
  55925. get: function () {
  55926. if (this.particleEmitterType.minEmitBox) {
  55927. return this.particleEmitterType.minEmitBox;
  55928. }
  55929. return BABYLON.Vector3.Zero();
  55930. },
  55931. set: function (value) {
  55932. if (this.particleEmitterType.minEmitBox) {
  55933. this.particleEmitterType.minEmitBox = value;
  55934. }
  55935. },
  55936. enumerable: true,
  55937. configurable: true
  55938. });
  55939. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55940. /**
  55941. * 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.
  55942. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55943. */
  55944. get: function () {
  55945. if (this.particleEmitterType.maxEmitBox) {
  55946. return this.particleEmitterType.maxEmitBox;
  55947. }
  55948. return BABYLON.Vector3.Zero();
  55949. },
  55950. set: function (value) {
  55951. if (this.particleEmitterType.maxEmitBox) {
  55952. this.particleEmitterType.maxEmitBox = value;
  55953. }
  55954. },
  55955. enumerable: true,
  55956. configurable: true
  55957. });
  55958. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55959. /**
  55960. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55961. */
  55962. get: function () {
  55963. return this._isBillboardBased;
  55964. },
  55965. set: function (value) {
  55966. if (this._isBillboardBased === value) {
  55967. return;
  55968. }
  55969. this._isBillboardBased = value;
  55970. this._reset();
  55971. },
  55972. enumerable: true,
  55973. configurable: true
  55974. });
  55975. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55976. /**
  55977. * Gets the image processing configuration used either in this material.
  55978. */
  55979. get: function () {
  55980. return this._imageProcessingConfiguration;
  55981. },
  55982. /**
  55983. * Sets the Default image processing configuration used either in the this material.
  55984. *
  55985. * If sets to null, the scene one is in use.
  55986. */
  55987. set: function (value) {
  55988. this._attachImageProcessingConfiguration(value);
  55989. },
  55990. enumerable: true,
  55991. configurable: true
  55992. });
  55993. /**
  55994. * Attaches a new image processing configuration to the Standard Material.
  55995. * @param configuration
  55996. */
  55997. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55998. if (configuration === this._imageProcessingConfiguration) {
  55999. return;
  56000. }
  56001. // Pick the scene configuration if needed.
  56002. if (!configuration) {
  56003. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  56004. }
  56005. else {
  56006. this._imageProcessingConfiguration = configuration;
  56007. }
  56008. };
  56009. /** @hidden */
  56010. BaseParticleSystem.prototype._reset = function () {
  56011. };
  56012. /** @hidden */
  56013. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  56014. if (!gradients) {
  56015. return this;
  56016. }
  56017. var index = 0;
  56018. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  56019. var valueGradient = gradients_1[_i];
  56020. if (valueGradient.gradient === gradient) {
  56021. gradients.splice(index, 1);
  56022. break;
  56023. }
  56024. index++;
  56025. }
  56026. if (texture) {
  56027. texture.dispose();
  56028. }
  56029. return this;
  56030. };
  56031. /**
  56032. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56033. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56034. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56035. * @returns the emitter
  56036. */
  56037. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56038. var particleEmitter = new BABYLON.PointParticleEmitter();
  56039. particleEmitter.direction1 = direction1;
  56040. particleEmitter.direction2 = direction2;
  56041. this.particleEmitterType = particleEmitter;
  56042. return particleEmitter;
  56043. };
  56044. /**
  56045. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56046. * @param radius The radius of the hemisphere to emit from
  56047. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56048. * @returns the emitter
  56049. */
  56050. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56051. if (radius === void 0) { radius = 1; }
  56052. if (radiusRange === void 0) { radiusRange = 1; }
  56053. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56054. this.particleEmitterType = particleEmitter;
  56055. return particleEmitter;
  56056. };
  56057. /**
  56058. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56059. * @param radius The radius of the sphere to emit from
  56060. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56061. * @returns the emitter
  56062. */
  56063. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56064. if (radius === void 0) { radius = 1; }
  56065. if (radiusRange === void 0) { radiusRange = 1; }
  56066. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56067. this.particleEmitterType = particleEmitter;
  56068. return particleEmitter;
  56069. };
  56070. /**
  56071. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56072. * @param radius The radius of the sphere to emit from
  56073. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56074. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56075. * @returns the emitter
  56076. */
  56077. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56078. if (radius === void 0) { radius = 1; }
  56079. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56080. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56081. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56082. this.particleEmitterType = particleEmitter;
  56083. return particleEmitter;
  56084. };
  56085. /**
  56086. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56087. * @param radius The radius of the emission cylinder
  56088. * @param height The height of the emission cylinder
  56089. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56090. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56091. * @returns the emitter
  56092. */
  56093. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56094. if (radius === void 0) { radius = 1; }
  56095. if (height === void 0) { height = 1; }
  56096. if (radiusRange === void 0) { radiusRange = 1; }
  56097. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56098. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56099. this.particleEmitterType = particleEmitter;
  56100. return particleEmitter;
  56101. };
  56102. /**
  56103. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  56104. * @param radius The radius of the cylinder to emit from
  56105. * @param height The height of the emission cylinder
  56106. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56107. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  56108. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  56109. * @returns the emitter
  56110. */
  56111. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  56112. if (radius === void 0) { radius = 1; }
  56113. if (height === void 0) { height = 1; }
  56114. if (radiusRange === void 0) { radiusRange = 1; }
  56115. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56116. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56117. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  56118. this.particleEmitterType = particleEmitter;
  56119. return particleEmitter;
  56120. };
  56121. /**
  56122. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56123. * @param radius The radius of the cone to emit from
  56124. * @param angle The base angle of the cone
  56125. * @returns the emitter
  56126. */
  56127. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56128. if (radius === void 0) { radius = 1; }
  56129. if (angle === void 0) { angle = Math.PI / 4; }
  56130. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56131. this.particleEmitterType = particleEmitter;
  56132. return particleEmitter;
  56133. };
  56134. /**
  56135. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56136. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56137. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56138. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56139. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56140. * @returns the emitter
  56141. */
  56142. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56143. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56144. this.particleEmitterType = particleEmitter;
  56145. this.direction1 = direction1;
  56146. this.direction2 = direction2;
  56147. this.minEmitBox = minEmitBox;
  56148. this.maxEmitBox = maxEmitBox;
  56149. return particleEmitter;
  56150. };
  56151. /**
  56152. * Source color is added to the destination color without alpha affecting the result
  56153. */
  56154. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56155. /**
  56156. * Blend current color and particle color using particle’s alpha
  56157. */
  56158. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56159. /**
  56160. * Add current color and particle color multiplied by particle’s alpha
  56161. */
  56162. BaseParticleSystem.BLENDMODE_ADD = 2;
  56163. /**
  56164. * Multiply current color with particle color
  56165. */
  56166. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56167. /**
  56168. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  56169. */
  56170. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  56171. return BaseParticleSystem;
  56172. }());
  56173. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56174. })(BABYLON || (BABYLON = {}));
  56175. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56176. var BABYLON;
  56177. (function (BABYLON) {
  56178. /**
  56179. * This represents a particle system in Babylon.
  56180. * 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.
  56181. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56182. * @example https://doc.babylonjs.com/babylon101/particles
  56183. */
  56184. var ParticleSystem = /** @class */ (function (_super) {
  56185. __extends(ParticleSystem, _super);
  56186. /**
  56187. * Instantiates a particle system.
  56188. * 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.
  56189. * @param name The name of the particle system
  56190. * @param capacity The max number of particles alive at the same time
  56191. * @param scene The scene the particle system belongs to
  56192. * @param customEffect a custom effect used to change the way particles are rendered by default
  56193. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56194. * @param epsilon Offset used to render the particles
  56195. */
  56196. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56197. if (customEffect === void 0) { customEffect = null; }
  56198. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56199. if (epsilon === void 0) { epsilon = 0.01; }
  56200. var _this = _super.call(this, name) || this;
  56201. /**
  56202. * @hidden
  56203. */
  56204. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  56205. /**
  56206. * An event triggered when the system is disposed
  56207. */
  56208. _this.onDisposeObservable = new BABYLON.Observable();
  56209. _this._particles = new Array();
  56210. _this._stockParticles = new Array();
  56211. _this._newPartsExcess = 0;
  56212. _this._vertexBuffers = {};
  56213. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56214. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56215. _this._scaledDirection = BABYLON.Vector3.Zero();
  56216. _this._scaledGravity = BABYLON.Vector3.Zero();
  56217. _this._currentRenderId = -1;
  56218. _this._useInstancing = false;
  56219. _this._started = false;
  56220. _this._stopped = false;
  56221. _this._actualFrame = 0;
  56222. /** @hidden */
  56223. _this._currentEmitRate1 = 0;
  56224. /** @hidden */
  56225. _this._currentEmitRate2 = 0;
  56226. /** @hidden */
  56227. _this._currentStartSize1 = 0;
  56228. /** @hidden */
  56229. _this._currentStartSize2 = 0;
  56230. _this._rawTextureWidth = 256;
  56231. _this._useRampGradients = false;
  56232. /**
  56233. * @hidden
  56234. * If the particle systems emitter should be disposed when the particle system is disposed
  56235. */
  56236. _this._disposeEmitterOnDispose = false;
  56237. // start of sub system methods
  56238. /**
  56239. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56240. * Its lifetime will start back at 0.
  56241. */
  56242. _this.recycleParticle = function (particle) {
  56243. // move particle from activeParticle list to stock particles
  56244. var lastParticle = _this._particles.pop();
  56245. if (lastParticle !== particle) {
  56246. lastParticle.copyTo(particle);
  56247. }
  56248. _this._stockParticles.push(lastParticle);
  56249. };
  56250. _this._createParticle = function () {
  56251. var particle;
  56252. if (_this._stockParticles.length !== 0) {
  56253. particle = _this._stockParticles.pop();
  56254. particle._reset();
  56255. }
  56256. else {
  56257. particle = new BABYLON.Particle(_this);
  56258. }
  56259. // Attach emitters
  56260. if (_this._subEmitters && _this._subEmitters.length > 0) {
  56261. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  56262. particle._attachedSubEmitters = [];
  56263. subEmitters.forEach(function (subEmitter) {
  56264. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  56265. var newEmitter = subEmitter.clone();
  56266. particle._attachedSubEmitters.push(newEmitter);
  56267. newEmitter.particleSystem.start();
  56268. }
  56269. });
  56270. }
  56271. return particle;
  56272. };
  56273. _this._emitFromParticle = function (particle) {
  56274. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  56275. return;
  56276. }
  56277. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  56278. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  56279. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  56280. var subSystem = subEmitter.clone();
  56281. ParticleSystem._InheritParticleInfoToSubEmitter(subSystem, particle);
  56282. subSystem.particleSystem._rootParticleSystem = _this;
  56283. _this.activeSubSystems.push(subSystem.particleSystem);
  56284. subSystem.particleSystem.start();
  56285. }
  56286. });
  56287. };
  56288. _this._capacity = capacity;
  56289. _this._epsilon = epsilon;
  56290. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56291. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56292. // Setup the default processing configuration to the scene.
  56293. _this._attachImageProcessingConfiguration(null);
  56294. _this._customEffect = customEffect;
  56295. _this._scene.particleSystems.push(_this);
  56296. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56297. _this._createIndexBuffer();
  56298. _this._createVertexBuffers();
  56299. // Default emitter type
  56300. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56301. _this.updateFunction = function (particles) {
  56302. var noiseTextureData = null;
  56303. var noiseTextureSize = null;
  56304. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56305. noiseTextureData = (_this.noiseTexture.readPixels());
  56306. noiseTextureSize = _this.noiseTexture.getSize();
  56307. }
  56308. var _loop_1 = function () {
  56309. particle = particles[index];
  56310. particle.age += _this._scaledUpdateSpeed;
  56311. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56312. _this._emitFromParticle(particle);
  56313. if (particle._attachedSubEmitters) {
  56314. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56315. subEmitter.particleSystem.disposeOnStop = true;
  56316. subEmitter.particleSystem.stop();
  56317. });
  56318. particle._attachedSubEmitters = null;
  56319. }
  56320. _this.recycleParticle(particle);
  56321. index--;
  56322. return "continue";
  56323. }
  56324. else {
  56325. var ratio = particle.age / particle.lifeTime;
  56326. // Color
  56327. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56328. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56329. if (currentGradient !== particle._currentColorGradient) {
  56330. particle._currentColor1.copyFrom(particle._currentColor2);
  56331. nextGradient.getColorToRef(particle._currentColor2);
  56332. particle._currentColorGradient = currentGradient;
  56333. }
  56334. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56335. });
  56336. }
  56337. else {
  56338. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56339. particle.color.addInPlace(_this._scaledColorStep);
  56340. if (particle.color.a < 0) {
  56341. particle.color.a = 0;
  56342. }
  56343. }
  56344. // Angular speed
  56345. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56346. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56347. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56348. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56349. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56350. particle._currentAngularSpeedGradient = currentGradient;
  56351. }
  56352. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56353. });
  56354. }
  56355. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56356. // Direction
  56357. var directionScale_1 = _this._scaledUpdateSpeed;
  56358. /// Velocity
  56359. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56360. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56361. if (currentGradient !== particle._currentVelocityGradient) {
  56362. particle._currentVelocity1 = particle._currentVelocity2;
  56363. particle._currentVelocity2 = nextGradient.getFactor();
  56364. particle._currentVelocityGradient = currentGradient;
  56365. }
  56366. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56367. });
  56368. }
  56369. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56370. /// Limit velocity
  56371. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56372. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56373. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56374. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56375. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56376. particle._currentLimitVelocityGradient = currentGradient;
  56377. }
  56378. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56379. var currentVelocity = particle.direction.length();
  56380. if (currentVelocity > limitVelocity) {
  56381. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56382. }
  56383. });
  56384. }
  56385. /// Drag
  56386. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56387. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56388. if (currentGradient !== particle._currentDragGradient) {
  56389. particle._currentDrag1 = particle._currentDrag2;
  56390. particle._currentDrag2 = nextGradient.getFactor();
  56391. particle._currentDragGradient = currentGradient;
  56392. }
  56393. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56394. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56395. });
  56396. }
  56397. particle.position.addInPlace(_this._scaledDirection);
  56398. // Noise
  56399. if (noiseTextureData && noiseTextureSize) {
  56400. var localPosition = BABYLON.Tmp.Vector3[0];
  56401. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56402. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56403. particle.position.subtractToRef(emitterPosition, localPosition);
  56404. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56405. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56406. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56407. var force = BABYLON.Tmp.Vector3[0];
  56408. var scaledForce = BABYLON.Tmp.Vector3[1];
  56409. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56410. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56411. particle.direction.addInPlace(scaledForce);
  56412. }
  56413. // Gravity
  56414. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56415. particle.direction.addInPlace(_this._scaledGravity);
  56416. // Size
  56417. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56418. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56419. if (currentGradient !== particle._currentSizeGradient) {
  56420. particle._currentSize1 = particle._currentSize2;
  56421. particle._currentSize2 = nextGradient.getFactor();
  56422. particle._currentSizeGradient = currentGradient;
  56423. }
  56424. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56425. });
  56426. }
  56427. // Remap data
  56428. if (_this._useRampGradients) {
  56429. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  56430. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  56431. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56432. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56433. particle.remapData.x = min;
  56434. particle.remapData.y = max - min;
  56435. });
  56436. }
  56437. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  56438. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  56439. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56440. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56441. particle.remapData.z = min;
  56442. particle.remapData.w = max - min;
  56443. });
  56444. }
  56445. }
  56446. if (_this._isAnimationSheetEnabled) {
  56447. particle.updateCellIndex();
  56448. }
  56449. // Update the position of the attached sub-emitters to match their attached particle
  56450. if (particle._attachedSubEmitters && particle._attachedSubEmitters.length > 0) {
  56451. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56452. ParticleSystem._InheritParticleInfoToSubEmitter(subEmitter, particle);
  56453. });
  56454. }
  56455. }
  56456. };
  56457. var particle;
  56458. for (var index = 0; index < particles.length; index++) {
  56459. _loop_1();
  56460. }
  56461. };
  56462. return _this;
  56463. }
  56464. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56465. /**
  56466. * Sets a callback that will be triggered when the system is disposed
  56467. */
  56468. set: function (callback) {
  56469. if (this._onDisposeObserver) {
  56470. this.onDisposeObservable.remove(this._onDisposeObserver);
  56471. }
  56472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56473. },
  56474. enumerable: true,
  56475. configurable: true
  56476. });
  56477. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  56478. /** Gets or sets a boolean indicating that ramp gradients must be used
  56479. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  56480. */
  56481. get: function () {
  56482. return this._useRampGradients;
  56483. },
  56484. set: function (value) {
  56485. if (this._useRampGradients === value) {
  56486. return;
  56487. }
  56488. this._useRampGradients = value;
  56489. this._resetEffect();
  56490. },
  56491. enumerable: true,
  56492. configurable: true
  56493. });
  56494. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56495. //end of Sub-emitter
  56496. /**
  56497. * Gets the current list of active particles
  56498. */
  56499. get: function () {
  56500. return this._particles;
  56501. },
  56502. enumerable: true,
  56503. configurable: true
  56504. });
  56505. /**
  56506. * Returns the string "ParticleSystem"
  56507. * @returns a string containing the class name
  56508. */
  56509. ParticleSystem.prototype.getClassName = function () {
  56510. return "ParticleSystem";
  56511. };
  56512. ParticleSystem._InheritParticleInfoToSubEmitter = function (subEmitter, particle) {
  56513. if (subEmitter.particleSystem.emitter.position) {
  56514. var emitterMesh = subEmitter.particleSystem.emitter;
  56515. emitterMesh.position.copyFrom(particle.position);
  56516. if (subEmitter.inheritDirection) {
  56517. emitterMesh.position.subtractToRef(particle.direction, BABYLON.Tmp.Vector3[0]);
  56518. // Look at using Y as forward
  56519. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56520. }
  56521. }
  56522. else {
  56523. var emitterPosition = subEmitter.particleSystem.emitter;
  56524. emitterPosition.copyFrom(particle.position);
  56525. if (subEmitter.inheritDirection) {
  56526. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  56527. }
  56528. }
  56529. // Set inheritedVelocityOffset to be used when new particles are created
  56530. particle.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56531. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56532. };
  56533. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56534. var newGradient = new BABYLON.FactorGradient();
  56535. newGradient.gradient = gradient;
  56536. newGradient.factor1 = factor;
  56537. newGradient.factor2 = factor2;
  56538. factorGradients.push(newGradient);
  56539. factorGradients.sort(function (a, b) {
  56540. if (a.gradient < b.gradient) {
  56541. return -1;
  56542. }
  56543. else if (a.gradient > b.gradient) {
  56544. return 1;
  56545. }
  56546. return 0;
  56547. });
  56548. };
  56549. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56550. if (!factorGradients) {
  56551. return;
  56552. }
  56553. var index = 0;
  56554. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56555. var factorGradient = factorGradients_1[_i];
  56556. if (factorGradient.gradient === gradient) {
  56557. factorGradients.splice(index, 1);
  56558. break;
  56559. }
  56560. index++;
  56561. }
  56562. };
  56563. /**
  56564. * Adds a new life time gradient
  56565. * @param gradient defines the gradient to use (between 0 and 1)
  56566. * @param factor defines the life time factor to affect to the specified gradient
  56567. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56568. * @returns the current particle system
  56569. */
  56570. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56571. if (!this._lifeTimeGradients) {
  56572. this._lifeTimeGradients = [];
  56573. }
  56574. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56575. return this;
  56576. };
  56577. /**
  56578. * Remove a specific life time gradient
  56579. * @param gradient defines the gradient to remove
  56580. * @returns the current particle system
  56581. */
  56582. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56583. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56584. return this;
  56585. };
  56586. /**
  56587. * Adds a new size gradient
  56588. * @param gradient defines the gradient to use (between 0 and 1)
  56589. * @param factor defines the size factor to affect to the specified gradient
  56590. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56591. * @returns the current particle system
  56592. */
  56593. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56594. if (!this._sizeGradients) {
  56595. this._sizeGradients = [];
  56596. }
  56597. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56598. return this;
  56599. };
  56600. /**
  56601. * Remove a specific size gradient
  56602. * @param gradient defines the gradient to remove
  56603. * @returns the current particle system
  56604. */
  56605. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56606. this._removeFactorGradient(this._sizeGradients, gradient);
  56607. return this;
  56608. };
  56609. /**
  56610. * Adds a new color remap gradient
  56611. * @param gradient defines the gradient to use (between 0 and 1)
  56612. * @param min defines the color remap minimal range
  56613. * @param max defines the color remap maximal range
  56614. * @returns the current particle system
  56615. */
  56616. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  56617. if (!this._colorRemapGradients) {
  56618. this._colorRemapGradients = [];
  56619. }
  56620. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  56621. return this;
  56622. };
  56623. /**
  56624. * Remove a specific color remap gradient
  56625. * @param gradient defines the gradient to remove
  56626. * @returns the current particle system
  56627. */
  56628. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  56629. this._removeFactorGradient(this._colorRemapGradients, gradient);
  56630. return this;
  56631. };
  56632. /**
  56633. * Adds a new alpha remap gradient
  56634. * @param gradient defines the gradient to use (between 0 and 1)
  56635. * @param min defines the alpha remap minimal range
  56636. * @param max defines the alpha remap maximal range
  56637. * @returns the current particle system
  56638. */
  56639. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  56640. if (!this._alphaRemapGradients) {
  56641. this._alphaRemapGradients = [];
  56642. }
  56643. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  56644. return this;
  56645. };
  56646. /**
  56647. * Remove a specific alpha remap gradient
  56648. * @param gradient defines the gradient to remove
  56649. * @returns the current particle system
  56650. */
  56651. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  56652. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  56653. return this;
  56654. };
  56655. /**
  56656. * Adds a new angular speed gradient
  56657. * @param gradient defines the gradient to use (between 0 and 1)
  56658. * @param factor defines the angular speed to affect to the specified gradient
  56659. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56660. * @returns the current particle system
  56661. */
  56662. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56663. if (!this._angularSpeedGradients) {
  56664. this._angularSpeedGradients = [];
  56665. }
  56666. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56667. return this;
  56668. };
  56669. /**
  56670. * Remove a specific angular speed gradient
  56671. * @param gradient defines the gradient to remove
  56672. * @returns the current particle system
  56673. */
  56674. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56675. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56676. return this;
  56677. };
  56678. /**
  56679. * Adds a new velocity gradient
  56680. * @param gradient defines the gradient to use (between 0 and 1)
  56681. * @param factor defines the velocity to affect to the specified gradient
  56682. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56683. * @returns the current particle system
  56684. */
  56685. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56686. if (!this._velocityGradients) {
  56687. this._velocityGradients = [];
  56688. }
  56689. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56690. return this;
  56691. };
  56692. /**
  56693. * Remove a specific velocity gradient
  56694. * @param gradient defines the gradient to remove
  56695. * @returns the current particle system
  56696. */
  56697. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56698. this._removeFactorGradient(this._velocityGradients, gradient);
  56699. return this;
  56700. };
  56701. /**
  56702. * Adds a new limit velocity gradient
  56703. * @param gradient defines the gradient to use (between 0 and 1)
  56704. * @param factor defines the limit velocity value to affect to the specified gradient
  56705. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56706. * @returns the current particle system
  56707. */
  56708. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56709. if (!this._limitVelocityGradients) {
  56710. this._limitVelocityGradients = [];
  56711. }
  56712. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56713. return this;
  56714. };
  56715. /**
  56716. * Remove a specific limit velocity gradient
  56717. * @param gradient defines the gradient to remove
  56718. * @returns the current particle system
  56719. */
  56720. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56721. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56722. return this;
  56723. };
  56724. /**
  56725. * Adds a new drag gradient
  56726. * @param gradient defines the gradient to use (between 0 and 1)
  56727. * @param factor defines the drag value to affect to the specified gradient
  56728. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56729. * @returns the current particle system
  56730. */
  56731. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56732. if (!this._dragGradients) {
  56733. this._dragGradients = [];
  56734. }
  56735. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56736. return this;
  56737. };
  56738. /**
  56739. * Remove a specific drag gradient
  56740. * @param gradient defines the gradient to remove
  56741. * @returns the current particle system
  56742. */
  56743. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56744. this._removeFactorGradient(this._dragGradients, gradient);
  56745. return this;
  56746. };
  56747. /**
  56748. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56749. * @param gradient defines the gradient to use (between 0 and 1)
  56750. * @param factor defines the emit rate value to affect to the specified gradient
  56751. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56752. * @returns the current particle system
  56753. */
  56754. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56755. if (!this._emitRateGradients) {
  56756. this._emitRateGradients = [];
  56757. }
  56758. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56759. if (!this._currentEmitRateGradient) {
  56760. this._currentEmitRateGradient = this._emitRateGradients[0];
  56761. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56762. this._currentEmitRate2 = this._currentEmitRate1;
  56763. }
  56764. if (this._emitRateGradients.length === 2) {
  56765. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56766. }
  56767. return this;
  56768. };
  56769. /**
  56770. * Remove a specific emit rate gradient
  56771. * @param gradient defines the gradient to remove
  56772. * @returns the current particle system
  56773. */
  56774. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56775. this._removeFactorGradient(this._emitRateGradients, gradient);
  56776. return this;
  56777. };
  56778. /**
  56779. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56780. * @param gradient defines the gradient to use (between 0 and 1)
  56781. * @param factor defines the start size value to affect to the specified gradient
  56782. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56783. * @returns the current particle system
  56784. */
  56785. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56786. if (!this._startSizeGradients) {
  56787. this._startSizeGradients = [];
  56788. }
  56789. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56790. if (!this._currentStartSizeGradient) {
  56791. this._currentStartSizeGradient = this._startSizeGradients[0];
  56792. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56793. this._currentStartSize2 = this._currentStartSize1;
  56794. }
  56795. if (this._startSizeGradients.length === 2) {
  56796. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56797. }
  56798. return this;
  56799. };
  56800. /**
  56801. * Remove a specific start size gradient
  56802. * @param gradient defines the gradient to remove
  56803. * @returns the current particle system
  56804. */
  56805. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56806. this._removeFactorGradient(this._emitRateGradients, gradient);
  56807. return this;
  56808. };
  56809. ParticleSystem.prototype._createRampGradientTexture = function () {
  56810. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  56811. return;
  56812. }
  56813. var data = new Uint8Array(this._rawTextureWidth * 4);
  56814. var tmpColor = BABYLON.Tmp.Color3[0];
  56815. for (var x = 0; x < this._rawTextureWidth; x++) {
  56816. var ratio = x / this._rawTextureWidth;
  56817. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  56818. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  56819. data[x * 4] = tmpColor.r * 255;
  56820. data[x * 4 + 1] = tmpColor.g * 255;
  56821. data[x * 4 + 2] = tmpColor.b * 255;
  56822. data[x * 4 + 3] = 255;
  56823. });
  56824. }
  56825. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56826. };
  56827. /**
  56828. * Gets the current list of ramp gradients.
  56829. * You must use addRampGradient and removeRampGradient to udpate this list
  56830. * @returns the list of ramp gradients
  56831. */
  56832. ParticleSystem.prototype.getRampGradients = function () {
  56833. return this._rampGradients;
  56834. };
  56835. /**
  56836. * Adds a new ramp gradient used to remap particle colors
  56837. * @param gradient defines the gradient to use (between 0 and 1)
  56838. * @param color defines the color to affect to the specified gradient
  56839. * @returns the current particle system
  56840. */
  56841. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  56842. if (!this._rampGradients) {
  56843. this._rampGradients = [];
  56844. }
  56845. var rampGradient = new BABYLON.Color3Gradient();
  56846. rampGradient.gradient = gradient;
  56847. rampGradient.color = color;
  56848. this._rampGradients.push(rampGradient);
  56849. this._rampGradients.sort(function (a, b) {
  56850. if (a.gradient < b.gradient) {
  56851. return -1;
  56852. }
  56853. else if (a.gradient > b.gradient) {
  56854. return 1;
  56855. }
  56856. return 0;
  56857. });
  56858. if (this._rampGradientsTexture) {
  56859. this._rampGradientsTexture.dispose();
  56860. this._rampGradientsTexture = null;
  56861. }
  56862. this._createRampGradientTexture();
  56863. return this;
  56864. };
  56865. /**
  56866. * Remove a specific ramp gradient
  56867. * @param gradient defines the gradient to remove
  56868. * @returns the current particle system
  56869. */
  56870. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  56871. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  56872. this._rampGradientsTexture = null;
  56873. if (this._rampGradients && this._rampGradients.length > 0) {
  56874. this._createRampGradientTexture();
  56875. }
  56876. return this;
  56877. };
  56878. /**
  56879. * Adds a new color gradient
  56880. * @param gradient defines the gradient to use (between 0 and 1)
  56881. * @param color defines the color to affect to the specified gradient
  56882. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56883. */
  56884. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56885. if (!this._colorGradients) {
  56886. this._colorGradients = [];
  56887. }
  56888. var colorGradient = new BABYLON.ColorGradient();
  56889. colorGradient.gradient = gradient;
  56890. colorGradient.color1 = color;
  56891. colorGradient.color2 = color2;
  56892. this._colorGradients.push(colorGradient);
  56893. this._colorGradients.sort(function (a, b) {
  56894. if (a.gradient < b.gradient) {
  56895. return -1;
  56896. }
  56897. else if (a.gradient > b.gradient) {
  56898. return 1;
  56899. }
  56900. return 0;
  56901. });
  56902. return this;
  56903. };
  56904. /**
  56905. * Remove a specific color gradient
  56906. * @param gradient defines the gradient to remove
  56907. */
  56908. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56909. if (!this._colorGradients) {
  56910. return this;
  56911. }
  56912. var index = 0;
  56913. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56914. var colorGradient = _a[_i];
  56915. if (colorGradient.gradient === gradient) {
  56916. this._colorGradients.splice(index, 1);
  56917. break;
  56918. }
  56919. index++;
  56920. }
  56921. return this;
  56922. };
  56923. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56924. u = Math.abs(u) * 0.5 + 0.5;
  56925. v = Math.abs(v) * 0.5 + 0.5;
  56926. var wrappedU = ((u * width) % width) | 0;
  56927. var wrappedV = ((v * height) % height) | 0;
  56928. var position = (wrappedU + wrappedV * width) * 4;
  56929. return pixels[position] / 255;
  56930. };
  56931. ParticleSystem.prototype._reset = function () {
  56932. this._resetEffect();
  56933. };
  56934. ParticleSystem.prototype._resetEffect = function () {
  56935. if (this._vertexBuffer) {
  56936. this._vertexBuffer.dispose();
  56937. this._vertexBuffer = null;
  56938. }
  56939. if (this._spriteBuffer) {
  56940. this._spriteBuffer.dispose();
  56941. this._spriteBuffer = null;
  56942. }
  56943. this._createVertexBuffers();
  56944. };
  56945. ParticleSystem.prototype._createVertexBuffers = function () {
  56946. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56947. if (this._isAnimationSheetEnabled) {
  56948. this._vertexBufferSize += 1;
  56949. }
  56950. if (!this._isBillboardBased) {
  56951. this._vertexBufferSize += 3;
  56952. }
  56953. if (this._useRampGradients) {
  56954. this._vertexBufferSize += 4;
  56955. }
  56956. var engine = this._scene.getEngine();
  56957. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56958. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56959. var dataOffset = 0;
  56960. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56961. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56962. dataOffset += 3;
  56963. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56964. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56965. dataOffset += 4;
  56966. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56967. this._vertexBuffers["angle"] = options;
  56968. dataOffset += 1;
  56969. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56970. this._vertexBuffers["size"] = size;
  56971. dataOffset += 2;
  56972. if (this._isAnimationSheetEnabled) {
  56973. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56974. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56975. dataOffset += 1;
  56976. }
  56977. if (!this._isBillboardBased) {
  56978. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56979. this._vertexBuffers["direction"] = directionBuffer;
  56980. dataOffset += 3;
  56981. }
  56982. if (this._useRampGradients) {
  56983. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56984. this._vertexBuffers["remapData"] = rampDataBuffer;
  56985. dataOffset += 4;
  56986. }
  56987. var offsets;
  56988. if (this._useInstancing) {
  56989. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56990. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56991. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56992. }
  56993. else {
  56994. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56995. dataOffset += 2;
  56996. }
  56997. this._vertexBuffers["offset"] = offsets;
  56998. };
  56999. ParticleSystem.prototype._createIndexBuffer = function () {
  57000. if (this._useInstancing) {
  57001. return;
  57002. }
  57003. var indices = [];
  57004. var index = 0;
  57005. for (var count = 0; count < this._capacity; count++) {
  57006. indices.push(index);
  57007. indices.push(index + 1);
  57008. indices.push(index + 2);
  57009. indices.push(index);
  57010. indices.push(index + 2);
  57011. indices.push(index + 3);
  57012. index += 4;
  57013. }
  57014. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  57015. };
  57016. /**
  57017. * Gets the maximum number of particles active at the same time.
  57018. * @returns The max number of active particles.
  57019. */
  57020. ParticleSystem.prototype.getCapacity = function () {
  57021. return this._capacity;
  57022. };
  57023. /**
  57024. * Gets whether there are still active particles in the system.
  57025. * @returns True if it is alive, otherwise false.
  57026. */
  57027. ParticleSystem.prototype.isAlive = function () {
  57028. return this._alive;
  57029. };
  57030. /**
  57031. * Gets if the system has been started. (Note: this will still be true after stop is called)
  57032. * @returns True if it has been started, otherwise false.
  57033. */
  57034. ParticleSystem.prototype.isStarted = function () {
  57035. return this._started;
  57036. };
  57037. /**
  57038. * Starts the particle system and begins to emit
  57039. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  57040. */
  57041. ParticleSystem.prototype.start = function (delay) {
  57042. var _this = this;
  57043. if (delay === void 0) { delay = 0; }
  57044. if (delay) {
  57045. setTimeout(function () {
  57046. _this.start(0);
  57047. }, delay);
  57048. return;
  57049. }
  57050. // Convert the subEmitters field to the constant type field _subEmitters
  57051. this._subEmitters = new Array();
  57052. if (this.subEmitters) {
  57053. this.subEmitters.forEach(function (subEmitter) {
  57054. if (subEmitter instanceof ParticleSystem) {
  57055. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  57056. }
  57057. else if (subEmitter instanceof BABYLON.SubEmitter) {
  57058. _this._subEmitters.push([subEmitter]);
  57059. }
  57060. else if (subEmitter instanceof Array) {
  57061. _this._subEmitters.push(subEmitter);
  57062. }
  57063. });
  57064. }
  57065. this._started = true;
  57066. this._stopped = false;
  57067. this._actualFrame = 0;
  57068. if (this._subEmitters && this._subEmitters.length != 0) {
  57069. this.activeSubSystems = new Array();
  57070. }
  57071. if (this.preWarmCycles) {
  57072. for (var index = 0; index < this.preWarmCycles; index++) {
  57073. this.animate(true);
  57074. }
  57075. }
  57076. };
  57077. /**
  57078. * Stops the particle system.
  57079. * @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.
  57080. */
  57081. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  57082. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  57083. this._stopped = true;
  57084. if (stopSubEmitters) {
  57085. this._stopSubEmitters();
  57086. }
  57087. };
  57088. // animation sheet
  57089. /**
  57090. * Remove all active particles
  57091. */
  57092. ParticleSystem.prototype.reset = function () {
  57093. this._stockParticles = [];
  57094. this._particles = [];
  57095. };
  57096. /**
  57097. * @hidden (for internal use only)
  57098. */
  57099. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  57100. var offset = index * this._vertexBufferSize;
  57101. this._vertexData[offset++] = particle.position.x;
  57102. this._vertexData[offset++] = particle.position.y;
  57103. this._vertexData[offset++] = particle.position.z;
  57104. this._vertexData[offset++] = particle.color.r;
  57105. this._vertexData[offset++] = particle.color.g;
  57106. this._vertexData[offset++] = particle.color.b;
  57107. this._vertexData[offset++] = particle.color.a;
  57108. this._vertexData[offset++] = particle.angle;
  57109. this._vertexData[offset++] = particle.scale.x * particle.size;
  57110. this._vertexData[offset++] = particle.scale.y * particle.size;
  57111. if (this._isAnimationSheetEnabled) {
  57112. this._vertexData[offset++] = particle.cellIndex;
  57113. }
  57114. if (!this._isBillboardBased) {
  57115. if (particle._initialDirection) {
  57116. this._vertexData[offset++] = particle._initialDirection.x;
  57117. this._vertexData[offset++] = particle._initialDirection.y;
  57118. this._vertexData[offset++] = particle._initialDirection.z;
  57119. }
  57120. else {
  57121. this._vertexData[offset++] = particle.direction.x;
  57122. this._vertexData[offset++] = particle.direction.y;
  57123. this._vertexData[offset++] = particle.direction.z;
  57124. }
  57125. }
  57126. if (this._useRampGradients) {
  57127. this._vertexData[offset++] = particle.remapData.x;
  57128. this._vertexData[offset++] = particle.remapData.y;
  57129. this._vertexData[offset++] = particle.remapData.z;
  57130. this._vertexData[offset++] = particle.remapData.w;
  57131. }
  57132. if (!this._useInstancing) {
  57133. if (this._isAnimationSheetEnabled) {
  57134. if (offsetX === 0)
  57135. offsetX = this._epsilon;
  57136. else if (offsetX === 1)
  57137. offsetX = 1 - this._epsilon;
  57138. if (offsetY === 0)
  57139. offsetY = this._epsilon;
  57140. else if (offsetY === 1)
  57141. offsetY = 1 - this._epsilon;
  57142. }
  57143. this._vertexData[offset++] = offsetX;
  57144. this._vertexData[offset++] = offsetY;
  57145. }
  57146. };
  57147. ParticleSystem.prototype._stopSubEmitters = function () {
  57148. if (!this.activeSubSystems) {
  57149. return;
  57150. }
  57151. this.activeSubSystems.forEach(function (subSystem) {
  57152. subSystem.stop(true);
  57153. });
  57154. this.activeSubSystems = new Array();
  57155. };
  57156. ParticleSystem.prototype._removeFromRoot = function () {
  57157. if (!this._rootParticleSystem) {
  57158. return;
  57159. }
  57160. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  57161. if (index !== -1) {
  57162. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  57163. }
  57164. };
  57165. // End of sub system methods
  57166. ParticleSystem.prototype._update = function (newParticles) {
  57167. var _this = this;
  57168. // Update current
  57169. this._alive = this._particles.length > 0;
  57170. if (this.emitter.position) {
  57171. var emitterMesh = this.emitter;
  57172. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  57173. }
  57174. else {
  57175. var emitterPosition = this.emitter;
  57176. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57177. }
  57178. this.updateFunction(this._particles);
  57179. // Add new ones
  57180. var particle;
  57181. var _loop_2 = function () {
  57182. if (this_1._particles.length === this_1._capacity) {
  57183. return "break";
  57184. }
  57185. particle = this_1._createParticle();
  57186. this_1._particles.push(particle);
  57187. // Emitter
  57188. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  57189. if (this_1.startPositionFunction) {
  57190. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57191. }
  57192. else {
  57193. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57194. }
  57195. if (this_1.startDirectionFunction) {
  57196. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57197. }
  57198. else {
  57199. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57200. }
  57201. if (emitPower === 0) {
  57202. if (!particle._initialDirection) {
  57203. particle._initialDirection = particle.direction.clone();
  57204. }
  57205. else {
  57206. particle._initialDirection.copyFrom(particle.direction);
  57207. }
  57208. }
  57209. else {
  57210. particle._initialDirection = null;
  57211. }
  57212. particle.direction.scaleInPlace(emitPower);
  57213. // Life time
  57214. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  57215. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  57216. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  57217. var factorGradient1 = currentGradient;
  57218. var factorGradient2 = nextGradient;
  57219. var lifeTime1 = factorGradient1.getFactor();
  57220. var lifeTime2 = factorGradient2.getFactor();
  57221. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  57222. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  57223. });
  57224. }
  57225. else {
  57226. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  57227. }
  57228. // Size
  57229. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  57230. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  57231. }
  57232. else {
  57233. particle._currentSizeGradient = this_1._sizeGradients[0];
  57234. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  57235. particle.size = particle._currentSize1;
  57236. if (this_1._sizeGradients.length > 1) {
  57237. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57238. }
  57239. else {
  57240. particle._currentSize2 = particle._currentSize1;
  57241. }
  57242. }
  57243. // Size and scale
  57244. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57245. // Adjust scale by start size
  57246. if (this_1._startSizeGradients && this_1._startSizeGradients[0]) {
  57247. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57248. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57249. if (currentGradient !== _this._currentStartSizeGradient) {
  57250. _this._currentStartSize1 = _this._currentStartSize2;
  57251. _this._currentStartSize2 = nextGradient.getFactor();
  57252. _this._currentStartSizeGradient = currentGradient;
  57253. }
  57254. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57255. particle.scale.scaleInPlace(value);
  57256. });
  57257. }
  57258. // Angle
  57259. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57260. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57261. }
  57262. else {
  57263. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57264. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57265. particle._currentAngularSpeed1 = particle.angularSpeed;
  57266. if (this_1._angularSpeedGradients.length > 1) {
  57267. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57268. }
  57269. else {
  57270. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57271. }
  57272. }
  57273. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57274. // Velocity
  57275. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57276. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57277. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57278. if (this_1._velocityGradients.length > 1) {
  57279. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57280. }
  57281. else {
  57282. particle._currentVelocity2 = particle._currentVelocity1;
  57283. }
  57284. }
  57285. // Limit velocity
  57286. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57287. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57288. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57289. if (this_1._limitVelocityGradients.length > 1) {
  57290. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57291. }
  57292. else {
  57293. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57294. }
  57295. }
  57296. // Drag
  57297. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57298. particle._currentDragGradient = this_1._dragGradients[0];
  57299. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57300. if (this_1._dragGradients.length > 1) {
  57301. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57302. }
  57303. else {
  57304. particle._currentDrag2 = particle._currentDrag1;
  57305. }
  57306. }
  57307. // Color
  57308. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57309. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57310. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57311. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57312. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57313. }
  57314. else {
  57315. particle._currentColorGradient = this_1._colorGradients[0];
  57316. particle._currentColorGradient.getColorToRef(particle.color);
  57317. particle._currentColor1.copyFrom(particle.color);
  57318. if (this_1._colorGradients.length > 1) {
  57319. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57320. }
  57321. else {
  57322. particle._currentColor2.copyFrom(particle.color);
  57323. }
  57324. }
  57325. // Sheet
  57326. if (this_1._isAnimationSheetEnabled) {
  57327. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57328. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57329. }
  57330. // Inherited Velocity
  57331. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  57332. // Ramp
  57333. if (this_1._useRampGradients) {
  57334. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  57335. }
  57336. };
  57337. var this_1 = this, step;
  57338. for (var index = 0; index < newParticles; index++) {
  57339. var state_1 = _loop_2();
  57340. if (state_1 === "break")
  57341. break;
  57342. }
  57343. };
  57344. /** @hidden */
  57345. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  57346. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57347. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57348. if (useRampGradients === void 0) { useRampGradients = false; }
  57349. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57350. if (isAnimationSheetEnabled) {
  57351. attributeNamesOrOptions.push("cellIndex");
  57352. }
  57353. if (!isBillboardBased) {
  57354. attributeNamesOrOptions.push("direction");
  57355. }
  57356. if (useRampGradients) {
  57357. attributeNamesOrOptions.push("remapData");
  57358. }
  57359. return attributeNamesOrOptions;
  57360. };
  57361. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57362. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57363. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57364. if (isAnimationSheetEnabled) {
  57365. effectCreationOption.push("particlesInfos");
  57366. }
  57367. return effectCreationOption;
  57368. };
  57369. ParticleSystem.prototype._getEffect = function (blendMode) {
  57370. if (this._customEffect) {
  57371. return this._customEffect;
  57372. }
  57373. ;
  57374. var defines = [];
  57375. if (this._scene.clipPlane) {
  57376. defines.push("#define CLIPPLANE");
  57377. }
  57378. if (this._scene.clipPlane2) {
  57379. defines.push("#define CLIPPLANE2");
  57380. }
  57381. if (this._scene.clipPlane3) {
  57382. defines.push("#define CLIPPLANE3");
  57383. }
  57384. if (this._scene.clipPlane4) {
  57385. defines.push("#define CLIPPLANE4");
  57386. }
  57387. if (this._isAnimationSheetEnabled) {
  57388. defines.push("#define ANIMATESHEET");
  57389. }
  57390. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57391. defines.push("#define BLENDMULTIPLYMODE");
  57392. }
  57393. if (this._useRampGradients) {
  57394. defines.push("#define RAMPGRADIENT");
  57395. }
  57396. if (this._isBillboardBased) {
  57397. defines.push("#define BILLBOARD");
  57398. switch (this.billboardMode) {
  57399. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57400. defines.push("#define BILLBOARDY");
  57401. break;
  57402. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57403. default:
  57404. break;
  57405. }
  57406. }
  57407. if (this._imageProcessingConfiguration) {
  57408. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57409. defines.push(this._imageProcessingConfigurationDefines.toString());
  57410. }
  57411. // Effect
  57412. var join = defines.join("\n");
  57413. if (this._cachedDefines !== join) {
  57414. this._cachedDefines = join;
  57415. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  57416. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57417. var samplers = ["diffuseSampler", "rampSampler"];
  57418. if (BABYLON.ImageProcessingConfiguration) {
  57419. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57420. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57421. }
  57422. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  57423. }
  57424. return this._effect;
  57425. };
  57426. /**
  57427. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57428. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57429. */
  57430. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57431. var _this = this;
  57432. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57433. if (!this._started)
  57434. return;
  57435. if (!preWarmOnly) {
  57436. // Check
  57437. if (!this.isReady())
  57438. return;
  57439. if (this._currentRenderId === this._scene.getRenderId()) {
  57440. return;
  57441. }
  57442. this._currentRenderId = this._scene.getRenderId();
  57443. }
  57444. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57445. // Determine the number of particles we need to create
  57446. var newParticles;
  57447. if (this.manualEmitCount > -1) {
  57448. newParticles = this.manualEmitCount;
  57449. this._newPartsExcess = 0;
  57450. this.manualEmitCount = 0;
  57451. }
  57452. else {
  57453. var rate_1 = this.emitRate;
  57454. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57455. var ratio = this._actualFrame / this.targetStopDuration;
  57456. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57457. if (currentGradient !== _this._currentEmitRateGradient) {
  57458. _this._currentEmitRate1 = _this._currentEmitRate2;
  57459. _this._currentEmitRate2 = nextGradient.getFactor();
  57460. _this._currentEmitRateGradient = currentGradient;
  57461. }
  57462. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57463. });
  57464. }
  57465. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57466. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57467. }
  57468. if (this._newPartsExcess > 1.0) {
  57469. newParticles += this._newPartsExcess >> 0;
  57470. this._newPartsExcess -= this._newPartsExcess >> 0;
  57471. }
  57472. this._alive = false;
  57473. if (!this._stopped) {
  57474. this._actualFrame += this._scaledUpdateSpeed;
  57475. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57476. this.stop();
  57477. }
  57478. else {
  57479. newParticles = 0;
  57480. }
  57481. this._update(newParticles);
  57482. // Stopped?
  57483. if (this._stopped) {
  57484. if (!this._alive) {
  57485. this._started = false;
  57486. if (this.onAnimationEnd) {
  57487. this.onAnimationEnd();
  57488. }
  57489. if (this.disposeOnStop) {
  57490. this._scene._toBeDisposed.push(this);
  57491. }
  57492. }
  57493. }
  57494. if (!preWarmOnly) {
  57495. // Update VBO
  57496. var offset = 0;
  57497. for (var index = 0; index < this._particles.length; index++) {
  57498. var particle = this._particles[index];
  57499. this._appendParticleVertices(offset, particle);
  57500. offset += this._useInstancing ? 1 : 4;
  57501. }
  57502. if (this._vertexBuffer) {
  57503. this._vertexBuffer.update(this._vertexData);
  57504. }
  57505. }
  57506. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57507. this.stop();
  57508. }
  57509. };
  57510. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57511. this._appendParticleVertex(offset++, particle, 0, 0);
  57512. if (!this._useInstancing) {
  57513. this._appendParticleVertex(offset++, particle, 1, 0);
  57514. this._appendParticleVertex(offset++, particle, 1, 1);
  57515. this._appendParticleVertex(offset++, particle, 0, 1);
  57516. }
  57517. };
  57518. /**
  57519. * Rebuilds the particle system.
  57520. */
  57521. ParticleSystem.prototype.rebuild = function () {
  57522. this._createIndexBuffer();
  57523. if (this._vertexBuffer) {
  57524. this._vertexBuffer._rebuild();
  57525. }
  57526. };
  57527. /**
  57528. * Is this system ready to be used/rendered
  57529. * @return true if the system is ready
  57530. */
  57531. ParticleSystem.prototype.isReady = function () {
  57532. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57533. return false;
  57534. }
  57535. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57536. if (!this._getEffect(this.blendMode).isReady()) {
  57537. return false;
  57538. }
  57539. }
  57540. else {
  57541. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  57542. return false;
  57543. }
  57544. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  57545. return false;
  57546. }
  57547. }
  57548. return true;
  57549. };
  57550. ParticleSystem.prototype._render = function (blendMode) {
  57551. var effect = this._getEffect(blendMode);
  57552. var engine = this._scene.getEngine();
  57553. // Render
  57554. engine.enableEffect(effect);
  57555. var viewMatrix = this._scene.getViewMatrix();
  57556. effect.setTexture("diffuseSampler", this.particleTexture);
  57557. effect.setMatrix("view", viewMatrix);
  57558. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57559. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57560. var baseSize = this.particleTexture.getBaseSize();
  57561. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57562. }
  57563. effect.setVector2("translationPivot", this.translationPivot);
  57564. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57565. if (this._isBillboardBased) {
  57566. var camera = this._scene.activeCamera;
  57567. effect.setVector3("eyePosition", camera.globalPosition);
  57568. }
  57569. if (this._rampGradientsTexture) {
  57570. effect.setTexture("rampSampler", this._rampGradientsTexture);
  57571. }
  57572. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57573. var invView = viewMatrix.clone();
  57574. invView.invert();
  57575. effect.setMatrix("invView", invView);
  57576. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57577. }
  57578. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57579. // image processing
  57580. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57581. this._imageProcessingConfiguration.bind(effect);
  57582. }
  57583. // Draw order
  57584. switch (blendMode) {
  57585. case ParticleSystem.BLENDMODE_ADD:
  57586. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57587. break;
  57588. case ParticleSystem.BLENDMODE_ONEONE:
  57589. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57590. break;
  57591. case ParticleSystem.BLENDMODE_STANDARD:
  57592. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57593. break;
  57594. case ParticleSystem.BLENDMODE_MULTIPLY:
  57595. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57596. break;
  57597. }
  57598. if (this._useInstancing) {
  57599. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57600. }
  57601. else {
  57602. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57603. }
  57604. return this._particles.length;
  57605. };
  57606. /**
  57607. * Renders the particle system in its current state.
  57608. * @returns the current number of particles
  57609. */
  57610. ParticleSystem.prototype.render = function () {
  57611. // Check
  57612. if (!this.isReady() || !this._particles.length) {
  57613. return 0;
  57614. }
  57615. var engine = this._scene.getEngine();
  57616. engine.setState(false);
  57617. if (this.forceDepthWrite) {
  57618. engine.setDepthWrite(true);
  57619. }
  57620. var outparticles = 0;
  57621. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57622. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  57623. }
  57624. outparticles = this._render(this.blendMode);
  57625. engine.unbindInstanceAttributes();
  57626. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57627. return outparticles;
  57628. };
  57629. /**
  57630. * Disposes the particle system and free the associated resources
  57631. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57632. */
  57633. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57634. if (disposeTexture === void 0) { disposeTexture = true; }
  57635. if (this._vertexBuffer) {
  57636. this._vertexBuffer.dispose();
  57637. this._vertexBuffer = null;
  57638. }
  57639. if (this._spriteBuffer) {
  57640. this._spriteBuffer.dispose();
  57641. this._spriteBuffer = null;
  57642. }
  57643. if (this._indexBuffer) {
  57644. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57645. this._indexBuffer = null;
  57646. }
  57647. if (disposeTexture && this.particleTexture) {
  57648. this.particleTexture.dispose();
  57649. this.particleTexture = null;
  57650. }
  57651. if (disposeTexture && this.noiseTexture) {
  57652. this.noiseTexture.dispose();
  57653. this.noiseTexture = null;
  57654. }
  57655. if (this._rampGradientsTexture) {
  57656. this._rampGradientsTexture.dispose();
  57657. this._rampGradientsTexture = null;
  57658. }
  57659. this._removeFromRoot();
  57660. if (this._disposeEmitterOnDispose && !this.emitter.isDisposed) {
  57661. this.emitter.dispose();
  57662. }
  57663. // Remove from scene
  57664. var index = this._scene.particleSystems.indexOf(this);
  57665. if (index > -1) {
  57666. this._scene.particleSystems.splice(index, 1);
  57667. }
  57668. // Callback
  57669. this.onDisposeObservable.notifyObservers(this);
  57670. this.onDisposeObservable.clear();
  57671. };
  57672. // Clone
  57673. /**
  57674. * Clones the particle system.
  57675. * @param name The name of the cloned object
  57676. * @param newEmitter The new emitter to use
  57677. * @returns the cloned particle system
  57678. */
  57679. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57680. var custom = null;
  57681. var program = null;
  57682. if (this.customShader != null) {
  57683. program = this.customShader;
  57684. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57685. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57686. }
  57687. else if (this._customEffect) {
  57688. custom = this._customEffect;
  57689. }
  57690. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57691. result.customShader = program;
  57692. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57693. if (newEmitter === undefined) {
  57694. newEmitter = this.emitter;
  57695. }
  57696. result.emitter = newEmitter;
  57697. if (this.particleTexture) {
  57698. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57699. }
  57700. // Clone gradients
  57701. if (this._colorGradients) {
  57702. this._colorGradients.forEach(function (v) {
  57703. result.addColorGradient(v.gradient, v.color1, v.color2);
  57704. });
  57705. }
  57706. if (this._dragGradients) {
  57707. this._dragGradients.forEach(function (v) {
  57708. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  57709. });
  57710. }
  57711. if (this._angularSpeedGradients) {
  57712. this._angularSpeedGradients.forEach(function (v) {
  57713. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  57714. });
  57715. }
  57716. if (this._emitRateGradients) {
  57717. this._emitRateGradients.forEach(function (v) {
  57718. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  57719. });
  57720. }
  57721. if (this._lifeTimeGradients) {
  57722. this._lifeTimeGradients.forEach(function (v) {
  57723. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  57724. });
  57725. }
  57726. if (this._limitVelocityGradients) {
  57727. this._limitVelocityGradients.forEach(function (v) {
  57728. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  57729. });
  57730. }
  57731. if (this._sizeGradients) {
  57732. this._sizeGradients.forEach(function (v) {
  57733. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  57734. });
  57735. }
  57736. if (this._startSizeGradients) {
  57737. this._startSizeGradients.forEach(function (v) {
  57738. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  57739. });
  57740. }
  57741. if (this._velocityGradients) {
  57742. this._velocityGradients.forEach(function (v) {
  57743. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  57744. });
  57745. }
  57746. if (this._rampGradients) {
  57747. this._rampGradients.forEach(function (v) {
  57748. result.addRampGradient(v.gradient, v.color);
  57749. });
  57750. }
  57751. if (this._colorRemapGradients) {
  57752. this._colorRemapGradients.forEach(function (v) {
  57753. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  57754. });
  57755. }
  57756. if (this._alphaRemapGradients) {
  57757. this._alphaRemapGradients.forEach(function (v) {
  57758. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  57759. });
  57760. }
  57761. if (!this.preventAutoStart) {
  57762. result.start();
  57763. }
  57764. return result;
  57765. };
  57766. /**
  57767. * Serializes the particle system to a JSON object.
  57768. * @returns the JSON object
  57769. */
  57770. ParticleSystem.prototype.serialize = function () {
  57771. var serializationObject = {};
  57772. ParticleSystem._Serialize(serializationObject, this);
  57773. serializationObject.textureMask = this.textureMask.asArray();
  57774. serializationObject.customShader = this.customShader;
  57775. serializationObject.preventAutoStart = this.preventAutoStart;
  57776. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57777. return serializationObject;
  57778. };
  57779. /** @hidden */
  57780. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57781. serializationObject.name = particleSystem.name;
  57782. serializationObject.id = particleSystem.id;
  57783. serializationObject.capacity = particleSystem.getCapacity();
  57784. // Emitter
  57785. if (particleSystem.emitter.position) {
  57786. var emitterMesh = particleSystem.emitter;
  57787. serializationObject.emitterId = emitterMesh.id;
  57788. }
  57789. else {
  57790. var emitterPosition = particleSystem.emitter;
  57791. serializationObject.emitter = emitterPosition.asArray();
  57792. }
  57793. // Emitter
  57794. if (particleSystem.particleEmitterType) {
  57795. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57796. }
  57797. if (particleSystem.particleTexture) {
  57798. serializationObject.textureName = particleSystem.particleTexture.name;
  57799. }
  57800. // Animations
  57801. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57802. // Particle system
  57803. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57804. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57805. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57806. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57807. serializationObject.minSize = particleSystem.minSize;
  57808. serializationObject.maxSize = particleSystem.maxSize;
  57809. serializationObject.minScaleX = particleSystem.minScaleX;
  57810. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57811. serializationObject.minScaleY = particleSystem.minScaleY;
  57812. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57813. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57814. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57815. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57816. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57817. serializationObject.emitRate = particleSystem.emitRate;
  57818. serializationObject.gravity = particleSystem.gravity.asArray();
  57819. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57820. serializationObject.color1 = particleSystem.color1.asArray();
  57821. serializationObject.color2 = particleSystem.color2.asArray();
  57822. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57823. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57824. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57825. serializationObject.blendMode = particleSystem.blendMode;
  57826. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57827. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57828. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57829. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57830. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57831. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57832. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57833. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57834. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57835. var colorGradients = particleSystem.getColorGradients();
  57836. if (colorGradients) {
  57837. serializationObject.colorGradients = [];
  57838. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57839. var colorGradient = colorGradients_1[_i];
  57840. var serializedGradient = {
  57841. gradient: colorGradient.gradient,
  57842. color1: colorGradient.color1.asArray()
  57843. };
  57844. if (colorGradient.color2) {
  57845. serializedGradient.color2 = colorGradient.color2.asArray();
  57846. }
  57847. serializationObject.colorGradients.push(serializedGradient);
  57848. }
  57849. }
  57850. var rampGradients = particleSystem.getRampGradients();
  57851. if (rampGradients) {
  57852. serializationObject.rampGradients = [];
  57853. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  57854. var rampGradient = rampGradients_1[_a];
  57855. var serializedGradient = {
  57856. gradient: rampGradient.gradient,
  57857. color: rampGradient.color.asArray()
  57858. };
  57859. serializationObject.rampGradients.push(serializedGradient);
  57860. }
  57861. }
  57862. var colorRemapGradients = particleSystem.getColorRemapGradients();
  57863. if (colorRemapGradients) {
  57864. serializationObject.colorRemapGradients = [];
  57865. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  57866. var colorRemapGradient = colorRemapGradients_1[_b];
  57867. var serializedGradient = {
  57868. gradient: colorRemapGradient.gradient,
  57869. factor1: colorRemapGradient.factor1
  57870. };
  57871. if (colorRemapGradient.factor2 !== undefined) {
  57872. serializedGradient.factor2 = colorRemapGradient.factor2;
  57873. }
  57874. serializationObject.colorRemapGradients.push(serializedGradient);
  57875. }
  57876. }
  57877. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  57878. if (alphaRemapGradients) {
  57879. serializationObject.alphaRemapGradients = [];
  57880. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  57881. var alphaRemapGradient = alphaRemapGradients_1[_c];
  57882. var serializedGradient = {
  57883. gradient: alphaRemapGradient.gradient,
  57884. factor1: alphaRemapGradient.factor1
  57885. };
  57886. if (alphaRemapGradient.factor2 !== undefined) {
  57887. serializedGradient.factor2 = alphaRemapGradient.factor2;
  57888. }
  57889. serializationObject.alphaRemapGradients.push(serializedGradient);
  57890. }
  57891. }
  57892. var sizeGradients = particleSystem.getSizeGradients();
  57893. if (sizeGradients) {
  57894. serializationObject.sizeGradients = [];
  57895. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  57896. var sizeGradient = sizeGradients_1[_d];
  57897. var serializedGradient = {
  57898. gradient: sizeGradient.gradient,
  57899. factor1: sizeGradient.factor1
  57900. };
  57901. if (sizeGradient.factor2 !== undefined) {
  57902. serializedGradient.factor2 = sizeGradient.factor2;
  57903. }
  57904. serializationObject.sizeGradients.push(serializedGradient);
  57905. }
  57906. }
  57907. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57908. if (angularSpeedGradients) {
  57909. serializationObject.angularSpeedGradients = [];
  57910. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  57911. var angularSpeedGradient = angularSpeedGradients_1[_e];
  57912. var serializedGradient = {
  57913. gradient: angularSpeedGradient.gradient,
  57914. factor1: angularSpeedGradient.factor1
  57915. };
  57916. if (angularSpeedGradient.factor2 !== undefined) {
  57917. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57918. }
  57919. serializationObject.angularSpeedGradients.push(serializedGradient);
  57920. }
  57921. }
  57922. var velocityGradients = particleSystem.getVelocityGradients();
  57923. if (velocityGradients) {
  57924. serializationObject.velocityGradients = [];
  57925. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  57926. var velocityGradient = velocityGradients_1[_f];
  57927. var serializedGradient = {
  57928. gradient: velocityGradient.gradient,
  57929. factor1: velocityGradient.factor1
  57930. };
  57931. if (velocityGradient.factor2 !== undefined) {
  57932. serializedGradient.factor2 = velocityGradient.factor2;
  57933. }
  57934. serializationObject.velocityGradients.push(serializedGradient);
  57935. }
  57936. }
  57937. var dragGradients = particleSystem.getDragGradients();
  57938. if (dragGradients) {
  57939. serializationObject.dragyGradients = [];
  57940. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  57941. var dragGradient = dragGradients_1[_g];
  57942. var serializedGradient = {
  57943. gradient: dragGradient.gradient,
  57944. factor1: dragGradient.factor1
  57945. };
  57946. if (dragGradient.factor2 !== undefined) {
  57947. serializedGradient.factor2 = dragGradient.factor2;
  57948. }
  57949. serializationObject.dragGradients.push(serializedGradient);
  57950. }
  57951. }
  57952. var emitRateGradients = particleSystem.getEmitRateGradients();
  57953. if (emitRateGradients) {
  57954. serializationObject.emitRateGradients = [];
  57955. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  57956. var emitRateGradient = emitRateGradients_1[_h];
  57957. var serializedGradient = {
  57958. gradient: emitRateGradient.gradient,
  57959. factor1: emitRateGradient.factor1
  57960. };
  57961. if (emitRateGradient.factor2 !== undefined) {
  57962. serializedGradient.factor2 = emitRateGradient.factor2;
  57963. }
  57964. serializationObject.emitRateGradients.push(serializedGradient);
  57965. }
  57966. }
  57967. var startSizeGradients = particleSystem.getStartSizeGradients();
  57968. if (startSizeGradients) {
  57969. serializationObject.startSizeGradients = [];
  57970. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  57971. var startSizeGradient = startSizeGradients_1[_j];
  57972. var serializedGradient = {
  57973. gradient: startSizeGradient.gradient,
  57974. factor1: startSizeGradient.factor1
  57975. };
  57976. if (startSizeGradient.factor2 !== undefined) {
  57977. serializedGradient.factor2 = startSizeGradient.factor2;
  57978. }
  57979. serializationObject.startSizeGradients.push(serializedGradient);
  57980. }
  57981. }
  57982. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57983. if (limitVelocityGradients) {
  57984. serializationObject.limitVelocityGradients = [];
  57985. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  57986. var limitVelocityGradient = limitVelocityGradients_1[_k];
  57987. var serializedGradient = {
  57988. gradient: limitVelocityGradient.gradient,
  57989. factor1: limitVelocityGradient.factor1
  57990. };
  57991. if (limitVelocityGradient.factor2 !== undefined) {
  57992. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57993. }
  57994. serializationObject.limitVelocityGradients.push(serializedGradient);
  57995. }
  57996. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57997. }
  57998. if (BABYLON.ProceduralTexture && particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57999. var noiseTexture = particleSystem.noiseTexture;
  58000. serializationObject.noiseTexture = noiseTexture.serialize();
  58001. }
  58002. };
  58003. /** @hidden */
  58004. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  58005. // Texture
  58006. if (parsedParticleSystem.textureName) {
  58007. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58008. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58009. }
  58010. // Emitter
  58011. if (parsedParticleSystem.emitterId === undefined) {
  58012. particleSystem.emitter = BABYLON.Vector3.Zero();
  58013. }
  58014. else if (parsedParticleSystem.emitterId) {
  58015. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58016. }
  58017. else {
  58018. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58019. }
  58020. // Misc.
  58021. if (parsedParticleSystem.renderingGroupId !== undefined) {
  58022. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  58023. }
  58024. if (parsedParticleSystem.isBillboardBased !== undefined) {
  58025. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  58026. }
  58027. // Animations
  58028. if (parsedParticleSystem.animations) {
  58029. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58030. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58031. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58032. }
  58033. }
  58034. if (parsedParticleSystem.autoAnimate) {
  58035. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  58036. }
  58037. // Particle system
  58038. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58039. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58040. particleSystem.minSize = parsedParticleSystem.minSize;
  58041. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58042. if (parsedParticleSystem.minScaleX) {
  58043. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  58044. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  58045. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  58046. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  58047. }
  58048. if (parsedParticleSystem.preWarmCycles !== undefined) {
  58049. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  58050. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  58051. }
  58052. if (parsedParticleSystem.minInitialRotation !== undefined) {
  58053. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  58054. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  58055. }
  58056. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58057. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58058. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58059. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58060. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58061. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58062. if (parsedParticleSystem.noiseStrength) {
  58063. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  58064. }
  58065. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58066. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58067. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58068. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58069. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58070. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58071. if (parsedParticleSystem.colorGradients) {
  58072. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  58073. var colorGradient = _a[_i];
  58074. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  58075. }
  58076. }
  58077. if (parsedParticleSystem.rampGradients) {
  58078. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  58079. var rampGradient = _c[_b];
  58080. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color1));
  58081. }
  58082. }
  58083. if (parsedParticleSystem.colorRemapGradients) {
  58084. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  58085. var colorRemapGradient = _e[_d];
  58086. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  58087. }
  58088. }
  58089. if (parsedParticleSystem.alphaRemapGradients) {
  58090. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  58091. var alphaRemapGradient = _g[_f];
  58092. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  58093. }
  58094. }
  58095. if (parsedParticleSystem.sizeGradients) {
  58096. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  58097. var sizeGradient = _j[_h];
  58098. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58099. }
  58100. }
  58101. if (parsedParticleSystem.sizeGradients) {
  58102. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  58103. var sizeGradient = _l[_k];
  58104. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58105. }
  58106. }
  58107. if (parsedParticleSystem.angularSpeedGradients) {
  58108. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  58109. var angularSpeedGradient = _o[_m];
  58110. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  58111. }
  58112. }
  58113. if (parsedParticleSystem.velocityGradients) {
  58114. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  58115. var velocityGradient = _q[_p];
  58116. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  58117. }
  58118. }
  58119. if (parsedParticleSystem.dragGradients) {
  58120. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  58121. var dragGradient = _s[_r];
  58122. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  58123. }
  58124. }
  58125. if (parsedParticleSystem.emitRateGradients) {
  58126. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  58127. var emitRateGradient = _u[_t];
  58128. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  58129. }
  58130. }
  58131. if (parsedParticleSystem.startSizeGradients) {
  58132. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  58133. var startSizeGradient = _w[_v];
  58134. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  58135. }
  58136. }
  58137. if (parsedParticleSystem.limitVelocityGradients) {
  58138. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  58139. var limitVelocityGradient = _y[_x];
  58140. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  58141. }
  58142. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  58143. }
  58144. if (parsedParticleSystem.noiseTexture) {
  58145. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  58146. }
  58147. // Emitter
  58148. var emitterType;
  58149. if (parsedParticleSystem.particleEmitterType) {
  58150. switch (parsedParticleSystem.particleEmitterType.type) {
  58151. case "SphereParticleEmitter":
  58152. emitterType = new BABYLON.SphereParticleEmitter();
  58153. break;
  58154. case "SphereDirectedParticleEmitter":
  58155. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58156. break;
  58157. case "ConeEmitter":
  58158. case "ConeParticleEmitter":
  58159. emitterType = new BABYLON.ConeParticleEmitter();
  58160. break;
  58161. case "BoxEmitter":
  58162. case "BoxParticleEmitter":
  58163. default:
  58164. emitterType = new BABYLON.BoxParticleEmitter();
  58165. break;
  58166. }
  58167. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58168. }
  58169. else {
  58170. emitterType = new BABYLON.BoxParticleEmitter();
  58171. emitterType.parse(parsedParticleSystem);
  58172. }
  58173. particleSystem.particleEmitterType = emitterType;
  58174. // Animation sheet
  58175. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  58176. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  58177. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  58178. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  58179. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  58180. };
  58181. /**
  58182. * Parses a JSON object to create a particle system.
  58183. * @param parsedParticleSystem The JSON object to parse
  58184. * @param scene The scene to create the particle system in
  58185. * @param rootUrl The root url to use to load external dependencies like texture
  58186. * @returns the Parsed particle system
  58187. */
  58188. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58189. var name = parsedParticleSystem.name;
  58190. var custom = null;
  58191. var program = null;
  58192. if (parsedParticleSystem.customShader) {
  58193. program = parsedParticleSystem.customShader;
  58194. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58195. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58196. }
  58197. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  58198. particleSystem.customShader = program;
  58199. if (parsedParticleSystem.id) {
  58200. particleSystem.id = parsedParticleSystem.id;
  58201. }
  58202. // Auto start
  58203. if (parsedParticleSystem.preventAutoStart) {
  58204. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  58205. }
  58206. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58207. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  58208. if (!particleSystem.preventAutoStart) {
  58209. particleSystem.start();
  58210. }
  58211. return particleSystem;
  58212. };
  58213. return ParticleSystem;
  58214. }(BABYLON.BaseParticleSystem));
  58215. BABYLON.ParticleSystem = ParticleSystem;
  58216. })(BABYLON || (BABYLON = {}));
  58217. //# sourceMappingURL=babylon.particleSystem.js.map
  58218. var BABYLON;
  58219. (function (BABYLON) {
  58220. /**
  58221. * Particle emitter emitting particles from the inside of a box.
  58222. * It emits the particles randomly between 2 given directions.
  58223. */
  58224. var BoxParticleEmitter = /** @class */ (function () {
  58225. /**
  58226. * Creates a new instance BoxParticleEmitter
  58227. */
  58228. function BoxParticleEmitter() {
  58229. /**
  58230. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58231. */
  58232. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58233. /**
  58234. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58235. */
  58236. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58237. /**
  58238. * 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.
  58239. */
  58240. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  58241. /**
  58242. * 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.
  58243. */
  58244. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  58245. }
  58246. /**
  58247. * Called by the particle System when the direction is computed for the created particle.
  58248. * @param worldMatrix is the world matrix of the particle system
  58249. * @param directionToUpdate is the direction vector to update with the result
  58250. * @param particle is the particle we are computed the direction for
  58251. */
  58252. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58253. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58254. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58255. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58256. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58257. };
  58258. /**
  58259. * Called by the particle System when the position is computed for the created particle.
  58260. * @param worldMatrix is the world matrix of the particle system
  58261. * @param positionToUpdate is the position vector to update with the result
  58262. * @param particle is the particle we are computed the position for
  58263. */
  58264. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58265. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  58266. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  58267. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  58268. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58269. };
  58270. /**
  58271. * Clones the current emitter and returns a copy of it
  58272. * @returns the new emitter
  58273. */
  58274. BoxParticleEmitter.prototype.clone = function () {
  58275. var newOne = new BoxParticleEmitter();
  58276. BABYLON.Tools.DeepCopy(this, newOne);
  58277. return newOne;
  58278. };
  58279. /**
  58280. * Called by the GPUParticleSystem to setup the update shader
  58281. * @param effect defines the update shader
  58282. */
  58283. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  58284. effect.setVector3("direction1", this.direction1);
  58285. effect.setVector3("direction2", this.direction2);
  58286. effect.setVector3("minEmitBox", this.minEmitBox);
  58287. effect.setVector3("maxEmitBox", this.maxEmitBox);
  58288. };
  58289. /**
  58290. * Returns a string to use to update the GPU particles update shader
  58291. * @returns a string containng the defines string
  58292. */
  58293. BoxParticleEmitter.prototype.getEffectDefines = function () {
  58294. return "#define BOXEMITTER";
  58295. };
  58296. /**
  58297. * Returns the string "BoxParticleEmitter"
  58298. * @returns a string containing the class name
  58299. */
  58300. BoxParticleEmitter.prototype.getClassName = function () {
  58301. return "BoxParticleEmitter";
  58302. };
  58303. /**
  58304. * Serializes the particle system to a JSON object.
  58305. * @returns the JSON object
  58306. */
  58307. BoxParticleEmitter.prototype.serialize = function () {
  58308. var serializationObject = {};
  58309. serializationObject.type = this.getClassName();
  58310. serializationObject.direction1 = this.direction1.asArray();
  58311. serializationObject.direction2 = this.direction2.asArray();
  58312. serializationObject.minEmitBox = this.minEmitBox.asArray();
  58313. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  58314. return serializationObject;
  58315. };
  58316. /**
  58317. * Parse properties from a JSON object
  58318. * @param serializationObject defines the JSON object
  58319. */
  58320. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  58321. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58322. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58323. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  58324. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  58325. };
  58326. return BoxParticleEmitter;
  58327. }());
  58328. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  58329. })(BABYLON || (BABYLON = {}));
  58330. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  58331. var BABYLON;
  58332. (function (BABYLON) {
  58333. /**
  58334. * Particle emitter emitting particles from the inside of a cylinder.
  58335. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  58336. */
  58337. var CylinderParticleEmitter = /** @class */ (function () {
  58338. /**
  58339. * Creates a new instance CylinderParticleEmitter
  58340. * @param radius the radius of the emission cylinder (1 by default)
  58341. * @param height the height of the emission cylinder (1 by default)
  58342. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58343. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58344. */
  58345. function CylinderParticleEmitter(
  58346. /**
  58347. * The radius of the emission cylinder.
  58348. */
  58349. radius,
  58350. /**
  58351. * The height of the emission cylinder.
  58352. */
  58353. height,
  58354. /**
  58355. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58356. */
  58357. radiusRange,
  58358. /**
  58359. * How much to randomize the particle direction [0-1].
  58360. */
  58361. directionRandomizer) {
  58362. if (radius === void 0) { radius = 1; }
  58363. if (height === void 0) { height = 1; }
  58364. if (radiusRange === void 0) { radiusRange = 1; }
  58365. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58366. this.radius = radius;
  58367. this.height = height;
  58368. this.radiusRange = radiusRange;
  58369. this.directionRandomizer = directionRandomizer;
  58370. }
  58371. /**
  58372. * Called by the particle System when the direction is computed for the created particle.
  58373. * @param worldMatrix is the world matrix of the particle system
  58374. * @param directionToUpdate is the direction vector to update with the result
  58375. * @param particle is the particle we are computed the direction for
  58376. */
  58377. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58378. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58379. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  58380. var angle = Math.atan2(direction.x, direction.z);
  58381. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58382. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58383. direction.x = Math.sin(angle);
  58384. direction.z = Math.cos(angle);
  58385. direction.normalize();
  58386. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58387. };
  58388. /**
  58389. * Called by the particle System when the position is computed for the created particle.
  58390. * @param worldMatrix is the world matrix of the particle system
  58391. * @param positionToUpdate is the position vector to update with the result
  58392. * @param particle is the particle we are computed the position for
  58393. */
  58394. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58395. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58396. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58397. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58398. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58399. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58400. var xPos = positionRadius * Math.cos(angle);
  58401. var zPos = positionRadius * Math.sin(angle);
  58402. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58403. };
  58404. /**
  58405. * Clones the current emitter and returns a copy of it
  58406. * @returns the new emitter
  58407. */
  58408. CylinderParticleEmitter.prototype.clone = function () {
  58409. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58410. BABYLON.Tools.DeepCopy(this, newOne);
  58411. return newOne;
  58412. };
  58413. /**
  58414. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58415. * @param effect defines the update shader
  58416. */
  58417. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58418. effect.setFloat("radius", this.radius);
  58419. effect.setFloat("height", this.height);
  58420. effect.setFloat("radiusRange", this.radiusRange);
  58421. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58422. };
  58423. /**
  58424. * Returns a string to use to update the GPU particles update shader
  58425. * @returns a string containng the defines string
  58426. */
  58427. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58428. return "#define CYLINDEREMITTER";
  58429. };
  58430. /**
  58431. * Returns the string "CylinderParticleEmitter"
  58432. * @returns a string containing the class name
  58433. */
  58434. CylinderParticleEmitter.prototype.getClassName = function () {
  58435. return "CylinderParticleEmitter";
  58436. };
  58437. /**
  58438. * Serializes the particle system to a JSON object.
  58439. * @returns the JSON object
  58440. */
  58441. CylinderParticleEmitter.prototype.serialize = function () {
  58442. var serializationObject = {};
  58443. serializationObject.type = this.getClassName();
  58444. serializationObject.radius = this.radius;
  58445. serializationObject.height = this.height;
  58446. serializationObject.radiusRange = this.radiusRange;
  58447. serializationObject.directionRandomizer = this.directionRandomizer;
  58448. return serializationObject;
  58449. };
  58450. /**
  58451. * Parse properties from a JSON object
  58452. * @param serializationObject defines the JSON object
  58453. */
  58454. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58455. this.radius = serializationObject.radius;
  58456. this.height = serializationObject.height;
  58457. this.radiusRange = serializationObject.radiusRange;
  58458. this.directionRandomizer = serializationObject.directionRandomizer;
  58459. };
  58460. return CylinderParticleEmitter;
  58461. }());
  58462. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58463. /**
  58464. * Particle emitter emitting particles from the inside of a cylinder.
  58465. * It emits the particles randomly between two vectors.
  58466. */
  58467. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58468. __extends(CylinderDirectedParticleEmitter, _super);
  58469. /**
  58470. * Creates a new instance CylinderDirectedParticleEmitter
  58471. * @param radius the radius of the emission cylinder (1 by default)
  58472. * @param height the height of the emission cylinder (1 by default)
  58473. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58474. * @param direction1 the min limit of the emission direction (up vector by default)
  58475. * @param direction2 the max limit of the emission direction (up vector by default)
  58476. */
  58477. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58478. /**
  58479. * The min limit of the emission direction.
  58480. */
  58481. direction1,
  58482. /**
  58483. * The max limit of the emission direction.
  58484. */
  58485. direction2) {
  58486. if (radius === void 0) { radius = 1; }
  58487. if (height === void 0) { height = 1; }
  58488. if (radiusRange === void 0) { radiusRange = 1; }
  58489. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58490. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58491. var _this = _super.call(this, radius, height, radiusRange) || this;
  58492. _this.direction1 = direction1;
  58493. _this.direction2 = direction2;
  58494. return _this;
  58495. }
  58496. /**
  58497. * Called by the particle System when the direction is computed for the created particle.
  58498. * @param worldMatrix is the world matrix of the particle system
  58499. * @param directionToUpdate is the direction vector to update with the result
  58500. * @param particle is the particle we are computed the direction for
  58501. */
  58502. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58503. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58504. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58505. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58506. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58507. };
  58508. /**
  58509. * Clones the current emitter and returns a copy of it
  58510. * @returns the new emitter
  58511. */
  58512. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58513. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58514. BABYLON.Tools.DeepCopy(this, newOne);
  58515. return newOne;
  58516. };
  58517. /**
  58518. * Called by the GPUParticleSystem to setup the update shader
  58519. * @param effect defines the update shader
  58520. */
  58521. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58522. effect.setFloat("radius", this.radius);
  58523. effect.setFloat("height", this.height);
  58524. effect.setFloat("radiusRange", this.radiusRange);
  58525. effect.setVector3("direction1", this.direction1);
  58526. effect.setVector3("direction2", this.direction2);
  58527. };
  58528. /**
  58529. * Returns a string to use to update the GPU particles update shader
  58530. * @returns a string containng the defines string
  58531. */
  58532. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58533. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58534. };
  58535. /**
  58536. * Returns the string "CylinderDirectedParticleEmitter"
  58537. * @returns a string containing the class name
  58538. */
  58539. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58540. return "CylinderDirectedParticleEmitter";
  58541. };
  58542. /**
  58543. * Serializes the particle system to a JSON object.
  58544. * @returns the JSON object
  58545. */
  58546. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58547. var serializationObject = _super.prototype.serialize.call(this);
  58548. serializationObject.direction1 = this.direction1.asArray();
  58549. serializationObject.direction2 = this.direction2.asArray();
  58550. return serializationObject;
  58551. };
  58552. /**
  58553. * Parse properties from a JSON object
  58554. * @param serializationObject defines the JSON object
  58555. */
  58556. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58557. _super.prototype.parse.call(this, serializationObject);
  58558. this.direction1.copyFrom(serializationObject.direction1);
  58559. this.direction2.copyFrom(serializationObject.direction2);
  58560. };
  58561. return CylinderDirectedParticleEmitter;
  58562. }(CylinderParticleEmitter));
  58563. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58564. })(BABYLON || (BABYLON = {}));
  58565. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58566. var BABYLON;
  58567. (function (BABYLON) {
  58568. /**
  58569. * Particle emitter emitting particles from the inside of a cone.
  58570. * It emits the particles alongside the cone volume from the base to the particle.
  58571. * The emission direction might be randomized.
  58572. */
  58573. var ConeParticleEmitter = /** @class */ (function () {
  58574. /**
  58575. * Creates a new instance ConeParticleEmitter
  58576. * @param radius the radius of the emission cone (1 by default)
  58577. * @param angles the cone base angle (PI by default)
  58578. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58579. */
  58580. function ConeParticleEmitter(radius, angle,
  58581. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58582. directionRandomizer) {
  58583. if (radius === void 0) { radius = 1; }
  58584. if (angle === void 0) { angle = Math.PI; }
  58585. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58586. this.directionRandomizer = directionRandomizer;
  58587. /**
  58588. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58589. */
  58590. this.radiusRange = 1;
  58591. /**
  58592. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58593. */
  58594. this.heightRange = 1;
  58595. /**
  58596. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58597. */
  58598. this.emitFromSpawnPointOnly = false;
  58599. this.angle = angle;
  58600. this.radius = radius;
  58601. }
  58602. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58603. /**
  58604. * Gets or sets the radius of the emission cone
  58605. */
  58606. get: function () {
  58607. return this._radius;
  58608. },
  58609. set: function (value) {
  58610. this._radius = value;
  58611. this._buildHeight();
  58612. },
  58613. enumerable: true,
  58614. configurable: true
  58615. });
  58616. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58617. /**
  58618. * Gets or sets the angle of the emission cone
  58619. */
  58620. get: function () {
  58621. return this._angle;
  58622. },
  58623. set: function (value) {
  58624. this._angle = value;
  58625. this._buildHeight();
  58626. },
  58627. enumerable: true,
  58628. configurable: true
  58629. });
  58630. ConeParticleEmitter.prototype._buildHeight = function () {
  58631. if (this._angle !== 0) {
  58632. this._height = this._radius / Math.tan(this._angle / 2);
  58633. }
  58634. else {
  58635. this._height = 1;
  58636. }
  58637. };
  58638. /**
  58639. * Called by the particle System when the direction is computed for the created particle.
  58640. * @param worldMatrix is the world matrix of the particle system
  58641. * @param directionToUpdate is the direction vector to update with the result
  58642. * @param particle is the particle we are computed the direction for
  58643. */
  58644. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58645. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58646. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58647. }
  58648. else {
  58649. // measure the direction Vector from the emitter to the particle.
  58650. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58651. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58652. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58653. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58654. direction.x += randX;
  58655. direction.y += randY;
  58656. direction.z += randZ;
  58657. direction.normalize();
  58658. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58659. }
  58660. };
  58661. /**
  58662. * Called by the particle System when the position is computed for the created particle.
  58663. * @param worldMatrix is the world matrix of the particle system
  58664. * @param positionToUpdate is the position vector to update with the result
  58665. * @param particle is the particle we are computed the position for
  58666. */
  58667. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58668. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58669. var h;
  58670. if (!this.emitFromSpawnPointOnly) {
  58671. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58672. // Better distribution in a cone at normal angles.
  58673. h = 1 - h * h;
  58674. }
  58675. else {
  58676. h = 0.0001;
  58677. }
  58678. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58679. radius = radius * h;
  58680. var randX = radius * Math.sin(s);
  58681. var randZ = radius * Math.cos(s);
  58682. var randY = h * this._height;
  58683. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58684. };
  58685. /**
  58686. * Clones the current emitter and returns a copy of it
  58687. * @returns the new emitter
  58688. */
  58689. ConeParticleEmitter.prototype.clone = function () {
  58690. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58691. BABYLON.Tools.DeepCopy(this, newOne);
  58692. return newOne;
  58693. };
  58694. /**
  58695. * Called by the GPUParticleSystem to setup the update shader
  58696. * @param effect defines the update shader
  58697. */
  58698. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58699. effect.setFloat2("radius", this._radius, this.radiusRange);
  58700. effect.setFloat("coneAngle", this._angle);
  58701. effect.setFloat2("height", this._height, this.heightRange);
  58702. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58703. };
  58704. /**
  58705. * Returns a string to use to update the GPU particles update shader
  58706. * @returns a string containng the defines string
  58707. */
  58708. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58709. var defines = "#define CONEEMITTER";
  58710. if (this.emitFromSpawnPointOnly) {
  58711. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58712. }
  58713. return defines;
  58714. };
  58715. /**
  58716. * Returns the string "ConeParticleEmitter"
  58717. * @returns a string containing the class name
  58718. */
  58719. ConeParticleEmitter.prototype.getClassName = function () {
  58720. return "ConeParticleEmitter";
  58721. };
  58722. /**
  58723. * Serializes the particle system to a JSON object.
  58724. * @returns the JSON object
  58725. */
  58726. ConeParticleEmitter.prototype.serialize = function () {
  58727. var serializationObject = {};
  58728. serializationObject.type = this.getClassName();
  58729. serializationObject.radius = this._radius;
  58730. serializationObject.angle = this._angle;
  58731. serializationObject.directionRandomizer = this.directionRandomizer;
  58732. return serializationObject;
  58733. };
  58734. /**
  58735. * Parse properties from a JSON object
  58736. * @param serializationObject defines the JSON object
  58737. */
  58738. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58739. this.radius = serializationObject.radius;
  58740. this.angle = serializationObject.angle;
  58741. this.directionRandomizer = serializationObject.directionRandomizer;
  58742. };
  58743. return ConeParticleEmitter;
  58744. }());
  58745. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58746. })(BABYLON || (BABYLON = {}));
  58747. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58748. var BABYLON;
  58749. (function (BABYLON) {
  58750. /**
  58751. * Particle emitter emitting particles from the inside of a sphere.
  58752. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58753. */
  58754. var SphereParticleEmitter = /** @class */ (function () {
  58755. /**
  58756. * Creates a new instance SphereParticleEmitter
  58757. * @param radius the radius of the emission sphere (1 by default)
  58758. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58759. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58760. */
  58761. function SphereParticleEmitter(
  58762. /**
  58763. * The radius of the emission sphere.
  58764. */
  58765. radius,
  58766. /**
  58767. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58768. */
  58769. radiusRange,
  58770. /**
  58771. * How much to randomize the particle direction [0-1].
  58772. */
  58773. directionRandomizer) {
  58774. if (radius === void 0) { radius = 1; }
  58775. if (radiusRange === void 0) { radiusRange = 1; }
  58776. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58777. this.radius = radius;
  58778. this.radiusRange = radiusRange;
  58779. this.directionRandomizer = directionRandomizer;
  58780. }
  58781. /**
  58782. * Called by the particle System when the direction is computed for the created particle.
  58783. * @param worldMatrix is the world matrix of the particle system
  58784. * @param directionToUpdate is the direction vector to update with the result
  58785. * @param particle is the particle we are computed the direction for
  58786. */
  58787. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58788. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58789. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58790. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58791. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58792. direction.x += randX;
  58793. direction.y += randY;
  58794. direction.z += randZ;
  58795. direction.normalize();
  58796. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58797. };
  58798. /**
  58799. * Called by the particle System when the position is computed for the created particle.
  58800. * @param worldMatrix is the world matrix of the particle system
  58801. * @param positionToUpdate is the position vector to update with the result
  58802. * @param particle is the particle we are computed the position for
  58803. */
  58804. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58805. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58806. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58807. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58808. var theta = Math.acos(2 * v - 1);
  58809. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58810. var randY = randRadius * Math.cos(theta);
  58811. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58812. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58813. };
  58814. /**
  58815. * Clones the current emitter and returns a copy of it
  58816. * @returns the new emitter
  58817. */
  58818. SphereParticleEmitter.prototype.clone = function () {
  58819. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58820. BABYLON.Tools.DeepCopy(this, newOne);
  58821. return newOne;
  58822. };
  58823. /**
  58824. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58825. * @param effect defines the update shader
  58826. */
  58827. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58828. effect.setFloat("radius", this.radius);
  58829. effect.setFloat("radiusRange", this.radiusRange);
  58830. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58831. };
  58832. /**
  58833. * Returns a string to use to update the GPU particles update shader
  58834. * @returns a string containng the defines string
  58835. */
  58836. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58837. return "#define SPHEREEMITTER";
  58838. };
  58839. /**
  58840. * Returns the string "SphereParticleEmitter"
  58841. * @returns a string containing the class name
  58842. */
  58843. SphereParticleEmitter.prototype.getClassName = function () {
  58844. return "SphereParticleEmitter";
  58845. };
  58846. /**
  58847. * Serializes the particle system to a JSON object.
  58848. * @returns the JSON object
  58849. */
  58850. SphereParticleEmitter.prototype.serialize = function () {
  58851. var serializationObject = {};
  58852. serializationObject.type = this.getClassName();
  58853. serializationObject.radius = this.radius;
  58854. serializationObject.radiusRange = this.radiusRange;
  58855. serializationObject.directionRandomizer = this.directionRandomizer;
  58856. return serializationObject;
  58857. };
  58858. /**
  58859. * Parse properties from a JSON object
  58860. * @param serializationObject defines the JSON object
  58861. */
  58862. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58863. this.radius = serializationObject.radius;
  58864. this.radiusRange = serializationObject.radiusRange;
  58865. this.directionRandomizer = serializationObject.directionRandomizer;
  58866. };
  58867. return SphereParticleEmitter;
  58868. }());
  58869. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58870. /**
  58871. * Particle emitter emitting particles from the inside of a sphere.
  58872. * It emits the particles randomly between two vectors.
  58873. */
  58874. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58875. __extends(SphereDirectedParticleEmitter, _super);
  58876. /**
  58877. * Creates a new instance SphereDirectedParticleEmitter
  58878. * @param radius the radius of the emission sphere (1 by default)
  58879. * @param direction1 the min limit of the emission direction (up vector by default)
  58880. * @param direction2 the max limit of the emission direction (up vector by default)
  58881. */
  58882. function SphereDirectedParticleEmitter(radius,
  58883. /**
  58884. * The min limit of the emission direction.
  58885. */
  58886. direction1,
  58887. /**
  58888. * The max limit of the emission direction.
  58889. */
  58890. direction2) {
  58891. if (radius === void 0) { radius = 1; }
  58892. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58893. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58894. var _this = _super.call(this, radius) || this;
  58895. _this.direction1 = direction1;
  58896. _this.direction2 = direction2;
  58897. return _this;
  58898. }
  58899. /**
  58900. * Called by the particle System when the direction is computed for the created particle.
  58901. * @param worldMatrix is the world matrix of the particle system
  58902. * @param directionToUpdate is the direction vector to update with the result
  58903. * @param particle is the particle we are computed the direction for
  58904. */
  58905. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58906. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58907. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58908. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58909. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58910. };
  58911. /**
  58912. * Clones the current emitter and returns a copy of it
  58913. * @returns the new emitter
  58914. */
  58915. SphereDirectedParticleEmitter.prototype.clone = function () {
  58916. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58917. BABYLON.Tools.DeepCopy(this, newOne);
  58918. return newOne;
  58919. };
  58920. /**
  58921. * Called by the GPUParticleSystem to setup the update shader
  58922. * @param effect defines the update shader
  58923. */
  58924. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58925. effect.setFloat("radius", this.radius);
  58926. effect.setFloat("radiusRange", this.radiusRange);
  58927. effect.setVector3("direction1", this.direction1);
  58928. effect.setVector3("direction2", this.direction2);
  58929. };
  58930. /**
  58931. * Returns a string to use to update the GPU particles update shader
  58932. * @returns a string containng the defines string
  58933. */
  58934. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58935. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58936. };
  58937. /**
  58938. * Returns the string "SphereDirectedParticleEmitter"
  58939. * @returns a string containing the class name
  58940. */
  58941. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58942. return "SphereDirectedParticleEmitter";
  58943. };
  58944. /**
  58945. * Serializes the particle system to a JSON object.
  58946. * @returns the JSON object
  58947. */
  58948. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58949. var serializationObject = _super.prototype.serialize.call(this);
  58950. serializationObject.direction1 = this.direction1.asArray();
  58951. serializationObject.direction2 = this.direction2.asArray();
  58952. return serializationObject;
  58953. };
  58954. /**
  58955. * Parse properties from a JSON object
  58956. * @param serializationObject defines the JSON object
  58957. */
  58958. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58959. _super.prototype.parse.call(this, serializationObject);
  58960. this.direction1.copyFrom(serializationObject.direction1);
  58961. this.direction2.copyFrom(serializationObject.direction2);
  58962. };
  58963. return SphereDirectedParticleEmitter;
  58964. }(SphereParticleEmitter));
  58965. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58966. })(BABYLON || (BABYLON = {}));
  58967. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58968. var BABYLON;
  58969. (function (BABYLON) {
  58970. /**
  58971. * Particle emitter emitting particles from the inside of a hemisphere.
  58972. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58973. */
  58974. var HemisphericParticleEmitter = /** @class */ (function () {
  58975. /**
  58976. * Creates a new instance HemisphericParticleEmitter
  58977. * @param radius the radius of the emission hemisphere (1 by default)
  58978. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58979. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58980. */
  58981. function HemisphericParticleEmitter(
  58982. /**
  58983. * The radius of the emission hemisphere.
  58984. */
  58985. radius,
  58986. /**
  58987. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58988. */
  58989. radiusRange,
  58990. /**
  58991. * How much to randomize the particle direction [0-1].
  58992. */
  58993. directionRandomizer) {
  58994. if (radius === void 0) { radius = 1; }
  58995. if (radiusRange === void 0) { radiusRange = 1; }
  58996. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58997. this.radius = radius;
  58998. this.radiusRange = radiusRange;
  58999. this.directionRandomizer = directionRandomizer;
  59000. }
  59001. /**
  59002. * Called by the particle System when the direction is computed for the created particle.
  59003. * @param worldMatrix is the world matrix of the particle system
  59004. * @param directionToUpdate is the direction vector to update with the result
  59005. * @param particle is the particle we are computed the direction for
  59006. */
  59007. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59008. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59009. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59010. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59011. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59012. direction.x += randX;
  59013. direction.y += randY;
  59014. direction.z += randZ;
  59015. direction.normalize();
  59016. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59017. };
  59018. /**
  59019. * Called by the particle System when the position is computed for the created particle.
  59020. * @param worldMatrix is the world matrix of the particle system
  59021. * @param positionToUpdate is the position vector to update with the result
  59022. * @param particle is the particle we are computed the position for
  59023. */
  59024. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59025. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  59026. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  59027. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59028. var theta = Math.acos(2 * v - 1);
  59029. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  59030. var randY = randRadius * Math.cos(theta);
  59031. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  59032. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  59033. };
  59034. /**
  59035. * Clones the current emitter and returns a copy of it
  59036. * @returns the new emitter
  59037. */
  59038. HemisphericParticleEmitter.prototype.clone = function () {
  59039. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  59040. BABYLON.Tools.DeepCopy(this, newOne);
  59041. return newOne;
  59042. };
  59043. /**
  59044. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59045. * @param effect defines the update shader
  59046. */
  59047. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  59048. effect.setFloat("radius", this.radius);
  59049. effect.setFloat("radiusRange", this.radiusRange);
  59050. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59051. };
  59052. /**
  59053. * Returns a string to use to update the GPU particles update shader
  59054. * @returns a string containng the defines string
  59055. */
  59056. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  59057. return "#define HEMISPHERICEMITTER";
  59058. };
  59059. /**
  59060. * Returns the string "HemisphericParticleEmitter"
  59061. * @returns a string containing the class name
  59062. */
  59063. HemisphericParticleEmitter.prototype.getClassName = function () {
  59064. return "HemisphericParticleEmitter";
  59065. };
  59066. /**
  59067. * Serializes the particle system to a JSON object.
  59068. * @returns the JSON object
  59069. */
  59070. HemisphericParticleEmitter.prototype.serialize = function () {
  59071. var serializationObject = {};
  59072. serializationObject.type = this.getClassName();
  59073. serializationObject.radius = this.radius;
  59074. serializationObject.radiusRange = this.radiusRange;
  59075. serializationObject.directionRandomizer = this.directionRandomizer;
  59076. return serializationObject;
  59077. };
  59078. /**
  59079. * Parse properties from a JSON object
  59080. * @param serializationObject defines the JSON object
  59081. */
  59082. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  59083. this.radius = serializationObject.radius;
  59084. this.radiusRange = serializationObject.radiusRange;
  59085. this.directionRandomizer = serializationObject.directionRandomizer;
  59086. };
  59087. return HemisphericParticleEmitter;
  59088. }());
  59089. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  59090. })(BABYLON || (BABYLON = {}));
  59091. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  59092. var BABYLON;
  59093. (function (BABYLON) {
  59094. /**
  59095. * Particle emitter emitting particles from a point.
  59096. * It emits the particles randomly between 2 given directions.
  59097. */
  59098. var PointParticleEmitter = /** @class */ (function () {
  59099. /**
  59100. * Creates a new instance PointParticleEmitter
  59101. */
  59102. function PointParticleEmitter() {
  59103. /**
  59104. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59105. */
  59106. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59107. /**
  59108. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59109. */
  59110. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59111. }
  59112. /**
  59113. * Called by the particle System when the direction is computed for the created particle.
  59114. * @param worldMatrix is the world matrix of the particle system
  59115. * @param directionToUpdate is the direction vector to update with the result
  59116. * @param particle is the particle we are computed the direction for
  59117. */
  59118. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59119. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59120. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59121. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59122. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59123. };
  59124. /**
  59125. * Called by the particle System when the position is computed for the created particle.
  59126. * @param worldMatrix is the world matrix of the particle system
  59127. * @param positionToUpdate is the position vector to update with the result
  59128. * @param particle is the particle we are computed the position for
  59129. */
  59130. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59131. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  59132. };
  59133. /**
  59134. * Clones the current emitter and returns a copy of it
  59135. * @returns the new emitter
  59136. */
  59137. PointParticleEmitter.prototype.clone = function () {
  59138. var newOne = new PointParticleEmitter();
  59139. BABYLON.Tools.DeepCopy(this, newOne);
  59140. return newOne;
  59141. };
  59142. /**
  59143. * Called by the GPUParticleSystem to setup the update shader
  59144. * @param effect defines the update shader
  59145. */
  59146. PointParticleEmitter.prototype.applyToShader = function (effect) {
  59147. effect.setVector3("direction1", this.direction1);
  59148. effect.setVector3("direction2", this.direction2);
  59149. };
  59150. /**
  59151. * Returns a string to use to update the GPU particles update shader
  59152. * @returns a string containng the defines string
  59153. */
  59154. PointParticleEmitter.prototype.getEffectDefines = function () {
  59155. return "#define POINTEMITTER";
  59156. };
  59157. /**
  59158. * Returns the string "PointParticleEmitter"
  59159. * @returns a string containing the class name
  59160. */
  59161. PointParticleEmitter.prototype.getClassName = function () {
  59162. return "PointParticleEmitter";
  59163. };
  59164. /**
  59165. * Serializes the particle system to a JSON object.
  59166. * @returns the JSON object
  59167. */
  59168. PointParticleEmitter.prototype.serialize = function () {
  59169. var serializationObject = {};
  59170. serializationObject.type = this.getClassName();
  59171. serializationObject.direction1 = this.direction1.asArray();
  59172. serializationObject.direction2 = this.direction2.asArray();
  59173. return serializationObject;
  59174. };
  59175. /**
  59176. * Parse properties from a JSON object
  59177. * @param serializationObject defines the JSON object
  59178. */
  59179. PointParticleEmitter.prototype.parse = function (serializationObject) {
  59180. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59181. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59182. };
  59183. return PointParticleEmitter;
  59184. }());
  59185. BABYLON.PointParticleEmitter = PointParticleEmitter;
  59186. })(BABYLON || (BABYLON = {}));
  59187. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  59188. var BABYLON;
  59189. (function (BABYLON) {
  59190. // Adds the parsers to the scene parsers.
  59191. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  59192. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  59193. if (!individualParser) {
  59194. return;
  59195. }
  59196. // Particles Systems
  59197. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59198. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59199. var parsedParticleSystem = parsedData.particleSystems[index];
  59200. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  59201. }
  59202. }
  59203. });
  59204. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  59205. if (parsedParticleSystem.activeParticleCount) {
  59206. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59207. return ps;
  59208. }
  59209. else {
  59210. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59211. return ps;
  59212. }
  59213. });
  59214. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  59215. if (uniformsNames === void 0) { uniformsNames = []; }
  59216. if (samplers === void 0) { samplers = []; }
  59217. if (defines === void 0) { defines = ""; }
  59218. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  59219. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  59220. if (defines.indexOf(" BILLBOARD") === -1) {
  59221. defines += "\n#define BILLBOARD\n";
  59222. }
  59223. if (samplers.indexOf("diffuseSampler") === -1) {
  59224. samplers.push("diffuseSampler");
  59225. }
  59226. return this.createEffect({
  59227. vertex: "particles",
  59228. fragmentElement: fragmentName
  59229. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  59230. };
  59231. })(BABYLON || (BABYLON = {}));
  59232. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  59233. var BABYLON;
  59234. (function (BABYLON) {
  59235. /**
  59236. * Type of sub emitter
  59237. */
  59238. var SubEmitterType;
  59239. (function (SubEmitterType) {
  59240. /**
  59241. * Attached to the particle over it's lifetime
  59242. */
  59243. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  59244. /**
  59245. * Created when the particle dies
  59246. */
  59247. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  59248. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  59249. /**
  59250. * Sub emitter class used to emit particles from an existing particle
  59251. */
  59252. var SubEmitter = /** @class */ (function () {
  59253. /**
  59254. * Creates a sub emitter
  59255. * @param particleSystem the particle system to be used by the sub emitter
  59256. */
  59257. function SubEmitter(
  59258. /**
  59259. * the particle system to be used by the sub emitter
  59260. */
  59261. particleSystem) {
  59262. this.particleSystem = particleSystem;
  59263. /**
  59264. * Type of the submitter (Default: END)
  59265. */
  59266. this.type = SubEmitterType.END;
  59267. /**
  59268. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  59269. * Note: This only is supported when using an emitter of type Mesh
  59270. */
  59271. this.inheritDirection = false;
  59272. /**
  59273. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  59274. */
  59275. this.inheritedVelocityAmount = 0;
  59276. }
  59277. /**
  59278. * Clones the sub emitter
  59279. * @returns the cloned sub emitter
  59280. */
  59281. SubEmitter.prototype.clone = function () {
  59282. // Clone particle system
  59283. var emitter = this.particleSystem.emitter;
  59284. if (!emitter) {
  59285. emitter = new BABYLON.Vector3();
  59286. }
  59287. else if (emitter instanceof BABYLON.Vector3) {
  59288. emitter = emitter.clone();
  59289. }
  59290. else if (emitter instanceof BABYLON.AbstractMesh) {
  59291. emitter = new BABYLON.Mesh("", emitter._scene);
  59292. }
  59293. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  59294. // Clone properties
  59295. clone.type = this.type;
  59296. clone.inheritDirection = this.inheritDirection;
  59297. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  59298. clone.particleSystem._disposeEmitterOnDispose = true;
  59299. return clone;
  59300. };
  59301. return SubEmitter;
  59302. }());
  59303. BABYLON.SubEmitter = SubEmitter;
  59304. })(BABYLON || (BABYLON = {}));
  59305. //# sourceMappingURL=babylon.subEmitter.js.map
  59306. var BABYLON;
  59307. (function (BABYLON) {
  59308. var ShaderMaterial = /** @class */ (function (_super) {
  59309. __extends(ShaderMaterial, _super);
  59310. function ShaderMaterial(name, scene, shaderPath, options) {
  59311. var _this = _super.call(this, name, scene) || this;
  59312. _this._textures = {};
  59313. _this._textureArrays = {};
  59314. _this._floats = {};
  59315. _this._ints = {};
  59316. _this._floatsArrays = {};
  59317. _this._colors3 = {};
  59318. _this._colors3Arrays = {};
  59319. _this._colors4 = {};
  59320. _this._vectors2 = {};
  59321. _this._vectors3 = {};
  59322. _this._vectors4 = {};
  59323. _this._matrices = {};
  59324. _this._matrices3x3 = {};
  59325. _this._matrices2x2 = {};
  59326. _this._vectors2Arrays = {};
  59327. _this._vectors3Arrays = {};
  59328. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59329. _this._shaderPath = shaderPath;
  59330. options.needAlphaBlending = options.needAlphaBlending || false;
  59331. options.needAlphaTesting = options.needAlphaTesting || false;
  59332. options.attributes = options.attributes || ["position", "normal", "uv"];
  59333. options.uniforms = options.uniforms || ["worldViewProjection"];
  59334. options.uniformBuffers = options.uniformBuffers || [];
  59335. options.samplers = options.samplers || [];
  59336. options.defines = options.defines || [];
  59337. _this._options = options;
  59338. return _this;
  59339. }
  59340. ShaderMaterial.prototype.getClassName = function () {
  59341. return "ShaderMaterial";
  59342. };
  59343. ShaderMaterial.prototype.needAlphaBlending = function () {
  59344. return this._options.needAlphaBlending;
  59345. };
  59346. ShaderMaterial.prototype.needAlphaTesting = function () {
  59347. return this._options.needAlphaTesting;
  59348. };
  59349. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59350. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59351. this._options.uniforms.push(uniformName);
  59352. }
  59353. };
  59354. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59355. if (this._options.samplers.indexOf(name) === -1) {
  59356. this._options.samplers.push(name);
  59357. }
  59358. this._textures[name] = texture;
  59359. return this;
  59360. };
  59361. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59362. if (this._options.samplers.indexOf(name) === -1) {
  59363. this._options.samplers.push(name);
  59364. }
  59365. this._checkUniform(name);
  59366. this._textureArrays[name] = textures;
  59367. return this;
  59368. };
  59369. ShaderMaterial.prototype.setFloat = function (name, value) {
  59370. this._checkUniform(name);
  59371. this._floats[name] = value;
  59372. return this;
  59373. };
  59374. ShaderMaterial.prototype.setInt = function (name, value) {
  59375. this._checkUniform(name);
  59376. this._ints[name] = value;
  59377. return this;
  59378. };
  59379. ShaderMaterial.prototype.setFloats = function (name, value) {
  59380. this._checkUniform(name);
  59381. this._floatsArrays[name] = value;
  59382. return this;
  59383. };
  59384. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59385. this._checkUniform(name);
  59386. this._colors3[name] = value;
  59387. return this;
  59388. };
  59389. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59390. this._checkUniform(name);
  59391. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59392. color.toArray(arr, arr.length);
  59393. return arr;
  59394. }, []);
  59395. return this;
  59396. };
  59397. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59398. this._checkUniform(name);
  59399. this._colors4[name] = value;
  59400. return this;
  59401. };
  59402. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59403. this._checkUniform(name);
  59404. this._vectors2[name] = value;
  59405. return this;
  59406. };
  59407. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59408. this._checkUniform(name);
  59409. this._vectors3[name] = value;
  59410. return this;
  59411. };
  59412. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59413. this._checkUniform(name);
  59414. this._vectors4[name] = value;
  59415. return this;
  59416. };
  59417. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59418. this._checkUniform(name);
  59419. this._matrices[name] = value;
  59420. return this;
  59421. };
  59422. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59423. this._checkUniform(name);
  59424. this._matrices3x3[name] = value;
  59425. return this;
  59426. };
  59427. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59428. this._checkUniform(name);
  59429. this._matrices2x2[name] = value;
  59430. return this;
  59431. };
  59432. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59433. this._checkUniform(name);
  59434. this._vectors2Arrays[name] = value;
  59435. return this;
  59436. };
  59437. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59438. this._checkUniform(name);
  59439. this._vectors3Arrays[name] = value;
  59440. return this;
  59441. };
  59442. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59443. if (!mesh) {
  59444. return true;
  59445. }
  59446. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59447. return false;
  59448. }
  59449. return false;
  59450. };
  59451. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59452. var scene = this.getScene();
  59453. var engine = scene.getEngine();
  59454. if (!this.checkReadyOnEveryCall) {
  59455. if (this._renderId === scene.getRenderId()) {
  59456. if (this._checkCache(scene, mesh, useInstances)) {
  59457. return true;
  59458. }
  59459. }
  59460. }
  59461. // Instances
  59462. var defines = [];
  59463. var attribs = [];
  59464. var fallbacks = new BABYLON.EffectFallbacks();
  59465. if (useInstances) {
  59466. defines.push("#define INSTANCES");
  59467. }
  59468. for (var index = 0; index < this._options.defines.length; index++) {
  59469. defines.push(this._options.defines[index]);
  59470. }
  59471. for (var index = 0; index < this._options.attributes.length; index++) {
  59472. attribs.push(this._options.attributes[index]);
  59473. }
  59474. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59475. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59476. defines.push("#define VERTEXCOLOR");
  59477. }
  59478. // Bones
  59479. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59480. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59481. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59482. if (mesh.numBoneInfluencers > 4) {
  59483. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59484. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59485. }
  59486. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59487. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59488. fallbacks.addCPUSkinningFallback(0, mesh);
  59489. if (this._options.uniforms.indexOf("mBones") === -1) {
  59490. this._options.uniforms.push("mBones");
  59491. }
  59492. }
  59493. else {
  59494. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59495. }
  59496. // Textures
  59497. for (var name in this._textures) {
  59498. if (!this._textures[name].isReady()) {
  59499. return false;
  59500. }
  59501. }
  59502. // Alpha test
  59503. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59504. defines.push("#define ALPHATEST");
  59505. }
  59506. var previousEffect = this._effect;
  59507. var join = defines.join("\n");
  59508. this._effect = engine.createEffect(this._shaderPath, {
  59509. attributes: attribs,
  59510. uniformsNames: this._options.uniforms,
  59511. uniformBuffersNames: this._options.uniformBuffers,
  59512. samplers: this._options.samplers,
  59513. defines: join,
  59514. fallbacks: fallbacks,
  59515. onCompiled: this.onCompiled,
  59516. onError: this.onError
  59517. }, engine);
  59518. if (!this._effect.isReady()) {
  59519. return false;
  59520. }
  59521. if (previousEffect !== this._effect) {
  59522. scene.resetCachedMaterial();
  59523. }
  59524. this._renderId = scene.getRenderId();
  59525. return true;
  59526. };
  59527. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59528. var scene = this.getScene();
  59529. if (!this._effect) {
  59530. return;
  59531. }
  59532. if (this._options.uniforms.indexOf("world") !== -1) {
  59533. this._effect.setMatrix("world", world);
  59534. }
  59535. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59536. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59537. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59538. }
  59539. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59540. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59541. }
  59542. };
  59543. ShaderMaterial.prototype.bind = function (world, mesh) {
  59544. // Std values
  59545. this.bindOnlyWorldMatrix(world);
  59546. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59547. if (this._options.uniforms.indexOf("view") !== -1) {
  59548. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59549. }
  59550. if (this._options.uniforms.indexOf("projection") !== -1) {
  59551. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59552. }
  59553. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59554. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59555. }
  59556. // Bones
  59557. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59558. var name;
  59559. // Texture
  59560. for (name in this._textures) {
  59561. this._effect.setTexture(name, this._textures[name]);
  59562. }
  59563. // Texture arrays
  59564. for (name in this._textureArrays) {
  59565. this._effect.setTextureArray(name, this._textureArrays[name]);
  59566. }
  59567. // Int
  59568. for (name in this._ints) {
  59569. this._effect.setInt(name, this._ints[name]);
  59570. }
  59571. // Float
  59572. for (name in this._floats) {
  59573. this._effect.setFloat(name, this._floats[name]);
  59574. }
  59575. // Floats
  59576. for (name in this._floatsArrays) {
  59577. this._effect.setArray(name, this._floatsArrays[name]);
  59578. }
  59579. // Color3
  59580. for (name in this._colors3) {
  59581. this._effect.setColor3(name, this._colors3[name]);
  59582. }
  59583. for (name in this._colors3Arrays) {
  59584. this._effect.setArray3(name, this._colors3Arrays[name]);
  59585. }
  59586. // Color4
  59587. for (name in this._colors4) {
  59588. var color = this._colors4[name];
  59589. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59590. }
  59591. // Vector2
  59592. for (name in this._vectors2) {
  59593. this._effect.setVector2(name, this._vectors2[name]);
  59594. }
  59595. // Vector3
  59596. for (name in this._vectors3) {
  59597. this._effect.setVector3(name, this._vectors3[name]);
  59598. }
  59599. // Vector4
  59600. for (name in this._vectors4) {
  59601. this._effect.setVector4(name, this._vectors4[name]);
  59602. }
  59603. // Matrix
  59604. for (name in this._matrices) {
  59605. this._effect.setMatrix(name, this._matrices[name]);
  59606. }
  59607. // Matrix 3x3
  59608. for (name in this._matrices3x3) {
  59609. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59610. }
  59611. // Matrix 2x2
  59612. for (name in this._matrices2x2) {
  59613. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59614. }
  59615. // Vector2Array
  59616. for (name in this._vectors2Arrays) {
  59617. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59618. }
  59619. // Vector3Array
  59620. for (name in this._vectors3Arrays) {
  59621. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59622. }
  59623. }
  59624. this._afterBind(mesh);
  59625. };
  59626. ShaderMaterial.prototype.getActiveTextures = function () {
  59627. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59628. for (var name in this._textures) {
  59629. activeTextures.push(this._textures[name]);
  59630. }
  59631. for (var name in this._textureArrays) {
  59632. var array = this._textureArrays[name];
  59633. for (var index = 0; index < array.length; index++) {
  59634. activeTextures.push(array[index]);
  59635. }
  59636. }
  59637. return activeTextures;
  59638. };
  59639. ShaderMaterial.prototype.hasTexture = function (texture) {
  59640. if (_super.prototype.hasTexture.call(this, texture)) {
  59641. return true;
  59642. }
  59643. for (var name in this._textures) {
  59644. if (this._textures[name] === texture) {
  59645. return true;
  59646. }
  59647. }
  59648. for (var name in this._textureArrays) {
  59649. var array = this._textureArrays[name];
  59650. for (var index = 0; index < array.length; index++) {
  59651. if (array[index] === texture) {
  59652. return true;
  59653. }
  59654. }
  59655. }
  59656. return false;
  59657. };
  59658. ShaderMaterial.prototype.clone = function (name) {
  59659. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59660. return newShaderMaterial;
  59661. };
  59662. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59663. if (forceDisposeTextures) {
  59664. var name;
  59665. for (name in this._textures) {
  59666. this._textures[name].dispose();
  59667. }
  59668. for (name in this._textureArrays) {
  59669. var array = this._textureArrays[name];
  59670. for (var index = 0; index < array.length; index++) {
  59671. array[index].dispose();
  59672. }
  59673. }
  59674. }
  59675. this._textures = {};
  59676. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59677. };
  59678. ShaderMaterial.prototype.serialize = function () {
  59679. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59680. serializationObject.customType = "BABYLON.ShaderMaterial";
  59681. serializationObject.options = this._options;
  59682. serializationObject.shaderPath = this._shaderPath;
  59683. var name;
  59684. // Texture
  59685. serializationObject.textures = {};
  59686. for (name in this._textures) {
  59687. serializationObject.textures[name] = this._textures[name].serialize();
  59688. }
  59689. // Texture arrays
  59690. serializationObject.textureArrays = {};
  59691. for (name in this._textureArrays) {
  59692. serializationObject.textureArrays[name] = [];
  59693. var array = this._textureArrays[name];
  59694. for (var index = 0; index < array.length; index++) {
  59695. serializationObject.textureArrays[name].push(array[index].serialize());
  59696. }
  59697. }
  59698. // Float
  59699. serializationObject.floats = {};
  59700. for (name in this._floats) {
  59701. serializationObject.floats[name] = this._floats[name];
  59702. }
  59703. // Float s
  59704. serializationObject.FloatArrays = {};
  59705. for (name in this._floatsArrays) {
  59706. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59707. }
  59708. // Color3
  59709. serializationObject.colors3 = {};
  59710. for (name in this._colors3) {
  59711. serializationObject.colors3[name] = this._colors3[name].asArray();
  59712. }
  59713. // Color3 array
  59714. serializationObject.colors3Arrays = {};
  59715. for (name in this._colors3Arrays) {
  59716. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59717. }
  59718. // Color4
  59719. serializationObject.colors4 = {};
  59720. for (name in this._colors4) {
  59721. serializationObject.colors4[name] = this._colors4[name].asArray();
  59722. }
  59723. // Vector2
  59724. serializationObject.vectors2 = {};
  59725. for (name in this._vectors2) {
  59726. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59727. }
  59728. // Vector3
  59729. serializationObject.vectors3 = {};
  59730. for (name in this._vectors3) {
  59731. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59732. }
  59733. // Vector4
  59734. serializationObject.vectors4 = {};
  59735. for (name in this._vectors4) {
  59736. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59737. }
  59738. // Matrix
  59739. serializationObject.matrices = {};
  59740. for (name in this._matrices) {
  59741. serializationObject.matrices[name] = this._matrices[name].asArray();
  59742. }
  59743. // Matrix 3x3
  59744. serializationObject.matrices3x3 = {};
  59745. for (name in this._matrices3x3) {
  59746. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59747. }
  59748. // Matrix 2x2
  59749. serializationObject.matrices2x2 = {};
  59750. for (name in this._matrices2x2) {
  59751. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59752. }
  59753. // Vector2Array
  59754. serializationObject.vectors2Arrays = {};
  59755. for (name in this._vectors2Arrays) {
  59756. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59757. }
  59758. // Vector3Array
  59759. serializationObject.vectors3Arrays = {};
  59760. for (name in this._vectors3Arrays) {
  59761. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59762. }
  59763. return serializationObject;
  59764. };
  59765. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59766. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59767. var name;
  59768. // Texture
  59769. for (name in source.textures) {
  59770. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59771. }
  59772. // Texture arrays
  59773. for (name in source.textureArrays) {
  59774. var array = source.textureArrays[name];
  59775. var textureArray = new Array();
  59776. for (var index = 0; index < array.length; index++) {
  59777. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59778. }
  59779. material.setTextureArray(name, textureArray);
  59780. }
  59781. // Float
  59782. for (name in source.floats) {
  59783. material.setFloat(name, source.floats[name]);
  59784. }
  59785. // Float s
  59786. for (name in source.floatsArrays) {
  59787. material.setFloats(name, source.floatsArrays[name]);
  59788. }
  59789. // Color3
  59790. for (name in source.colors3) {
  59791. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59792. }
  59793. // Color3 arrays
  59794. for (name in source.colors3Arrays) {
  59795. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59796. if (i % 3 === 0) {
  59797. arr.push([num]);
  59798. }
  59799. else {
  59800. arr[arr.length - 1].push(num);
  59801. }
  59802. return arr;
  59803. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59804. material.setColor3Array(name, colors);
  59805. }
  59806. // Color4
  59807. for (name in source.colors4) {
  59808. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59809. }
  59810. // Vector2
  59811. for (name in source.vectors2) {
  59812. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59813. }
  59814. // Vector3
  59815. for (name in source.vectors3) {
  59816. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59817. }
  59818. // Vector4
  59819. for (name in source.vectors4) {
  59820. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59821. }
  59822. // Matrix
  59823. for (name in source.matrices) {
  59824. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59825. }
  59826. // Matrix 3x3
  59827. for (name in source.matrices3x3) {
  59828. material.setMatrix3x3(name, source.matrices3x3[name]);
  59829. }
  59830. // Matrix 2x2
  59831. for (name in source.matrices2x2) {
  59832. material.setMatrix2x2(name, source.matrices2x2[name]);
  59833. }
  59834. // Vector2Array
  59835. for (name in source.vectors2Arrays) {
  59836. material.setArray2(name, source.vectors2Arrays[name]);
  59837. }
  59838. // Vector3Array
  59839. for (name in source.vectors3Arrays) {
  59840. material.setArray3(name, source.vectors3Arrays[name]);
  59841. }
  59842. return material;
  59843. };
  59844. return ShaderMaterial;
  59845. }(BABYLON.Material));
  59846. BABYLON.ShaderMaterial = ShaderMaterial;
  59847. })(BABYLON || (BABYLON = {}));
  59848. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59849. var BABYLON;
  59850. (function (BABYLON) {
  59851. var GroundMesh = /** @class */ (function (_super) {
  59852. __extends(GroundMesh, _super);
  59853. function GroundMesh(name, scene) {
  59854. var _this = _super.call(this, name, scene) || this;
  59855. _this.generateOctree = false;
  59856. return _this;
  59857. }
  59858. GroundMesh.prototype.getClassName = function () {
  59859. return "GroundMesh";
  59860. };
  59861. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59862. get: function () {
  59863. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59864. },
  59865. enumerable: true,
  59866. configurable: true
  59867. });
  59868. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59869. get: function () {
  59870. return this._subdivisionsX;
  59871. },
  59872. enumerable: true,
  59873. configurable: true
  59874. });
  59875. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59876. get: function () {
  59877. return this._subdivisionsY;
  59878. },
  59879. enumerable: true,
  59880. configurable: true
  59881. });
  59882. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59883. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59884. this._subdivisionsX = chunksCount;
  59885. this._subdivisionsY = chunksCount;
  59886. this.subdivide(chunksCount);
  59887. // Call the octree system optimization if it is defined.
  59888. var thisAsAny = this;
  59889. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  59890. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59891. }
  59892. };
  59893. /**
  59894. * Returns a height (y) value in the Worl system :
  59895. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59896. * Returns the ground y position if (x, z) are outside the ground surface.
  59897. */
  59898. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59899. var world = this.getWorldMatrix();
  59900. var invMat = BABYLON.Tmp.Matrix[5];
  59901. world.invertToRef(invMat);
  59902. var tmpVect = BABYLON.Tmp.Vector3[8];
  59903. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59904. x = tmpVect.x;
  59905. z = tmpVect.z;
  59906. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59907. return this.position.y;
  59908. }
  59909. if (!this._heightQuads || this._heightQuads.length == 0) {
  59910. this._initHeightQuads();
  59911. this._computeHeightQuads();
  59912. }
  59913. var facet = this._getFacetAt(x, z);
  59914. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59915. // return y in the World system
  59916. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59917. return tmpVect.y;
  59918. };
  59919. /**
  59920. * Returns a normalized vector (Vector3) orthogonal to the ground
  59921. * at the ground coordinates (x, z) expressed in the World system.
  59922. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59923. */
  59924. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59925. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59926. this.getNormalAtCoordinatesToRef(x, z, normal);
  59927. return normal;
  59928. };
  59929. /**
  59930. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59931. * at the ground coordinates (x, z) expressed in the World system.
  59932. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59933. * Returns the GroundMesh.
  59934. */
  59935. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59936. var world = this.getWorldMatrix();
  59937. var tmpMat = BABYLON.Tmp.Matrix[5];
  59938. world.invertToRef(tmpMat);
  59939. var tmpVect = BABYLON.Tmp.Vector3[8];
  59940. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59941. x = tmpVect.x;
  59942. z = tmpVect.z;
  59943. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59944. return this;
  59945. }
  59946. if (!this._heightQuads || this._heightQuads.length == 0) {
  59947. this._initHeightQuads();
  59948. this._computeHeightQuads();
  59949. }
  59950. var facet = this._getFacetAt(x, z);
  59951. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59952. return this;
  59953. };
  59954. /**
  59955. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59956. * if the ground has been updated.
  59957. * This can be used in the render loop.
  59958. * Returns the GroundMesh.
  59959. */
  59960. GroundMesh.prototype.updateCoordinateHeights = function () {
  59961. if (!this._heightQuads || this._heightQuads.length == 0) {
  59962. this._initHeightQuads();
  59963. }
  59964. this._computeHeightQuads();
  59965. return this;
  59966. };
  59967. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59968. GroundMesh.prototype._getFacetAt = function (x, z) {
  59969. // retrieve col and row from x, z coordinates in the ground local system
  59970. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59971. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59972. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59973. var facet;
  59974. if (z < quad.slope.x * x + quad.slope.y) {
  59975. facet = quad.facet1;
  59976. }
  59977. else {
  59978. facet = quad.facet2;
  59979. }
  59980. return facet;
  59981. };
  59982. // Creates and populates the heightMap array with "facet" elements :
  59983. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59984. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59985. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59986. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59987. // Returns the GroundMesh.
  59988. GroundMesh.prototype._initHeightQuads = function () {
  59989. var subdivisionsX = this._subdivisionsX;
  59990. var subdivisionsY = this._subdivisionsY;
  59991. this._heightQuads = new Array();
  59992. for (var row = 0; row < subdivisionsY; row++) {
  59993. for (var col = 0; col < subdivisionsX; col++) {
  59994. 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) };
  59995. this._heightQuads[row * subdivisionsX + col] = quad;
  59996. }
  59997. }
  59998. return this;
  59999. };
  60000. // Compute each quad element values and update the the heightMap array :
  60001. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60002. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60003. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60004. // Returns the GroundMesh.
  60005. GroundMesh.prototype._computeHeightQuads = function () {
  60006. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60007. if (!positions) {
  60008. return this;
  60009. }
  60010. var v1 = BABYLON.Tmp.Vector3[3];
  60011. var v2 = BABYLON.Tmp.Vector3[2];
  60012. var v3 = BABYLON.Tmp.Vector3[1];
  60013. var v4 = BABYLON.Tmp.Vector3[0];
  60014. var v1v2 = BABYLON.Tmp.Vector3[4];
  60015. var v1v3 = BABYLON.Tmp.Vector3[5];
  60016. var v1v4 = BABYLON.Tmp.Vector3[6];
  60017. var norm1 = BABYLON.Tmp.Vector3[7];
  60018. var norm2 = BABYLON.Tmp.Vector3[8];
  60019. var i = 0;
  60020. var j = 0;
  60021. var k = 0;
  60022. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60023. var h = 0;
  60024. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60025. var d2 = 0;
  60026. var subdivisionsX = this._subdivisionsX;
  60027. var subdivisionsY = this._subdivisionsY;
  60028. for (var row = 0; row < subdivisionsY; row++) {
  60029. for (var col = 0; col < subdivisionsX; col++) {
  60030. i = col * 3;
  60031. j = row * (subdivisionsX + 1) * 3;
  60032. k = (row + 1) * (subdivisionsX + 1) * 3;
  60033. v1.x = positions[j + i];
  60034. v1.y = positions[j + i + 1];
  60035. v1.z = positions[j + i + 2];
  60036. v2.x = positions[j + i + 3];
  60037. v2.y = positions[j + i + 4];
  60038. v2.z = positions[j + i + 5];
  60039. v3.x = positions[k + i];
  60040. v3.y = positions[k + i + 1];
  60041. v3.z = positions[k + i + 2];
  60042. v4.x = positions[k + i + 3];
  60043. v4.y = positions[k + i + 4];
  60044. v4.z = positions[k + i + 5];
  60045. // 2D slope V1V4
  60046. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60047. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60048. // facet equations :
  60049. // we compute each facet normal vector
  60050. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60051. // we compute the value d by applying the equation to v1 which belongs to the plane
  60052. // then we store the facet equation in a Vector4
  60053. v2.subtractToRef(v1, v1v2);
  60054. v3.subtractToRef(v1, v1v3);
  60055. v4.subtractToRef(v1, v1v4);
  60056. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60057. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60058. norm1.normalize();
  60059. norm2.normalize();
  60060. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60061. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60062. var quad = this._heightQuads[row * subdivisionsX + col];
  60063. quad.slope.copyFromFloats(cd, h);
  60064. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60065. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60066. }
  60067. }
  60068. return this;
  60069. };
  60070. GroundMesh.prototype.serialize = function (serializationObject) {
  60071. _super.prototype.serialize.call(this, serializationObject);
  60072. serializationObject.subdivisionsX = this._subdivisionsX;
  60073. serializationObject.subdivisionsY = this._subdivisionsY;
  60074. serializationObject.minX = this._minX;
  60075. serializationObject.maxX = this._maxX;
  60076. serializationObject.minZ = this._minZ;
  60077. serializationObject.maxZ = this._maxZ;
  60078. serializationObject.width = this._width;
  60079. serializationObject.height = this._height;
  60080. };
  60081. GroundMesh.Parse = function (parsedMesh, scene) {
  60082. var result = new GroundMesh(parsedMesh.name, scene);
  60083. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60084. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60085. result._minX = parsedMesh.minX;
  60086. result._maxX = parsedMesh.maxX;
  60087. result._minZ = parsedMesh.minZ;
  60088. result._maxZ = parsedMesh.maxZ;
  60089. result._width = parsedMesh.width;
  60090. result._height = parsedMesh.height;
  60091. return result;
  60092. };
  60093. return GroundMesh;
  60094. }(BABYLON.Mesh));
  60095. BABYLON.GroundMesh = GroundMesh;
  60096. })(BABYLON || (BABYLON = {}));
  60097. //# sourceMappingURL=babylon.groundMesh.js.map
  60098. var BABYLON;
  60099. (function (BABYLON) {
  60100. /**
  60101. * Creates an instance based on a source mesh.
  60102. */
  60103. var InstancedMesh = /** @class */ (function (_super) {
  60104. __extends(InstancedMesh, _super);
  60105. function InstancedMesh(name, source) {
  60106. var _this = _super.call(this, name, source.getScene()) || this;
  60107. source.instances.push(_this);
  60108. _this._sourceMesh = source;
  60109. _this.position.copyFrom(source.position);
  60110. _this.rotation.copyFrom(source.rotation);
  60111. _this.scaling.copyFrom(source.scaling);
  60112. if (source.rotationQuaternion) {
  60113. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60114. }
  60115. _this.infiniteDistance = source.infiniteDistance;
  60116. _this.setPivotMatrix(source.getPivotMatrix());
  60117. _this.refreshBoundingInfo();
  60118. _this._syncSubMeshes();
  60119. return _this;
  60120. }
  60121. /**
  60122. * Returns the string "InstancedMesh".
  60123. */
  60124. InstancedMesh.prototype.getClassName = function () {
  60125. return "InstancedMesh";
  60126. };
  60127. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60128. // Methods
  60129. get: function () {
  60130. return this._sourceMesh.receiveShadows;
  60131. },
  60132. enumerable: true,
  60133. configurable: true
  60134. });
  60135. Object.defineProperty(InstancedMesh.prototype, "material", {
  60136. get: function () {
  60137. return this._sourceMesh.material;
  60138. },
  60139. enumerable: true,
  60140. configurable: true
  60141. });
  60142. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60143. get: function () {
  60144. return this._sourceMesh.visibility;
  60145. },
  60146. enumerable: true,
  60147. configurable: true
  60148. });
  60149. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60150. get: function () {
  60151. return this._sourceMesh.skeleton;
  60152. },
  60153. enumerable: true,
  60154. configurable: true
  60155. });
  60156. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60157. get: function () {
  60158. return this._sourceMesh.renderingGroupId;
  60159. },
  60160. set: function (value) {
  60161. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60162. return;
  60163. }
  60164. //no-op with warning
  60165. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60166. },
  60167. enumerable: true,
  60168. configurable: true
  60169. });
  60170. /**
  60171. * Returns the total number of vertices (integer).
  60172. */
  60173. InstancedMesh.prototype.getTotalVertices = function () {
  60174. return this._sourceMesh.getTotalVertices();
  60175. };
  60176. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60177. get: function () {
  60178. return this._sourceMesh;
  60179. },
  60180. enumerable: true,
  60181. configurable: true
  60182. });
  60183. /**
  60184. * Is this node ready to be used/rendered
  60185. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60186. * @return {boolean} is it ready
  60187. */
  60188. InstancedMesh.prototype.isReady = function (completeCheck) {
  60189. if (completeCheck === void 0) { completeCheck = false; }
  60190. return this._sourceMesh.isReady(completeCheck, true);
  60191. };
  60192. /**
  60193. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60194. */
  60195. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60196. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60197. };
  60198. /**
  60199. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60200. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60201. * The `data` are either a numeric array either a Float32Array.
  60202. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60203. * 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).
  60204. * Note that a new underlying VertexBuffer object is created each call.
  60205. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60206. *
  60207. * Possible `kind` values :
  60208. * - BABYLON.VertexBuffer.PositionKind
  60209. * - BABYLON.VertexBuffer.UVKind
  60210. * - BABYLON.VertexBuffer.UV2Kind
  60211. * - BABYLON.VertexBuffer.UV3Kind
  60212. * - BABYLON.VertexBuffer.UV4Kind
  60213. * - BABYLON.VertexBuffer.UV5Kind
  60214. * - BABYLON.VertexBuffer.UV6Kind
  60215. * - BABYLON.VertexBuffer.ColorKind
  60216. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60217. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60218. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60219. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60220. *
  60221. * Returns the Mesh.
  60222. */
  60223. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60224. if (this.sourceMesh) {
  60225. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60226. }
  60227. return this.sourceMesh;
  60228. };
  60229. /**
  60230. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60231. * If the mesh has no geometry, it is simply returned as it is.
  60232. * The `data` are either a numeric array either a Float32Array.
  60233. * No new underlying VertexBuffer object is created.
  60234. * 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.
  60235. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60236. *
  60237. * Possible `kind` values :
  60238. * - BABYLON.VertexBuffer.PositionKind
  60239. * - BABYLON.VertexBuffer.UVKind
  60240. * - BABYLON.VertexBuffer.UV2Kind
  60241. * - BABYLON.VertexBuffer.UV3Kind
  60242. * - BABYLON.VertexBuffer.UV4Kind
  60243. * - BABYLON.VertexBuffer.UV5Kind
  60244. * - BABYLON.VertexBuffer.UV6Kind
  60245. * - BABYLON.VertexBuffer.ColorKind
  60246. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60247. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60248. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60249. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60250. *
  60251. * Returns the Mesh.
  60252. */
  60253. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60254. if (this.sourceMesh) {
  60255. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60256. }
  60257. return this.sourceMesh;
  60258. };
  60259. /**
  60260. * Sets the mesh indices.
  60261. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60262. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60263. * This method creates a new index buffer each call.
  60264. * Returns the Mesh.
  60265. */
  60266. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60267. if (totalVertices === void 0) { totalVertices = null; }
  60268. if (this.sourceMesh) {
  60269. this.sourceMesh.setIndices(indices, totalVertices);
  60270. }
  60271. return this.sourceMesh;
  60272. };
  60273. /**
  60274. * Boolean : True if the mesh owns the requested kind of data.
  60275. */
  60276. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60277. return this._sourceMesh.isVerticesDataPresent(kind);
  60278. };
  60279. /**
  60280. * Returns an array of indices (IndicesArray).
  60281. */
  60282. InstancedMesh.prototype.getIndices = function () {
  60283. return this._sourceMesh.getIndices();
  60284. };
  60285. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60286. get: function () {
  60287. return this._sourceMesh._positions;
  60288. },
  60289. enumerable: true,
  60290. configurable: true
  60291. });
  60292. /**
  60293. * Sets a new updated BoundingInfo to the mesh.
  60294. * Returns the mesh.
  60295. */
  60296. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60297. var meshBB = this._sourceMesh.getBoundingInfo();
  60298. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60299. this._updateBoundingInfo();
  60300. return this;
  60301. };
  60302. /** @hidden */
  60303. InstancedMesh.prototype._preActivate = function () {
  60304. if (this._currentLOD) {
  60305. this._currentLOD._preActivate();
  60306. }
  60307. return this;
  60308. };
  60309. /** @hidden */
  60310. InstancedMesh.prototype._activate = function (renderId) {
  60311. if (this._currentLOD) {
  60312. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60313. }
  60314. return this;
  60315. };
  60316. /**
  60317. * Returns the current associated LOD AbstractMesh.
  60318. */
  60319. InstancedMesh.prototype.getLOD = function (camera) {
  60320. if (!camera) {
  60321. return this;
  60322. }
  60323. var boundingInfo = this.getBoundingInfo();
  60324. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60325. if (this._currentLOD === this.sourceMesh) {
  60326. return this;
  60327. }
  60328. return this._currentLOD;
  60329. };
  60330. /** @hidden */
  60331. InstancedMesh.prototype._syncSubMeshes = function () {
  60332. this.releaseSubMeshes();
  60333. if (this._sourceMesh.subMeshes) {
  60334. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60335. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60336. }
  60337. }
  60338. return this;
  60339. };
  60340. /** @hidden */
  60341. InstancedMesh.prototype._generatePointsArray = function () {
  60342. return this._sourceMesh._generatePointsArray();
  60343. };
  60344. /**
  60345. * Creates a new InstancedMesh from the current mesh.
  60346. * - name (string) : the cloned mesh name
  60347. * - newParent (optional Node) : the optional Node to parent the clone to.
  60348. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60349. *
  60350. * Returns the clone.
  60351. */
  60352. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60353. var result = this._sourceMesh.createInstance(name);
  60354. // Deep copy
  60355. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60356. // Bounding info
  60357. this.refreshBoundingInfo();
  60358. // Parent
  60359. if (newParent) {
  60360. result.parent = newParent;
  60361. }
  60362. if (!doNotCloneChildren) {
  60363. // Children
  60364. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60365. var mesh = this.getScene().meshes[index];
  60366. if (mesh.parent === this) {
  60367. mesh.clone(mesh.name, result);
  60368. }
  60369. }
  60370. }
  60371. result.computeWorldMatrix(true);
  60372. return result;
  60373. };
  60374. /**
  60375. * Disposes the InstancedMesh.
  60376. * Returns nothing.
  60377. */
  60378. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60379. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60380. // Remove from mesh
  60381. var index = this._sourceMesh.instances.indexOf(this);
  60382. this._sourceMesh.instances.splice(index, 1);
  60383. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60384. };
  60385. return InstancedMesh;
  60386. }(BABYLON.AbstractMesh));
  60387. BABYLON.InstancedMesh = InstancedMesh;
  60388. })(BABYLON || (BABYLON = {}));
  60389. //# sourceMappingURL=babylon.instancedMesh.js.map
  60390. var BABYLON;
  60391. (function (BABYLON) {
  60392. var LinesMesh = /** @class */ (function (_super) {
  60393. __extends(LinesMesh, _super);
  60394. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60395. if (scene === void 0) { scene = null; }
  60396. if (parent === void 0) { parent = null; }
  60397. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60398. _this.useVertexColor = useVertexColor;
  60399. _this.useVertexAlpha = useVertexAlpha;
  60400. _this.color = new BABYLON.Color3(1, 1, 1);
  60401. _this.alpha = 1;
  60402. if (source) {
  60403. _this.color = source.color.clone();
  60404. _this.alpha = source.alpha;
  60405. _this.useVertexColor = source.useVertexColor;
  60406. _this.useVertexAlpha = source.useVertexAlpha;
  60407. }
  60408. _this._intersectionThreshold = 0.1;
  60409. var defines = [];
  60410. var options = {
  60411. attributes: [BABYLON.VertexBuffer.PositionKind],
  60412. uniforms: ["world", "viewProjection"],
  60413. needAlphaBlending: true,
  60414. defines: defines
  60415. };
  60416. if (useVertexAlpha === false) {
  60417. options.needAlphaBlending = false;
  60418. }
  60419. if (!useVertexColor) {
  60420. options.uniforms.push("color");
  60421. }
  60422. else {
  60423. options.defines.push("#define VERTEXCOLOR");
  60424. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60425. }
  60426. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60427. return _this;
  60428. }
  60429. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60430. /**
  60431. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60432. * This margin is expressed in world space coordinates, so its value may vary.
  60433. * Default value is 0.1
  60434. * @returns the intersection Threshold value.
  60435. */
  60436. get: function () {
  60437. return this._intersectionThreshold;
  60438. },
  60439. /**
  60440. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60441. * This margin is expressed in world space coordinates, so its value may vary.
  60442. * @param value the new threshold to apply
  60443. */
  60444. set: function (value) {
  60445. if (this._intersectionThreshold === value) {
  60446. return;
  60447. }
  60448. this._intersectionThreshold = value;
  60449. if (this.geometry) {
  60450. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60451. }
  60452. },
  60453. enumerable: true,
  60454. configurable: true
  60455. });
  60456. /**
  60457. * Returns the string "LineMesh"
  60458. */
  60459. LinesMesh.prototype.getClassName = function () {
  60460. return "LinesMesh";
  60461. };
  60462. Object.defineProperty(LinesMesh.prototype, "material", {
  60463. /**
  60464. * @hidden
  60465. */
  60466. get: function () {
  60467. return this._colorShader;
  60468. },
  60469. /**
  60470. * @hidden
  60471. */
  60472. set: function (value) {
  60473. // Do nothing
  60474. },
  60475. enumerable: true,
  60476. configurable: true
  60477. });
  60478. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60479. /**
  60480. * @hidden
  60481. */
  60482. get: function () {
  60483. return false;
  60484. },
  60485. enumerable: true,
  60486. configurable: true
  60487. });
  60488. LinesMesh.prototype.createInstance = function (name) {
  60489. throw new Error("LinesMeshes do not support createInstance.");
  60490. };
  60491. /** @hidden */
  60492. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60493. if (!this._geometry) {
  60494. return this;
  60495. }
  60496. // VBOs
  60497. this._geometry._bind(this._colorShader.getEffect());
  60498. // Color
  60499. if (!this.useVertexColor) {
  60500. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60501. }
  60502. return this;
  60503. };
  60504. /** @hidden */
  60505. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60506. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60507. return this;
  60508. }
  60509. var engine = this.getScene().getEngine();
  60510. // Draw order
  60511. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60512. return this;
  60513. };
  60514. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60515. this._colorShader.dispose();
  60516. _super.prototype.dispose.call(this, doNotRecurse);
  60517. };
  60518. /**
  60519. * Returns a new LineMesh object cloned from the current one.
  60520. */
  60521. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60522. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60523. };
  60524. return LinesMesh;
  60525. }(BABYLON.Mesh));
  60526. BABYLON.LinesMesh = LinesMesh;
  60527. })(BABYLON || (BABYLON = {}));
  60528. //# sourceMappingURL=babylon.linesMesh.js.map
  60529. var BABYLON;
  60530. (function (BABYLON) {
  60531. /**
  60532. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60533. * The underlying implementation relies on an associative array to ensure the best performances.
  60534. * The value can be anything including 'null' but except 'undefined'
  60535. */
  60536. var StringDictionary = /** @class */ (function () {
  60537. function StringDictionary() {
  60538. this._count = 0;
  60539. this._data = {};
  60540. }
  60541. /**
  60542. * This will clear this dictionary and copy the content from the 'source' one.
  60543. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60544. * @param source the dictionary to take the content from and copy to this dictionary
  60545. */
  60546. StringDictionary.prototype.copyFrom = function (source) {
  60547. var _this = this;
  60548. this.clear();
  60549. source.forEach(function (t, v) { return _this.add(t, v); });
  60550. };
  60551. /**
  60552. * Get a value based from its key
  60553. * @param key the given key to get the matching value from
  60554. * @return the value if found, otherwise undefined is returned
  60555. */
  60556. StringDictionary.prototype.get = function (key) {
  60557. var val = this._data[key];
  60558. if (val !== undefined) {
  60559. return val;
  60560. }
  60561. return undefined;
  60562. };
  60563. /**
  60564. * Get a value from its key or add it if it doesn't exist.
  60565. * This method will ensure you that a given key/data will be present in the dictionary.
  60566. * @param key the given key to get the matching value from
  60567. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60568. * The factory will only be invoked if there's no data for the given key.
  60569. * @return the value corresponding to the key.
  60570. */
  60571. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60572. var val = this.get(key);
  60573. if (val !== undefined) {
  60574. return val;
  60575. }
  60576. val = factory(key);
  60577. if (val) {
  60578. this.add(key, val);
  60579. }
  60580. return val;
  60581. };
  60582. /**
  60583. * Get a value from its key if present in the dictionary otherwise add it
  60584. * @param key the key to get the value from
  60585. * @param val if there's no such key/value pair in the dictionary add it with this value
  60586. * @return the value corresponding to the key
  60587. */
  60588. StringDictionary.prototype.getOrAdd = function (key, val) {
  60589. var curVal = this.get(key);
  60590. if (curVal !== undefined) {
  60591. return curVal;
  60592. }
  60593. this.add(key, val);
  60594. return val;
  60595. };
  60596. /**
  60597. * Check if there's a given key in the dictionary
  60598. * @param key the key to check for
  60599. * @return true if the key is present, false otherwise
  60600. */
  60601. StringDictionary.prototype.contains = function (key) {
  60602. return this._data[key] !== undefined;
  60603. };
  60604. /**
  60605. * Add a new key and its corresponding value
  60606. * @param key the key to add
  60607. * @param value the value corresponding to the key
  60608. * @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
  60609. */
  60610. StringDictionary.prototype.add = function (key, value) {
  60611. if (this._data[key] !== undefined) {
  60612. return false;
  60613. }
  60614. this._data[key] = value;
  60615. ++this._count;
  60616. return true;
  60617. };
  60618. StringDictionary.prototype.set = function (key, value) {
  60619. if (this._data[key] === undefined) {
  60620. return false;
  60621. }
  60622. this._data[key] = value;
  60623. return true;
  60624. };
  60625. /**
  60626. * Get the element of the given key and remove it from the dictionary
  60627. * @param key
  60628. */
  60629. StringDictionary.prototype.getAndRemove = function (key) {
  60630. var val = this.get(key);
  60631. if (val !== undefined) {
  60632. delete this._data[key];
  60633. --this._count;
  60634. return val;
  60635. }
  60636. return null;
  60637. };
  60638. /**
  60639. * Remove a key/value from the dictionary.
  60640. * @param key the key to remove
  60641. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60642. */
  60643. StringDictionary.prototype.remove = function (key) {
  60644. if (this.contains(key)) {
  60645. delete this._data[key];
  60646. --this._count;
  60647. return true;
  60648. }
  60649. return false;
  60650. };
  60651. /**
  60652. * Clear the whole content of the dictionary
  60653. */
  60654. StringDictionary.prototype.clear = function () {
  60655. this._data = {};
  60656. this._count = 0;
  60657. };
  60658. Object.defineProperty(StringDictionary.prototype, "count", {
  60659. get: function () {
  60660. return this._count;
  60661. },
  60662. enumerable: true,
  60663. configurable: true
  60664. });
  60665. /**
  60666. * Execute a callback on each key/val of the dictionary.
  60667. * Note that you can remove any element in this dictionary in the callback implementation
  60668. * @param callback the callback to execute on a given key/value pair
  60669. */
  60670. StringDictionary.prototype.forEach = function (callback) {
  60671. for (var cur in this._data) {
  60672. var val = this._data[cur];
  60673. callback(cur, val);
  60674. }
  60675. };
  60676. /**
  60677. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60678. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60679. * Note that you can remove any element in this dictionary in the callback implementation
  60680. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60681. */
  60682. StringDictionary.prototype.first = function (callback) {
  60683. for (var cur in this._data) {
  60684. var val = this._data[cur];
  60685. var res = callback(cur, val);
  60686. if (res) {
  60687. return res;
  60688. }
  60689. }
  60690. return null;
  60691. };
  60692. return StringDictionary;
  60693. }());
  60694. BABYLON.StringDictionary = StringDictionary;
  60695. })(BABYLON || (BABYLON = {}));
  60696. //# sourceMappingURL=babylon.stringDictionary.js.map
  60697. var BABYLON;
  60698. (function (BABYLON) {
  60699. var Debug;
  60700. (function (Debug) {
  60701. /**
  60702. * Class used to render a debug view of a given skeleton
  60703. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60704. */
  60705. var SkeletonViewer = /** @class */ (function () {
  60706. /**
  60707. * Creates a new SkeletonViewer
  60708. * @param skeleton defines the skeleton to render
  60709. * @param mesh defines the mesh attached to the skeleton
  60710. * @param scene defines the hosting scene
  60711. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60712. * @param renderingGroupId defines the rendering group id to use with the viewer
  60713. */
  60714. function SkeletonViewer(
  60715. /** defines the skeleton to render */
  60716. skeleton,
  60717. /** defines the mesh attached to the skeleton */
  60718. mesh, scene,
  60719. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60720. autoUpdateBonesMatrices,
  60721. /** defines the rendering group id to use with the viewer */
  60722. renderingGroupId) {
  60723. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60724. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60725. this.skeleton = skeleton;
  60726. this.mesh = mesh;
  60727. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60728. this.renderingGroupId = renderingGroupId;
  60729. /** Gets or sets the color used to render the skeleton */
  60730. this.color = BABYLON.Color3.White();
  60731. this._debugLines = new Array();
  60732. this._isEnabled = false;
  60733. this._scene = scene;
  60734. this.update();
  60735. this._renderFunction = this.update.bind(this);
  60736. }
  60737. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60738. get: function () {
  60739. return this._isEnabled;
  60740. },
  60741. /** Gets or sets a boolean indicating if the viewer is enabled */
  60742. set: function (value) {
  60743. if (this._isEnabled === value) {
  60744. return;
  60745. }
  60746. this._isEnabled = value;
  60747. if (value) {
  60748. this._scene.registerBeforeRender(this._renderFunction);
  60749. }
  60750. else {
  60751. this._scene.unregisterBeforeRender(this._renderFunction);
  60752. }
  60753. },
  60754. enumerable: true,
  60755. configurable: true
  60756. });
  60757. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60758. if (x === void 0) { x = 0; }
  60759. if (y === void 0) { y = 0; }
  60760. if (z === void 0) { z = 0; }
  60761. var tmat = BABYLON.Tmp.Matrix[0];
  60762. var parentBone = bone.getParent();
  60763. tmat.copyFrom(bone.getLocalMatrix());
  60764. if (x !== 0 || y !== 0 || z !== 0) {
  60765. var tmat2 = BABYLON.Tmp.Matrix[1];
  60766. BABYLON.Matrix.IdentityToRef(tmat2);
  60767. tmat2.m[12] = x;
  60768. tmat2.m[13] = y;
  60769. tmat2.m[14] = z;
  60770. tmat2.multiplyToRef(tmat, tmat);
  60771. }
  60772. if (parentBone) {
  60773. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60774. }
  60775. tmat.multiplyToRef(meshMat, tmat);
  60776. position.x = tmat.m[12];
  60777. position.y = tmat.m[13];
  60778. position.z = tmat.m[14];
  60779. };
  60780. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60781. var len = bones.length;
  60782. var meshPos = this.mesh.position;
  60783. for (var i = 0; i < len; i++) {
  60784. var bone = bones[i];
  60785. var points = this._debugLines[i];
  60786. if (!points) {
  60787. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60788. this._debugLines[i] = points;
  60789. }
  60790. this._getBonePosition(points[0], bone, meshMat);
  60791. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60792. points[0].subtractInPlace(meshPos);
  60793. points[1].subtractInPlace(meshPos);
  60794. }
  60795. };
  60796. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60797. var len = bones.length;
  60798. var boneNum = 0;
  60799. var meshPos = this.mesh.position;
  60800. for (var i = len - 1; i >= 0; i--) {
  60801. var childBone = bones[i];
  60802. var parentBone = childBone.getParent();
  60803. if (!parentBone) {
  60804. continue;
  60805. }
  60806. var points = this._debugLines[boneNum];
  60807. if (!points) {
  60808. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60809. this._debugLines[boneNum] = points;
  60810. }
  60811. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60812. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60813. points[0].subtractInPlace(meshPos);
  60814. points[1].subtractInPlace(meshPos);
  60815. boneNum++;
  60816. }
  60817. };
  60818. /** Update the viewer to sync with current skeleton state */
  60819. SkeletonViewer.prototype.update = function () {
  60820. if (this.autoUpdateBonesMatrices) {
  60821. this.skeleton.computeAbsoluteTransforms();
  60822. }
  60823. if (this.skeleton.bones[0].length === undefined) {
  60824. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60825. }
  60826. else {
  60827. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60828. }
  60829. if (!this._debugMesh) {
  60830. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60831. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60832. }
  60833. else {
  60834. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60835. }
  60836. this._debugMesh.position.copyFrom(this.mesh.position);
  60837. this._debugMesh.color = this.color;
  60838. };
  60839. /** Release associated resources */
  60840. SkeletonViewer.prototype.dispose = function () {
  60841. if (this._debugMesh) {
  60842. this.isEnabled = false;
  60843. this._debugMesh.dispose();
  60844. this._debugMesh = null;
  60845. }
  60846. };
  60847. return SkeletonViewer;
  60848. }());
  60849. Debug.SkeletonViewer = SkeletonViewer;
  60850. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60851. })(BABYLON || (BABYLON = {}));
  60852. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60853. /**
  60854. * Module Debug contains the (visual) components to debug a scene correctly
  60855. */
  60856. var BABYLON;
  60857. (function (BABYLON) {
  60858. var Debug;
  60859. (function (Debug) {
  60860. /**
  60861. * The Axes viewer will show 3 axes in a specific point in space
  60862. */
  60863. var AxesViewer = /** @class */ (function () {
  60864. /**
  60865. * Creates a new AxesViewer
  60866. * @param scene defines the hosting scene
  60867. * @param scaleLines defines a number used to scale line length (1 by default)
  60868. */
  60869. function AxesViewer(scene, scaleLines) {
  60870. if (scaleLines === void 0) { scaleLines = 1; }
  60871. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60872. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60873. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60874. /**
  60875. * Gets or sets a number used to scale line length
  60876. */
  60877. this.scaleLines = 1;
  60878. this.scaleLines = scaleLines;
  60879. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60880. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60881. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60882. this._xmesh.renderingGroupId = 2;
  60883. this._ymesh.renderingGroupId = 2;
  60884. this._zmesh.renderingGroupId = 2;
  60885. this._xmesh.material.checkReadyOnlyOnce = true;
  60886. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60887. this._ymesh.material.checkReadyOnlyOnce = true;
  60888. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60889. this._zmesh.material.checkReadyOnlyOnce = true;
  60890. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60891. this.scene = scene;
  60892. }
  60893. /**
  60894. * Force the viewer to update
  60895. * @param position defines the position of the viewer
  60896. * @param xaxis defines the x axis of the viewer
  60897. * @param yaxis defines the y axis of the viewer
  60898. * @param zaxis defines the z axis of the viewer
  60899. */
  60900. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60901. var scaleLines = this.scaleLines;
  60902. if (this._xmesh) {
  60903. this._xmesh.position.copyFrom(position);
  60904. }
  60905. if (this._ymesh) {
  60906. this._ymesh.position.copyFrom(position);
  60907. }
  60908. if (this._zmesh) {
  60909. this._zmesh.position.copyFrom(position);
  60910. }
  60911. var point2 = this._xline[1];
  60912. point2.x = xaxis.x * scaleLines;
  60913. point2.y = xaxis.y * scaleLines;
  60914. point2.z = xaxis.z * scaleLines;
  60915. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60916. point2 = this._yline[1];
  60917. point2.x = yaxis.x * scaleLines;
  60918. point2.y = yaxis.y * scaleLines;
  60919. point2.z = yaxis.z * scaleLines;
  60920. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60921. point2 = this._zline[1];
  60922. point2.x = zaxis.x * scaleLines;
  60923. point2.y = zaxis.y * scaleLines;
  60924. point2.z = zaxis.z * scaleLines;
  60925. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60926. };
  60927. /** Releases resources */
  60928. AxesViewer.prototype.dispose = function () {
  60929. if (this._xmesh) {
  60930. this._xmesh.dispose();
  60931. }
  60932. if (this._ymesh) {
  60933. this._ymesh.dispose();
  60934. }
  60935. if (this._zmesh) {
  60936. this._zmesh.dispose();
  60937. }
  60938. this._xmesh = null;
  60939. this._ymesh = null;
  60940. this._zmesh = null;
  60941. this.scene = null;
  60942. };
  60943. return AxesViewer;
  60944. }());
  60945. Debug.AxesViewer = AxesViewer;
  60946. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60947. })(BABYLON || (BABYLON = {}));
  60948. //# sourceMappingURL=babylon.axesViewer.js.map
  60949. var BABYLON;
  60950. (function (BABYLON) {
  60951. var Debug;
  60952. (function (Debug) {
  60953. /**
  60954. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60955. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60956. */
  60957. var BoneAxesViewer = /** @class */ (function (_super) {
  60958. __extends(BoneAxesViewer, _super);
  60959. /**
  60960. * Creates a new BoneAxesViewer
  60961. * @param scene defines the hosting scene
  60962. * @param bone defines the target bone
  60963. * @param mesh defines the target mesh
  60964. * @param scaleLines defines a scaling factor for line length (1 by default)
  60965. */
  60966. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60967. if (scaleLines === void 0) { scaleLines = 1; }
  60968. var _this = _super.call(this, scene, scaleLines) || this;
  60969. /** Gets current position */
  60970. _this.pos = BABYLON.Vector3.Zero();
  60971. /** Gets direction of X axis */
  60972. _this.xaxis = BABYLON.Vector3.Zero();
  60973. /** Gets direction of Y axis */
  60974. _this.yaxis = BABYLON.Vector3.Zero();
  60975. /** Gets direction of Z axis */
  60976. _this.zaxis = BABYLON.Vector3.Zero();
  60977. _this.mesh = mesh;
  60978. _this.bone = bone;
  60979. return _this;
  60980. }
  60981. /**
  60982. * Force the viewer to update
  60983. */
  60984. BoneAxesViewer.prototype.update = function () {
  60985. if (!this.mesh || !this.bone) {
  60986. return;
  60987. }
  60988. var bone = this.bone;
  60989. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60990. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60991. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60992. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60993. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60994. };
  60995. /** Releases resources */
  60996. BoneAxesViewer.prototype.dispose = function () {
  60997. if (this.mesh) {
  60998. this.mesh = null;
  60999. this.bone = null;
  61000. _super.prototype.dispose.call(this);
  61001. }
  61002. };
  61003. return BoneAxesViewer;
  61004. }(Debug.AxesViewer));
  61005. Debug.BoneAxesViewer = BoneAxesViewer;
  61006. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61007. })(BABYLON || (BABYLON = {}));
  61008. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  61009. var BABYLON;
  61010. (function (BABYLON) {
  61011. var RayHelper = /** @class */ (function () {
  61012. function RayHelper(ray) {
  61013. this.ray = ray;
  61014. }
  61015. RayHelper.CreateAndShow = function (ray, scene, color) {
  61016. var helper = new RayHelper(ray);
  61017. helper.show(scene, color);
  61018. return helper;
  61019. };
  61020. RayHelper.prototype.show = function (scene, color) {
  61021. if (!this._renderFunction && this.ray) {
  61022. var ray = this.ray;
  61023. this._renderFunction = this._render.bind(this);
  61024. this._scene = scene;
  61025. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  61026. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  61027. if (this._renderFunction) {
  61028. this._scene.registerBeforeRender(this._renderFunction);
  61029. }
  61030. }
  61031. if (color && this._renderLine) {
  61032. this._renderLine.color.copyFrom(color);
  61033. }
  61034. };
  61035. RayHelper.prototype.hide = function () {
  61036. if (this._renderFunction && this._scene) {
  61037. this._scene.unregisterBeforeRender(this._renderFunction);
  61038. this._scene = null;
  61039. this._renderFunction = null;
  61040. if (this._renderLine) {
  61041. this._renderLine.dispose();
  61042. this._renderLine = null;
  61043. }
  61044. this._renderPoints = [];
  61045. }
  61046. };
  61047. RayHelper.prototype._render = function () {
  61048. var ray = this.ray;
  61049. if (!ray) {
  61050. return;
  61051. }
  61052. var point = this._renderPoints[1];
  61053. var len = Math.min(ray.length, 1000000);
  61054. point.copyFrom(ray.direction);
  61055. point.scaleInPlace(len);
  61056. point.addInPlace(ray.origin);
  61057. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  61058. };
  61059. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  61060. this._attachedToMesh = mesh;
  61061. var ray = this.ray;
  61062. if (!ray) {
  61063. return;
  61064. }
  61065. if (!ray.direction) {
  61066. ray.direction = BABYLON.Vector3.Zero();
  61067. }
  61068. if (!ray.origin) {
  61069. ray.origin = BABYLON.Vector3.Zero();
  61070. }
  61071. if (length) {
  61072. ray.length = length;
  61073. }
  61074. if (!meshSpaceOrigin) {
  61075. meshSpaceOrigin = BABYLON.Vector3.Zero();
  61076. }
  61077. if (!meshSpaceDirection) {
  61078. // -1 so that this will work with Mesh.lookAt
  61079. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61080. }
  61081. if (!this._meshSpaceDirection) {
  61082. this._meshSpaceDirection = meshSpaceDirection.clone();
  61083. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61084. }
  61085. else {
  61086. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61087. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61088. }
  61089. if (!this._updateToMeshFunction) {
  61090. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61091. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61092. }
  61093. this._updateToMesh();
  61094. };
  61095. RayHelper.prototype.detachFromMesh = function () {
  61096. if (this._attachedToMesh) {
  61097. if (this._updateToMeshFunction) {
  61098. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61099. }
  61100. this._attachedToMesh = null;
  61101. this._updateToMeshFunction = null;
  61102. }
  61103. };
  61104. RayHelper.prototype._updateToMesh = function () {
  61105. var ray = this.ray;
  61106. if (!this._attachedToMesh || !ray) {
  61107. return;
  61108. }
  61109. if (this._attachedToMesh._isDisposed) {
  61110. this.detachFromMesh();
  61111. return;
  61112. }
  61113. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61114. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61115. };
  61116. RayHelper.prototype.dispose = function () {
  61117. this.hide();
  61118. this.detachFromMesh();
  61119. this.ray = null;
  61120. };
  61121. return RayHelper;
  61122. }());
  61123. BABYLON.RayHelper = RayHelper;
  61124. })(BABYLON || (BABYLON = {}));
  61125. //# sourceMappingURL=babylon.rayHelper.js.map
  61126. var BABYLON;
  61127. (function (BABYLON) {
  61128. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  61129. get: function () {
  61130. if (!this._debugLayer) {
  61131. this._debugLayer = new DebugLayer(this);
  61132. }
  61133. return this._debugLayer;
  61134. },
  61135. enumerable: true,
  61136. configurable: true
  61137. });
  61138. var DebugLayer = /** @class */ (function () {
  61139. function DebugLayer(scene) {
  61140. var _this = this;
  61141. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61142. this.onPropertyChangedObservable = new BABYLON.Observable();
  61143. this._scene = scene;
  61144. this._scene.onDisposeObservable.add(function () {
  61145. // Debug layer
  61146. if (_this._scene._debugLayer) {
  61147. _this._scene._debugLayer.hide();
  61148. }
  61149. });
  61150. }
  61151. /** Creates the inspector window. */
  61152. DebugLayer.prototype._createInspector = function (config) {
  61153. if (config === void 0) { config = {}; }
  61154. var popup = config.popup || false;
  61155. var initialTab = config.initialTab || 0;
  61156. var parentElement = config.parentElement || null;
  61157. if (!this._inspector) {
  61158. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61159. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61160. } // else nothing to do as instance is already created
  61161. };
  61162. DebugLayer.prototype.isVisible = function () {
  61163. if (!this._inspector) {
  61164. return false;
  61165. }
  61166. return true;
  61167. };
  61168. DebugLayer.prototype.hide = function () {
  61169. if (this._inspector) {
  61170. try {
  61171. this._inspector.dispose();
  61172. }
  61173. catch (e) {
  61174. // If the inspector has been removed directly from the inspector tool
  61175. }
  61176. this.onPropertyChangedObservable.clear();
  61177. this._inspector = null;
  61178. }
  61179. };
  61180. /**
  61181. *
  61182. * Launch the debugLayer.
  61183. *
  61184. * initialTab:
  61185. * | Value | Tab Name |
  61186. * | --- | --- |
  61187. * | 0 | Scene |
  61188. * | 1 | Console |
  61189. * | 2 | Stats |
  61190. * | 3 | Textures |
  61191. * | 4 | Mesh |
  61192. * | 5 | Light |
  61193. * | 6 | Material |
  61194. * | 7 | GLTF |
  61195. * | 8 | GUI |
  61196. * | 9 | Physics |
  61197. * | 10 | Camera |
  61198. * | 11 | Audio |
  61199. *
  61200. */
  61201. DebugLayer.prototype.show = function (config) {
  61202. if (config === void 0) { config = {}; }
  61203. if (typeof this.BJSINSPECTOR == 'undefined') {
  61204. // Load inspector and add it to the DOM
  61205. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61206. }
  61207. else {
  61208. // Otherwise creates the inspector
  61209. this._createInspector(config);
  61210. }
  61211. };
  61212. /**
  61213. * Gets the active tab
  61214. * @return the index of the active tab or -1 if the inspector is hidden
  61215. */
  61216. DebugLayer.prototype.getActiveTab = function () {
  61217. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  61218. };
  61219. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61220. return DebugLayer;
  61221. }());
  61222. BABYLON.DebugLayer = DebugLayer;
  61223. })(BABYLON || (BABYLON = {}));
  61224. //# sourceMappingURL=babylon.debugLayer.js.map
  61225. var BABYLON;
  61226. (function (BABYLON) {
  61227. var Debug;
  61228. (function (Debug) {
  61229. /**
  61230. * Used to show the physics impostor around the specific mesh
  61231. */
  61232. var PhysicsViewer = /** @class */ (function () {
  61233. /**
  61234. * Creates a new PhysicsViewer
  61235. * @param scene defines the hosting scene
  61236. */
  61237. function PhysicsViewer(scene) {
  61238. /** @hidden */
  61239. this._impostors = [];
  61240. /** @hidden */
  61241. this._meshes = [];
  61242. /** @hidden */
  61243. this._numMeshes = 0;
  61244. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61245. var physicEngine = this._scene.getPhysicsEngine();
  61246. if (physicEngine) {
  61247. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  61248. }
  61249. }
  61250. /** @hidden */
  61251. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61252. var plugin = this._physicsEnginePlugin;
  61253. for (var i = 0; i < this._numMeshes; i++) {
  61254. var impostor = this._impostors[i];
  61255. if (!impostor) {
  61256. continue;
  61257. }
  61258. if (impostor.isDisposed) {
  61259. this.hideImpostor(this._impostors[i--]);
  61260. }
  61261. else {
  61262. var mesh = this._meshes[i];
  61263. if (mesh && plugin) {
  61264. plugin.syncMeshWithImpostor(mesh, impostor);
  61265. }
  61266. }
  61267. }
  61268. };
  61269. /**
  61270. * Renders a specified physic impostor
  61271. * @param impostor defines the impostor to render
  61272. */
  61273. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61274. if (!this._scene) {
  61275. return;
  61276. }
  61277. for (var i = 0; i < this._numMeshes; i++) {
  61278. if (this._impostors[i] == impostor) {
  61279. return;
  61280. }
  61281. }
  61282. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61283. if (debugMesh) {
  61284. this._impostors[this._numMeshes] = impostor;
  61285. this._meshes[this._numMeshes] = debugMesh;
  61286. if (this._numMeshes === 0) {
  61287. this._renderFunction = this._updateDebugMeshes.bind(this);
  61288. this._scene.registerBeforeRender(this._renderFunction);
  61289. }
  61290. this._numMeshes++;
  61291. }
  61292. };
  61293. /**
  61294. * Hides a specified physic impostor
  61295. * @param impostor defines the impostor to hide
  61296. */
  61297. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61298. if (!impostor || !this._scene) {
  61299. return;
  61300. }
  61301. var removed = false;
  61302. for (var i = 0; i < this._numMeshes; i++) {
  61303. if (this._impostors[i] == impostor) {
  61304. var mesh = this._meshes[i];
  61305. if (!mesh) {
  61306. continue;
  61307. }
  61308. this._scene.removeMesh(mesh);
  61309. mesh.dispose();
  61310. this._numMeshes--;
  61311. if (this._numMeshes > 0) {
  61312. this._meshes[i] = this._meshes[this._numMeshes];
  61313. this._impostors[i] = this._impostors[this._numMeshes];
  61314. this._meshes[this._numMeshes] = null;
  61315. this._impostors[this._numMeshes] = null;
  61316. }
  61317. else {
  61318. this._meshes[0] = null;
  61319. this._impostors[0] = null;
  61320. }
  61321. removed = true;
  61322. break;
  61323. }
  61324. }
  61325. if (removed && this._numMeshes === 0) {
  61326. this._scene.unregisterBeforeRender(this._renderFunction);
  61327. }
  61328. };
  61329. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61330. if (!this._debugMaterial) {
  61331. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61332. this._debugMaterial.wireframe = true;
  61333. }
  61334. return this._debugMaterial;
  61335. };
  61336. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61337. if (!this._debugBoxMesh) {
  61338. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61339. this._debugBoxMesh.renderingGroupId = 1;
  61340. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61341. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61342. scene.removeMesh(this._debugBoxMesh);
  61343. }
  61344. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61345. };
  61346. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61347. if (!this._debugSphereMesh) {
  61348. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61349. this._debugSphereMesh.renderingGroupId = 1;
  61350. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61351. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61352. scene.removeMesh(this._debugSphereMesh);
  61353. }
  61354. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61355. };
  61356. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61357. var mesh = null;
  61358. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61359. mesh = this._getDebugBoxMesh(scene);
  61360. impostor.getBoxSizeToRef(mesh.scaling);
  61361. }
  61362. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61363. mesh = this._getDebugSphereMesh(scene);
  61364. var radius = impostor.getRadius();
  61365. mesh.scaling.x = radius * 2;
  61366. mesh.scaling.y = radius * 2;
  61367. mesh.scaling.z = radius * 2;
  61368. }
  61369. return mesh;
  61370. };
  61371. /** Releases all resources */
  61372. PhysicsViewer.prototype.dispose = function () {
  61373. for (var i = 0; i < this._numMeshes; i++) {
  61374. this.hideImpostor(this._impostors[i]);
  61375. }
  61376. if (this._debugBoxMesh) {
  61377. this._debugBoxMesh.dispose();
  61378. }
  61379. if (this._debugSphereMesh) {
  61380. this._debugSphereMesh.dispose();
  61381. }
  61382. if (this._debugMaterial) {
  61383. this._debugMaterial.dispose();
  61384. }
  61385. this._impostors.length = 0;
  61386. this._scene = null;
  61387. this._physicsEnginePlugin = null;
  61388. };
  61389. return PhysicsViewer;
  61390. }());
  61391. Debug.PhysicsViewer = PhysicsViewer;
  61392. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61393. })(BABYLON || (BABYLON = {}));
  61394. //# sourceMappingURL=babylon.physicsViewer.js.map
  61395. var BABYLON;
  61396. (function (BABYLON) {
  61397. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  61398. get: function () {
  61399. return this._forceShowBoundingBoxes || false;
  61400. },
  61401. set: function (value) {
  61402. this._forceShowBoundingBoxes = value;
  61403. // Lazyly creates a BB renderer if needed.
  61404. if (value) {
  61405. this.getBoundingBoxRenderer();
  61406. }
  61407. },
  61408. enumerable: true,
  61409. configurable: true
  61410. });
  61411. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  61412. if (!this._boundingBoxRenderer) {
  61413. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  61414. }
  61415. return this._boundingBoxRenderer;
  61416. };
  61417. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  61418. get: function () {
  61419. return this._showBoundingBox || false;
  61420. },
  61421. set: function (value) {
  61422. this._showBoundingBox = value;
  61423. // Lazyly creates a BB renderer if needed.
  61424. if (value) {
  61425. this.getScene().getBoundingBoxRenderer();
  61426. }
  61427. },
  61428. enumerable: true,
  61429. configurable: true
  61430. });
  61431. var BoundingBoxRenderer = /** @class */ (function () {
  61432. function BoundingBoxRenderer(scene) {
  61433. /**
  61434. * The component name helpfull to identify the component in the list of scene components.
  61435. */
  61436. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  61437. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61438. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61439. this.showBackLines = true;
  61440. this.renderList = new BABYLON.SmartArray(32);
  61441. this._vertexBuffers = {};
  61442. this.scene = scene;
  61443. scene._addComponent(this);
  61444. }
  61445. /**
  61446. * Registers the component in a given scene
  61447. */
  61448. BoundingBoxRenderer.prototype.register = function () {
  61449. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  61450. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  61451. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  61452. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  61453. };
  61454. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  61455. if (mesh.showSubMeshesBoundingBox) {
  61456. var boundingInfo = subMesh.getBoundingInfo();
  61457. if (boundingInfo !== null && boundingInfo !== undefined) {
  61458. this.renderList.push(boundingInfo.boundingBox);
  61459. }
  61460. }
  61461. };
  61462. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  61463. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  61464. var boundingInfo = sourceMesh.getBoundingInfo();
  61465. this.renderList.push(boundingInfo.boundingBox);
  61466. }
  61467. };
  61468. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61469. if (this._colorShader) {
  61470. return;
  61471. }
  61472. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  61473. attributes: [BABYLON.VertexBuffer.PositionKind],
  61474. uniforms: ["world", "viewProjection", "color"]
  61475. });
  61476. var engine = this.scene.getEngine();
  61477. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61478. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61479. this._createIndexBuffer();
  61480. };
  61481. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61482. var engine = this.scene.getEngine();
  61483. 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]);
  61484. };
  61485. /**
  61486. * Rebuilds the elements related to this component in case of
  61487. * context lost for instance.
  61488. */
  61489. BoundingBoxRenderer.prototype.rebuild = function () {
  61490. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61491. if (vb) {
  61492. vb._rebuild();
  61493. }
  61494. this._createIndexBuffer();
  61495. };
  61496. BoundingBoxRenderer.prototype.reset = function () {
  61497. this.renderList.reset();
  61498. };
  61499. BoundingBoxRenderer.prototype.render = function () {
  61500. if (this.renderList.length === 0) {
  61501. return;
  61502. }
  61503. this._prepareRessources();
  61504. if (!this._colorShader.isReady()) {
  61505. return;
  61506. }
  61507. var engine = this.scene.getEngine();
  61508. engine.setDepthWrite(false);
  61509. this._colorShader._preBind();
  61510. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61511. var boundingBox = this.renderList.data[boundingBoxIndex];
  61512. var min = boundingBox.minimum;
  61513. var max = boundingBox.maximum;
  61514. var diff = max.subtract(min);
  61515. var median = min.add(diff.scale(0.5));
  61516. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61517. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61518. .multiply(boundingBox.getWorldMatrix());
  61519. // VBOs
  61520. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61521. if (this.showBackLines) {
  61522. // Back
  61523. engine.setDepthFunctionToGreaterOrEqual();
  61524. this.scene.resetCachedMaterial();
  61525. this._colorShader.setColor4("color", this.backColor.toColor4());
  61526. this._colorShader.bind(worldMatrix);
  61527. // Draw order
  61528. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61529. }
  61530. // Front
  61531. engine.setDepthFunctionToLess();
  61532. this.scene.resetCachedMaterial();
  61533. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61534. this._colorShader.bind(worldMatrix);
  61535. // Draw order
  61536. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61537. }
  61538. this._colorShader.unbind();
  61539. engine.setDepthFunctionToLessOrEqual();
  61540. engine.setDepthWrite(true);
  61541. };
  61542. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61543. this._prepareRessources();
  61544. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61545. return;
  61546. }
  61547. var engine = this.scene.getEngine();
  61548. engine.setDepthWrite(false);
  61549. engine.setColorWrite(false);
  61550. this._colorShader._preBind();
  61551. var boundingBox = mesh._boundingInfo.boundingBox;
  61552. var min = boundingBox.minimum;
  61553. var max = boundingBox.maximum;
  61554. var diff = max.subtract(min);
  61555. var median = min.add(diff.scale(0.5));
  61556. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61557. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61558. .multiply(boundingBox.getWorldMatrix());
  61559. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61560. engine.setDepthFunctionToLess();
  61561. this.scene.resetCachedMaterial();
  61562. this._colorShader.bind(worldMatrix);
  61563. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61564. this._colorShader.unbind();
  61565. engine.setDepthFunctionToLessOrEqual();
  61566. engine.setDepthWrite(true);
  61567. engine.setColorWrite(true);
  61568. };
  61569. BoundingBoxRenderer.prototype.dispose = function () {
  61570. if (!this._colorShader) {
  61571. return;
  61572. }
  61573. this.renderList.dispose();
  61574. this._colorShader.dispose();
  61575. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61576. if (buffer) {
  61577. buffer.dispose();
  61578. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61579. }
  61580. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61581. };
  61582. return BoundingBoxRenderer;
  61583. }());
  61584. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61585. })(BABYLON || (BABYLON = {}));
  61586. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61587. var BABYLON;
  61588. (function (BABYLON) {
  61589. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61590. return this._gl.createTransformFeedback();
  61591. };
  61592. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61593. this._gl.deleteTransformFeedback(value);
  61594. };
  61595. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61596. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61597. };
  61598. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61599. if (usePoints === void 0) { usePoints = true; }
  61600. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61601. };
  61602. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61603. this._gl.endTransformFeedback();
  61604. };
  61605. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61606. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61607. };
  61608. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61609. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61610. };
  61611. })(BABYLON || (BABYLON = {}));
  61612. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61613. var BABYLON;
  61614. (function (BABYLON) {
  61615. /**
  61616. * This represents a GPU particle system in Babylon
  61617. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61618. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61619. */
  61620. var GPUParticleSystem = /** @class */ (function (_super) {
  61621. __extends(GPUParticleSystem, _super);
  61622. /**
  61623. * Instantiates a GPU particle system.
  61624. * 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.
  61625. * @param name The name of the particle system
  61626. * @param options The options used to create the system
  61627. * @param scene The scene the particle system belongs to
  61628. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61629. */
  61630. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61631. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61632. var _this = _super.call(this, name) || this;
  61633. /**
  61634. * The layer mask we are rendering the particles through.
  61635. */
  61636. _this.layerMask = 0x0FFFFFFF;
  61637. _this._accumulatedCount = 0;
  61638. _this._targetIndex = 0;
  61639. _this._currentRenderId = -1;
  61640. _this._started = false;
  61641. _this._stopped = false;
  61642. _this._timeDelta = 0;
  61643. _this._attributesStrideSize = 21;
  61644. _this._actualFrame = 0;
  61645. _this._rawTextureWidth = 256;
  61646. /**
  61647. * An event triggered when the system is disposed.
  61648. */
  61649. _this.onDisposeObservable = new BABYLON.Observable();
  61650. /**
  61651. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61652. * to override the particles.
  61653. */
  61654. _this.forceDepthWrite = false;
  61655. _this._preWarmDone = false;
  61656. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61657. // Setup the default processing configuration to the scene.
  61658. _this._attachImageProcessingConfiguration(null);
  61659. _this._engine = _this._scene.getEngine();
  61660. if (!options.randomTextureSize) {
  61661. delete options.randomTextureSize;
  61662. }
  61663. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61664. var optionsAsNumber = options;
  61665. if (isFinite(optionsAsNumber)) {
  61666. fullOptions.capacity = optionsAsNumber;
  61667. }
  61668. _this._capacity = fullOptions.capacity;
  61669. _this._activeCount = fullOptions.capacity;
  61670. _this._currentActiveCount = 0;
  61671. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61672. _this._scene.particleSystems.push(_this);
  61673. _this._updateEffectOptions = {
  61674. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset"],
  61675. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61676. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61677. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61678. uniformBuffersNames: [],
  61679. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61680. defines: "",
  61681. fallbacks: null,
  61682. onCompiled: null,
  61683. onError: null,
  61684. indexParameters: null,
  61685. maxSimultaneousLights: 0,
  61686. transformFeedbackVaryings: []
  61687. };
  61688. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61689. // Random data
  61690. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61691. var d = [];
  61692. for (var i = 0; i < maxTextureSize; ++i) {
  61693. d.push(Math.random());
  61694. d.push(Math.random());
  61695. d.push(Math.random());
  61696. d.push(Math.random());
  61697. }
  61698. _this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  61699. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61700. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61701. d = [];
  61702. for (var i = 0; i < maxTextureSize; ++i) {
  61703. d.push(Math.random());
  61704. d.push(Math.random());
  61705. d.push(Math.random());
  61706. d.push(Math.random());
  61707. }
  61708. _this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  61709. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61710. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61711. _this._randomTextureSize = maxTextureSize;
  61712. return _this;
  61713. }
  61714. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61715. /**
  61716. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61717. */
  61718. get: function () {
  61719. if (!BABYLON.Engine.LastCreatedEngine) {
  61720. return false;
  61721. }
  61722. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61723. },
  61724. enumerable: true,
  61725. configurable: true
  61726. });
  61727. /**
  61728. * Gets the maximum number of particles active at the same time.
  61729. * @returns The max number of active particles.
  61730. */
  61731. GPUParticleSystem.prototype.getCapacity = function () {
  61732. return this._capacity;
  61733. };
  61734. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61735. /**
  61736. * Gets or set the number of active particles
  61737. */
  61738. get: function () {
  61739. return this._activeCount;
  61740. },
  61741. set: function (value) {
  61742. this._activeCount = Math.min(value, this._capacity);
  61743. },
  61744. enumerable: true,
  61745. configurable: true
  61746. });
  61747. /**
  61748. * Is this system ready to be used/rendered
  61749. * @return true if the system is ready
  61750. */
  61751. GPUParticleSystem.prototype.isReady = function () {
  61752. if (!this._updateEffect) {
  61753. this._recreateUpdateEffect();
  61754. this._recreateRenderEffect();
  61755. return false;
  61756. }
  61757. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61758. return false;
  61759. }
  61760. return true;
  61761. };
  61762. /**
  61763. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61764. * @returns True if it has been started, otherwise false.
  61765. */
  61766. GPUParticleSystem.prototype.isStarted = function () {
  61767. return this._started;
  61768. };
  61769. /**
  61770. * Starts the particle system and begins to emit
  61771. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  61772. */
  61773. GPUParticleSystem.prototype.start = function (delay) {
  61774. var _this = this;
  61775. if (delay === void 0) { delay = 0; }
  61776. if (delay) {
  61777. setTimeout(function () {
  61778. _this.start(0);
  61779. }, delay);
  61780. return;
  61781. }
  61782. this._started = true;
  61783. this._stopped = false;
  61784. this._preWarmDone = false;
  61785. };
  61786. /**
  61787. * Stops the particle system.
  61788. */
  61789. GPUParticleSystem.prototype.stop = function () {
  61790. this._stopped = true;
  61791. };
  61792. /**
  61793. * Remove all active particles
  61794. */
  61795. GPUParticleSystem.prototype.reset = function () {
  61796. this._releaseBuffers();
  61797. this._releaseVAOs();
  61798. this._currentActiveCount = 0;
  61799. this._targetIndex = 0;
  61800. };
  61801. /**
  61802. * Returns the string "GPUParticleSystem"
  61803. * @returns a string containing the class name
  61804. */
  61805. GPUParticleSystem.prototype.getClassName = function () {
  61806. return "GPUParticleSystem";
  61807. };
  61808. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61809. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  61810. this._releaseBuffers();
  61811. return this;
  61812. };
  61813. /**
  61814. * Adds a new color gradient
  61815. * @param gradient defines the gradient to use (between 0 and 1)
  61816. * @param color defines the color to affect to the specified gradient
  61817. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61818. * @returns the current particle system
  61819. */
  61820. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61821. if (!this._colorGradients) {
  61822. this._colorGradients = [];
  61823. }
  61824. var colorGradient = new BABYLON.ColorGradient();
  61825. colorGradient.gradient = gradient;
  61826. colorGradient.color1 = color1;
  61827. this._colorGradients.push(colorGradient);
  61828. this._colorGradients.sort(function (a, b) {
  61829. if (a.gradient < b.gradient) {
  61830. return -1;
  61831. }
  61832. else if (a.gradient > b.gradient) {
  61833. return 1;
  61834. }
  61835. return 0;
  61836. });
  61837. if (this._colorGradientsTexture) {
  61838. this._colorGradientsTexture.dispose();
  61839. this._colorGradientsTexture = null;
  61840. }
  61841. this._releaseBuffers();
  61842. return this;
  61843. };
  61844. /**
  61845. * Remove a specific color gradient
  61846. * @param gradient defines the gradient to remove
  61847. * @returns the current particle system
  61848. */
  61849. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61850. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  61851. this._colorGradientsTexture = null;
  61852. return this;
  61853. };
  61854. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61855. var valueGradient = new BABYLON.FactorGradient();
  61856. valueGradient.gradient = gradient;
  61857. valueGradient.factor1 = factor;
  61858. factorGradients.push(valueGradient);
  61859. factorGradients.sort(function (a, b) {
  61860. if (a.gradient < b.gradient) {
  61861. return -1;
  61862. }
  61863. else if (a.gradient > b.gradient) {
  61864. return 1;
  61865. }
  61866. return 0;
  61867. });
  61868. this._releaseBuffers();
  61869. };
  61870. /**
  61871. * Adds a new size gradient
  61872. * @param gradient defines the gradient to use (between 0 and 1)
  61873. * @param factor defines the size factor to affect to the specified gradient
  61874. * @returns the current particle system
  61875. */
  61876. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61877. if (!this._sizeGradients) {
  61878. this._sizeGradients = [];
  61879. }
  61880. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61881. if (this._sizeGradientsTexture) {
  61882. this._sizeGradientsTexture.dispose();
  61883. this._sizeGradientsTexture = null;
  61884. }
  61885. this._releaseBuffers();
  61886. return this;
  61887. };
  61888. /**
  61889. * Remove a specific size gradient
  61890. * @param gradient defines the gradient to remove
  61891. * @returns the current particle system
  61892. */
  61893. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61894. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61895. this._sizeGradientsTexture = null;
  61896. return this;
  61897. };
  61898. /**
  61899. * Adds a new angular speed gradient
  61900. * @param gradient defines the gradient to use (between 0 and 1)
  61901. * @param factor defines the angular speed to affect to the specified gradient
  61902. * @returns the current particle system
  61903. */
  61904. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61905. if (!this._angularSpeedGradients) {
  61906. this._angularSpeedGradients = [];
  61907. }
  61908. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61909. if (this._angularSpeedGradientsTexture) {
  61910. this._angularSpeedGradientsTexture.dispose();
  61911. this._angularSpeedGradientsTexture = null;
  61912. }
  61913. this._releaseBuffers();
  61914. return this;
  61915. };
  61916. /**
  61917. * Remove a specific angular speed gradient
  61918. * @param gradient defines the gradient to remove
  61919. * @returns the current particle system
  61920. */
  61921. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61922. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61923. this._angularSpeedGradientsTexture = null;
  61924. return this;
  61925. };
  61926. /**
  61927. * Adds a new velocity gradient
  61928. * @param gradient defines the gradient to use (between 0 and 1)
  61929. * @param factor defines the velocity to affect to the specified gradient
  61930. * @returns the current particle system
  61931. */
  61932. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61933. if (!this._velocityGradients) {
  61934. this._velocityGradients = [];
  61935. }
  61936. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61937. if (this._velocityGradientsTexture) {
  61938. this._velocityGradientsTexture.dispose();
  61939. this._velocityGradientsTexture = null;
  61940. }
  61941. this._releaseBuffers();
  61942. return this;
  61943. };
  61944. /**
  61945. * Remove a specific velocity gradient
  61946. * @param gradient defines the gradient to remove
  61947. * @returns the current particle system
  61948. */
  61949. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61950. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61951. this._velocityGradientsTexture = null;
  61952. return this;
  61953. };
  61954. /**
  61955. * Adds a new limit velocity gradient
  61956. * @param gradient defines the gradient to use (between 0 and 1)
  61957. * @param factor defines the limit velocity value to affect to the specified gradient
  61958. * @returns the current particle system
  61959. */
  61960. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61961. if (!this._limitVelocityGradients) {
  61962. this._limitVelocityGradients = [];
  61963. }
  61964. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61965. if (this._limitVelocityGradientsTexture) {
  61966. this._limitVelocityGradientsTexture.dispose();
  61967. this._limitVelocityGradientsTexture = null;
  61968. }
  61969. this._releaseBuffers();
  61970. return this;
  61971. };
  61972. /**
  61973. * Remove a specific limit velocity gradient
  61974. * @param gradient defines the gradient to remove
  61975. * @returns the current particle system
  61976. */
  61977. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61978. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61979. this._limitVelocityGradientsTexture = null;
  61980. return this;
  61981. };
  61982. /**
  61983. * Adds a new drag gradient
  61984. * @param gradient defines the gradient to use (between 0 and 1)
  61985. * @param factor defines the drag value to affect to the specified gradient
  61986. * @returns the current particle system
  61987. */
  61988. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61989. if (!this._dragGradients) {
  61990. this._dragGradients = [];
  61991. }
  61992. this._addFactorGradient(this._dragGradients, gradient, factor);
  61993. if (this._dragGradientsTexture) {
  61994. this._dragGradientsTexture.dispose();
  61995. this._dragGradientsTexture = null;
  61996. }
  61997. this._releaseBuffers();
  61998. return this;
  61999. };
  62000. /**
  62001. * Remove a specific drag gradient
  62002. * @param gradient defines the gradient to remove
  62003. * @returns the current particle system
  62004. */
  62005. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  62006. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  62007. this._dragGradientsTexture = null;
  62008. return this;
  62009. };
  62010. /**
  62011. * Not supported by GPUParticleSystem
  62012. * @param gradient defines the gradient to use (between 0 and 1)
  62013. * @param factor defines the emit rate value to affect to the specified gradient
  62014. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  62015. * @returns the current particle system
  62016. */
  62017. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  62018. // Do nothing as emit rate is not supported by GPUParticleSystem
  62019. return this;
  62020. };
  62021. /**
  62022. * Not supported by GPUParticleSystem
  62023. * @param gradient defines the gradient to remove
  62024. * @returns the current particle system
  62025. */
  62026. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  62027. // Do nothing as emit rate is not supported by GPUParticleSystem
  62028. return this;
  62029. };
  62030. /**
  62031. * Not supported by GPUParticleSystem
  62032. * @param gradient defines the gradient to use (between 0 and 1)
  62033. * @param factor defines the start size value to affect to the specified gradient
  62034. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  62035. * @returns the current particle system
  62036. */
  62037. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  62038. // Do nothing as start size is not supported by GPUParticleSystem
  62039. return this;
  62040. };
  62041. /**
  62042. * Not supported by GPUParticleSystem
  62043. * @param gradient defines the gradient to remove
  62044. * @returns the current particle system
  62045. */
  62046. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  62047. // Do nothing as start size is not supported by GPUParticleSystem
  62048. return this;
  62049. };
  62050. /**
  62051. * Not supported by GPUParticleSystem
  62052. * @param gradient defines the gradient to use (between 0 and 1)
  62053. * @param min defines the color remap minimal range
  62054. * @param max defines the color remap maximal range
  62055. * @returns the current particle system
  62056. */
  62057. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  62058. // Do nothing as start size is not supported by GPUParticleSystem
  62059. return this;
  62060. };
  62061. /**
  62062. * Not supported by GPUParticleSystem
  62063. * @param gradient defines the gradient to remove
  62064. * @returns the current particle system
  62065. */
  62066. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  62067. // Do nothing as start size is not supported by GPUParticleSystem
  62068. return this;
  62069. };
  62070. /**
  62071. * Not supported by GPUParticleSystem
  62072. * @param gradient defines the gradient to use (between 0 and 1)
  62073. * @param min defines the alpha remap minimal range
  62074. * @param max defines the alpha remap maximal range
  62075. * @returns the current particle system
  62076. */
  62077. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  62078. // Do nothing as start size is not supported by GPUParticleSystem
  62079. return this;
  62080. };
  62081. /**
  62082. * Not supported by GPUParticleSystem
  62083. * @param gradient defines the gradient to remove
  62084. * @returns the current particle system
  62085. */
  62086. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  62087. // Do nothing as start size is not supported by GPUParticleSystem
  62088. return this;
  62089. };
  62090. /**
  62091. * Not supported by GPUParticleSystem
  62092. * @param gradient defines the gradient to use (between 0 and 1)
  62093. * @param color defines the color to affect to the specified gradient
  62094. * @returns the current particle system
  62095. */
  62096. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  62097. //Not supported by GPUParticleSystem
  62098. return this;
  62099. };
  62100. /**
  62101. * Not supported by GPUParticleSystem
  62102. * @param gradient defines the gradient to remove
  62103. * @returns the current particle system
  62104. */
  62105. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  62106. //Not supported by GPUParticleSystem
  62107. return this;
  62108. };
  62109. /**
  62110. * Not supported by GPUParticleSystem
  62111. * @returns the list of ramp gradients
  62112. */
  62113. GPUParticleSystem.prototype.getRampGradients = function () {
  62114. return null;
  62115. };
  62116. GPUParticleSystem.prototype._reset = function () {
  62117. this._releaseBuffers();
  62118. };
  62119. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  62120. var updateVertexBuffers = {};
  62121. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  62122. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  62123. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  62124. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  62125. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  62126. var offset = 12;
  62127. if (!this._colorGradientsTexture) {
  62128. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  62129. offset += 4;
  62130. }
  62131. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  62132. offset += 3;
  62133. if (!this._isBillboardBased) {
  62134. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  62135. offset += 3;
  62136. }
  62137. if (this._angularSpeedGradientsTexture) {
  62138. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  62139. offset += 1;
  62140. }
  62141. else {
  62142. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  62143. offset += 2;
  62144. }
  62145. if (this._isAnimationSheetEnabled) {
  62146. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  62147. offset += 1;
  62148. if (this.spriteRandomStartCell) {
  62149. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  62150. offset += 1;
  62151. }
  62152. }
  62153. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  62154. this._engine.bindArrayBuffer(null);
  62155. return vao;
  62156. };
  62157. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  62158. var renderVertexBuffers = {};
  62159. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  62160. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  62161. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  62162. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  62163. var offset = 12;
  62164. if (!this._colorGradientsTexture) {
  62165. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  62166. offset += 4;
  62167. }
  62168. offset += 3; // Direction
  62169. if (!this._isBillboardBased) {
  62170. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  62171. offset += 3;
  62172. }
  62173. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  62174. if (this._angularSpeedGradientsTexture) {
  62175. offset++;
  62176. }
  62177. else {
  62178. offset += 2;
  62179. }
  62180. if (this._isAnimationSheetEnabled) {
  62181. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  62182. offset += 1;
  62183. if (this.spriteRandomStartCell) {
  62184. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  62185. offset += 1;
  62186. }
  62187. }
  62188. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  62189. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  62190. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  62191. this._engine.bindArrayBuffer(null);
  62192. return vao;
  62193. };
  62194. GPUParticleSystem.prototype._initialize = function (force) {
  62195. if (force === void 0) { force = false; }
  62196. if (this._buffer0 && !force) {
  62197. return;
  62198. }
  62199. var engine = this._scene.getEngine();
  62200. var data = new Array();
  62201. if (!this.isBillboardBased) {
  62202. this._attributesStrideSize += 3;
  62203. }
  62204. if (this._colorGradientsTexture) {
  62205. this._attributesStrideSize -= 4;
  62206. }
  62207. if (this._angularSpeedGradientsTexture) {
  62208. this._attributesStrideSize -= 1;
  62209. }
  62210. if (this._isAnimationSheetEnabled) {
  62211. this._attributesStrideSize += 1;
  62212. if (this.spriteRandomStartCell) {
  62213. this._attributesStrideSize += 1;
  62214. }
  62215. }
  62216. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  62217. // position
  62218. data.push(0.0);
  62219. data.push(0.0);
  62220. data.push(0.0);
  62221. // Age and life
  62222. data.push(0.0); // create the particle as a dead one to create a new one at start
  62223. data.push(0.0);
  62224. // Seed
  62225. data.push(Math.random());
  62226. data.push(Math.random());
  62227. data.push(Math.random());
  62228. data.push(Math.random());
  62229. // Size
  62230. data.push(0.0);
  62231. data.push(0.0);
  62232. data.push(0.0);
  62233. if (!this._colorGradientsTexture) {
  62234. // color
  62235. data.push(0.0);
  62236. data.push(0.0);
  62237. data.push(0.0);
  62238. data.push(0.0);
  62239. }
  62240. // direction
  62241. data.push(0.0);
  62242. data.push(0.0);
  62243. data.push(0.0);
  62244. if (!this.isBillboardBased) {
  62245. // initialDirection
  62246. data.push(0.0);
  62247. data.push(0.0);
  62248. data.push(0.0);
  62249. }
  62250. // angle
  62251. data.push(0.0);
  62252. if (!this._angularSpeedGradientsTexture) {
  62253. data.push(0.0);
  62254. }
  62255. if (this._isAnimationSheetEnabled) {
  62256. data.push(0.0);
  62257. if (this.spriteRandomStartCell) {
  62258. data.push(0.0);
  62259. }
  62260. }
  62261. }
  62262. // Sprite data
  62263. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  62264. -0.5, 0.5, 0, 1,
  62265. -0.5, -0.5, 0, 0,
  62266. 0.5, -0.5, 1, 0]);
  62267. // Buffers
  62268. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62269. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62270. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  62271. // Update VAO
  62272. this._updateVAO = [];
  62273. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  62274. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  62275. // Render VAO
  62276. this._renderVAO = [];
  62277. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  62278. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  62279. // Links
  62280. this._sourceBuffer = this._buffer0;
  62281. this._targetBuffer = this._buffer1;
  62282. };
  62283. /** @hidden */
  62284. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  62285. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  62286. if (this._isBillboardBased) {
  62287. defines += "\n#define BILLBOARD";
  62288. }
  62289. if (this._colorGradientsTexture) {
  62290. defines += "\n#define COLORGRADIENTS";
  62291. }
  62292. if (this._sizeGradientsTexture) {
  62293. defines += "\n#define SIZEGRADIENTS";
  62294. }
  62295. if (this._angularSpeedGradientsTexture) {
  62296. defines += "\n#define ANGULARSPEEDGRADIENTS";
  62297. }
  62298. if (this._velocityGradientsTexture) {
  62299. defines += "\n#define VELOCITYGRADIENTS";
  62300. }
  62301. if (this._limitVelocityGradientsTexture) {
  62302. defines += "\n#define LIMITVELOCITYGRADIENTS";
  62303. }
  62304. if (this._dragGradientsTexture) {
  62305. defines += "\n#define DRAGGRADIENTS";
  62306. }
  62307. if (this.isAnimationSheetEnabled) {
  62308. defines += "\n#define ANIMATESHEET";
  62309. if (this.spriteRandomStartCell) {
  62310. defines += "\n#define ANIMATESHEETRANDOMSTART";
  62311. }
  62312. }
  62313. if (this.noiseTexture) {
  62314. defines += "\n#define NOISE";
  62315. }
  62316. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  62317. return;
  62318. }
  62319. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  62320. if (!this._colorGradientsTexture) {
  62321. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  62322. }
  62323. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  62324. if (!this._isBillboardBased) {
  62325. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  62326. }
  62327. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  62328. if (this.isAnimationSheetEnabled) {
  62329. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  62330. if (this.spriteRandomStartCell) {
  62331. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  62332. }
  62333. }
  62334. this._updateEffectOptions.defines = defines;
  62335. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  62336. };
  62337. /** @hidden */
  62338. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  62339. var defines = "";
  62340. if (this._scene.clipPlane) {
  62341. defines = "\n#define CLIPPLANE";
  62342. }
  62343. if (this._scene.clipPlane2) {
  62344. defines = "\n#define CLIPPLANE2";
  62345. }
  62346. if (this._scene.clipPlane3) {
  62347. defines = "\n#define CLIPPLANE3";
  62348. }
  62349. if (this._scene.clipPlane4) {
  62350. defines = "\n#define CLIPPLANE4";
  62351. }
  62352. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  62353. defines = "\n#define BLENDMULTIPLYMODE";
  62354. }
  62355. if (this._isBillboardBased) {
  62356. defines += "\n#define BILLBOARD";
  62357. switch (this.billboardMode) {
  62358. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  62359. defines += "\n#define BILLBOARDY";
  62360. break;
  62361. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  62362. default:
  62363. break;
  62364. }
  62365. }
  62366. if (this._colorGradientsTexture) {
  62367. defines += "\n#define COLORGRADIENTS";
  62368. }
  62369. if (this.isAnimationSheetEnabled) {
  62370. defines += "\n#define ANIMATESHEET";
  62371. }
  62372. if (this._imageProcessingConfiguration) {
  62373. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62374. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  62375. }
  62376. if (this._renderEffect && this._renderEffect.defines === defines) {
  62377. return;
  62378. }
  62379. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  62380. var samplers = ["textureSampler", "colorGradientSampler"];
  62381. if (BABYLON.ImageProcessingConfiguration) {
  62382. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  62383. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62384. }
  62385. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  62386. };
  62387. /**
  62388. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62389. * @param preWarm defines if we are in the pre-warmimg phase
  62390. */
  62391. GPUParticleSystem.prototype.animate = function (preWarm) {
  62392. if (preWarm === void 0) { preWarm = false; }
  62393. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62394. this._actualFrame += this._timeDelta;
  62395. if (!this._stopped) {
  62396. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62397. this.stop();
  62398. }
  62399. }
  62400. };
  62401. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  62402. var texture = this[textureName];
  62403. if (!factorGradients || !factorGradients.length || texture) {
  62404. return;
  62405. }
  62406. var data = new Float32Array(this._rawTextureWidth);
  62407. for (var x = 0; x < this._rawTextureWidth; x++) {
  62408. var ratio = x / this._rawTextureWidth;
  62409. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  62410. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  62411. });
  62412. }
  62413. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62414. };
  62415. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  62416. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  62417. };
  62418. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  62419. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  62420. };
  62421. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  62422. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  62423. };
  62424. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  62425. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  62426. };
  62427. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  62428. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  62429. };
  62430. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  62431. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  62432. return;
  62433. }
  62434. var data = new Uint8Array(this._rawTextureWidth * 4);
  62435. var tmpColor = BABYLON.Tmp.Color4[0];
  62436. for (var x = 0; x < this._rawTextureWidth; x++) {
  62437. var ratio = x / this._rawTextureWidth;
  62438. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  62439. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  62440. data[x * 4] = tmpColor.r * 255;
  62441. data[x * 4 + 1] = tmpColor.g * 255;
  62442. data[x * 4 + 2] = tmpColor.b * 255;
  62443. data[x * 4 + 3] = tmpColor.a * 255;
  62444. });
  62445. }
  62446. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62447. };
  62448. /**
  62449. * Renders the particle system in its current state
  62450. * @param preWarm defines if the system should only update the particles but not render them
  62451. * @returns the current number of particles
  62452. */
  62453. GPUParticleSystem.prototype.render = function (preWarm) {
  62454. if (preWarm === void 0) { preWarm = false; }
  62455. if (!this._started) {
  62456. return 0;
  62457. }
  62458. this._createColorGradientTexture();
  62459. this._createSizeGradientTexture();
  62460. this._createAngularSpeedGradientTexture();
  62461. this._createVelocityGradientTexture();
  62462. this._createLimitVelocityGradientTexture();
  62463. this._createDragGradientTexture();
  62464. this._recreateUpdateEffect();
  62465. this._recreateRenderEffect();
  62466. if (!this.isReady()) {
  62467. return 0;
  62468. }
  62469. if (!preWarm) {
  62470. if (!this._preWarmDone && this.preWarmCycles) {
  62471. for (var index = 0; index < this.preWarmCycles; index++) {
  62472. this.animate(true);
  62473. this.render(true);
  62474. }
  62475. this._preWarmDone = true;
  62476. }
  62477. if (this._currentRenderId === this._scene.getRenderId()) {
  62478. return 0;
  62479. }
  62480. this._currentRenderId = this._scene.getRenderId();
  62481. }
  62482. // Get everything ready to render
  62483. this._initialize();
  62484. this._accumulatedCount += this.emitRate * this._timeDelta;
  62485. if (this._accumulatedCount > 1) {
  62486. var intPart = this._accumulatedCount | 0;
  62487. this._accumulatedCount -= intPart;
  62488. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  62489. }
  62490. if (!this._currentActiveCount) {
  62491. return 0;
  62492. }
  62493. // Enable update effect
  62494. this._engine.enableEffect(this._updateEffect);
  62495. this._engine.setState(false);
  62496. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  62497. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  62498. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  62499. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  62500. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  62501. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  62502. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  62503. if (!this._colorGradientsTexture) {
  62504. this._updateEffect.setDirectColor4("color1", this.color1);
  62505. this._updateEffect.setDirectColor4("color2", this.color2);
  62506. }
  62507. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  62508. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  62509. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  62510. this._updateEffect.setVector3("gravity", this.gravity);
  62511. if (this._sizeGradientsTexture) {
  62512. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  62513. }
  62514. if (this._angularSpeedGradientsTexture) {
  62515. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  62516. }
  62517. if (this._velocityGradientsTexture) {
  62518. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  62519. }
  62520. if (this._limitVelocityGradientsTexture) {
  62521. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  62522. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  62523. }
  62524. if (this._dragGradientsTexture) {
  62525. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62526. }
  62527. if (this.particleEmitterType) {
  62528. this.particleEmitterType.applyToShader(this._updateEffect);
  62529. }
  62530. if (this._isAnimationSheetEnabled) {
  62531. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62532. }
  62533. if (this.noiseTexture) {
  62534. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62535. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62536. }
  62537. var emitterWM;
  62538. if (this.emitter.position) {
  62539. var emitterMesh = this.emitter;
  62540. emitterWM = emitterMesh.getWorldMatrix();
  62541. }
  62542. else {
  62543. var emitterPosition = this.emitter;
  62544. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62545. }
  62546. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62547. // Bind source VAO
  62548. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62549. // Update
  62550. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62551. this._engine.setRasterizerState(false);
  62552. this._engine.beginTransformFeedback(true);
  62553. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62554. this._engine.endTransformFeedback();
  62555. this._engine.setRasterizerState(true);
  62556. this._engine.bindTransformFeedbackBuffer(null);
  62557. if (!preWarm) {
  62558. // Enable render effect
  62559. this._engine.enableEffect(this._renderEffect);
  62560. var viewMatrix = this._scene.getViewMatrix();
  62561. this._renderEffect.setMatrix("view", viewMatrix);
  62562. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62563. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62564. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62565. if (this._colorGradientsTexture) {
  62566. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62567. }
  62568. else {
  62569. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62570. }
  62571. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62572. var baseSize = this.particleTexture.getBaseSize();
  62573. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62574. }
  62575. if (this._isBillboardBased) {
  62576. var camera = this._scene.activeCamera;
  62577. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62578. }
  62579. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62580. var invView = viewMatrix.clone();
  62581. invView.invert();
  62582. this._renderEffect.setMatrix("invView", invView);
  62583. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62584. }
  62585. // image processing
  62586. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62587. this._imageProcessingConfiguration.bind(this._renderEffect);
  62588. }
  62589. // Draw order
  62590. switch (this.blendMode) {
  62591. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62592. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62593. break;
  62594. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62595. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62596. break;
  62597. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62598. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62599. break;
  62600. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62601. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62602. break;
  62603. }
  62604. if (this.forceDepthWrite) {
  62605. this._engine.setDepthWrite(true);
  62606. }
  62607. // Bind source VAO
  62608. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62609. // Render
  62610. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62611. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62612. }
  62613. // Switch VAOs
  62614. this._targetIndex++;
  62615. if (this._targetIndex === 2) {
  62616. this._targetIndex = 0;
  62617. }
  62618. // Switch buffers
  62619. var tmpBuffer = this._sourceBuffer;
  62620. this._sourceBuffer = this._targetBuffer;
  62621. this._targetBuffer = tmpBuffer;
  62622. return this._currentActiveCount;
  62623. };
  62624. /**
  62625. * Rebuilds the particle system
  62626. */
  62627. GPUParticleSystem.prototype.rebuild = function () {
  62628. this._initialize(true);
  62629. };
  62630. GPUParticleSystem.prototype._releaseBuffers = function () {
  62631. if (this._buffer0) {
  62632. this._buffer0.dispose();
  62633. this._buffer0 = null;
  62634. }
  62635. if (this._buffer1) {
  62636. this._buffer1.dispose();
  62637. this._buffer1 = null;
  62638. }
  62639. if (this._spriteBuffer) {
  62640. this._spriteBuffer.dispose();
  62641. this._spriteBuffer = null;
  62642. }
  62643. };
  62644. GPUParticleSystem.prototype._releaseVAOs = function () {
  62645. if (!this._updateVAO) {
  62646. return;
  62647. }
  62648. for (var index = 0; index < this._updateVAO.length; index++) {
  62649. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62650. }
  62651. this._updateVAO = [];
  62652. for (var index = 0; index < this._renderVAO.length; index++) {
  62653. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62654. }
  62655. this._renderVAO = [];
  62656. };
  62657. /**
  62658. * Disposes the particle system and free the associated resources
  62659. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62660. */
  62661. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62662. if (disposeTexture === void 0) { disposeTexture = true; }
  62663. var index = this._scene.particleSystems.indexOf(this);
  62664. if (index > -1) {
  62665. this._scene.particleSystems.splice(index, 1);
  62666. }
  62667. this._releaseBuffers();
  62668. this._releaseVAOs();
  62669. if (this._colorGradientsTexture) {
  62670. this._colorGradientsTexture.dispose();
  62671. this._colorGradientsTexture = null;
  62672. }
  62673. if (this._sizeGradientsTexture) {
  62674. this._sizeGradientsTexture.dispose();
  62675. this._sizeGradientsTexture = null;
  62676. }
  62677. if (this._angularSpeedGradientsTexture) {
  62678. this._angularSpeedGradientsTexture.dispose();
  62679. this._angularSpeedGradientsTexture = null;
  62680. }
  62681. if (this._velocityGradientsTexture) {
  62682. this._velocityGradientsTexture.dispose();
  62683. this._velocityGradientsTexture = null;
  62684. }
  62685. if (this._limitVelocityGradientsTexture) {
  62686. this._limitVelocityGradientsTexture.dispose();
  62687. this._limitVelocityGradientsTexture = null;
  62688. }
  62689. if (this._dragGradientsTexture) {
  62690. this._dragGradientsTexture.dispose();
  62691. this._dragGradientsTexture = null;
  62692. }
  62693. if (this._randomTexture) {
  62694. this._randomTexture.dispose();
  62695. this._randomTexture = null;
  62696. }
  62697. if (this._randomTexture2) {
  62698. this._randomTexture2.dispose();
  62699. this._randomTexture2 = null;
  62700. }
  62701. if (disposeTexture && this.particleTexture) {
  62702. this.particleTexture.dispose();
  62703. this.particleTexture = null;
  62704. }
  62705. if (disposeTexture && this.noiseTexture) {
  62706. this.noiseTexture.dispose();
  62707. this.noiseTexture = null;
  62708. }
  62709. // Callback
  62710. this.onDisposeObservable.notifyObservers(this);
  62711. this.onDisposeObservable.clear();
  62712. };
  62713. /**
  62714. * Clones the particle system.
  62715. * @param name The name of the cloned object
  62716. * @param newEmitter The new emitter to use
  62717. * @returns the cloned particle system
  62718. */
  62719. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62720. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62721. BABYLON.Tools.DeepCopy(this, result);
  62722. if (newEmitter === undefined) {
  62723. newEmitter = this.emitter;
  62724. }
  62725. result.emitter = newEmitter;
  62726. if (this.particleTexture) {
  62727. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62728. }
  62729. return result;
  62730. };
  62731. /**
  62732. * Serializes the particle system to a JSON object.
  62733. * @returns the JSON object
  62734. */
  62735. GPUParticleSystem.prototype.serialize = function () {
  62736. var serializationObject = {};
  62737. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62738. serializationObject.activeParticleCount = this.activeParticleCount;
  62739. return serializationObject;
  62740. };
  62741. /**
  62742. * Parses a JSON object to create a GPU particle system.
  62743. * @param parsedParticleSystem The JSON object to parse
  62744. * @param scene The scene to create the particle system in
  62745. * @param rootUrl The root url to use to load external dependencies like texture
  62746. * @returns the parsed GPU particle system
  62747. */
  62748. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62749. var name = parsedParticleSystem.name;
  62750. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62751. if (parsedParticleSystem.activeParticleCount) {
  62752. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62753. }
  62754. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62755. return particleSystem;
  62756. };
  62757. return GPUParticleSystem;
  62758. }(BABYLON.BaseParticleSystem));
  62759. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62760. })(BABYLON || (BABYLON = {}));
  62761. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62762. var BABYLON;
  62763. (function (BABYLON) {
  62764. /**
  62765. * Represents one particle of a solid particle system.
  62766. */
  62767. var SolidParticle = /** @class */ (function () {
  62768. /**
  62769. * Creates a Solid Particle object.
  62770. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62771. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62772. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62773. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62774. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62775. * @param shapeId (integer) is the model shape identifier in the SPS.
  62776. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62777. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62778. */
  62779. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62780. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62781. /**
  62782. * particle global index
  62783. */
  62784. this.idx = 0;
  62785. /**
  62786. * The color of the particle
  62787. */
  62788. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62789. /**
  62790. * The world space position of the particle.
  62791. */
  62792. this.position = BABYLON.Vector3.Zero();
  62793. /**
  62794. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62795. */
  62796. this.rotation = BABYLON.Vector3.Zero();
  62797. /**
  62798. * The scaling of the particle.
  62799. */
  62800. this.scaling = BABYLON.Vector3.One();
  62801. /**
  62802. * The uvs of the particle.
  62803. */
  62804. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62805. /**
  62806. * The current speed of the particle.
  62807. */
  62808. this.velocity = BABYLON.Vector3.Zero();
  62809. /**
  62810. * The pivot point in the particle local space.
  62811. */
  62812. this.pivot = BABYLON.Vector3.Zero();
  62813. /**
  62814. * Must the particle be translated from its pivot point in its local space ?
  62815. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62816. * Default : false
  62817. */
  62818. this.translateFromPivot = false;
  62819. /**
  62820. * Is the particle active or not ?
  62821. */
  62822. this.alive = true;
  62823. /**
  62824. * Is the particle visible or not ?
  62825. */
  62826. this.isVisible = true;
  62827. /**
  62828. * Index of this particle in the global "positions" array (Internal use)
  62829. * @hidden
  62830. */
  62831. this._pos = 0;
  62832. /**
  62833. * @hidden Index of this particle in the global "indices" array (Internal use)
  62834. */
  62835. this._ind = 0;
  62836. /**
  62837. * ModelShape id of this particle
  62838. */
  62839. this.shapeId = 0;
  62840. /**
  62841. * Index of the particle in its shape id (Internal use)
  62842. */
  62843. this.idxInShape = 0;
  62844. /**
  62845. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62846. */
  62847. this._stillInvisible = false;
  62848. /**
  62849. * @hidden Last computed particle rotation matrix
  62850. */
  62851. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62852. /**
  62853. * Parent particle Id, if any.
  62854. * Default null.
  62855. */
  62856. this.parentId = null;
  62857. /**
  62858. * @hidden Internal global position in the SPS.
  62859. */
  62860. this._globalPosition = BABYLON.Vector3.Zero();
  62861. this.idx = particleIndex;
  62862. this._pos = positionIndex;
  62863. this._ind = indiceIndex;
  62864. this._model = model;
  62865. this.shapeId = shapeId;
  62866. this.idxInShape = idxInShape;
  62867. this._sps = sps;
  62868. if (modelBoundingInfo) {
  62869. this._modelBoundingInfo = modelBoundingInfo;
  62870. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62871. }
  62872. }
  62873. Object.defineProperty(SolidParticle.prototype, "scale", {
  62874. /**
  62875. * Legacy support, changed scale to scaling
  62876. */
  62877. get: function () {
  62878. return this.scaling;
  62879. },
  62880. /**
  62881. * Legacy support, changed scale to scaling
  62882. */
  62883. set: function (scale) {
  62884. this.scaling = scale;
  62885. },
  62886. enumerable: true,
  62887. configurable: true
  62888. });
  62889. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62890. /**
  62891. * Legacy support, changed quaternion to rotationQuaternion
  62892. */
  62893. get: function () {
  62894. return this.rotationQuaternion;
  62895. },
  62896. /**
  62897. * Legacy support, changed quaternion to rotationQuaternion
  62898. */
  62899. set: function (q) {
  62900. this.rotationQuaternion = q;
  62901. },
  62902. enumerable: true,
  62903. configurable: true
  62904. });
  62905. /**
  62906. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62907. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62908. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62909. * @returns true if it intersects
  62910. */
  62911. SolidParticle.prototype.intersectsMesh = function (target) {
  62912. if (!this._boundingInfo || !target._boundingInfo) {
  62913. return false;
  62914. }
  62915. if (this._sps._bSphereOnly) {
  62916. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62917. }
  62918. return this._boundingInfo.intersects(target._boundingInfo, false);
  62919. };
  62920. return SolidParticle;
  62921. }());
  62922. BABYLON.SolidParticle = SolidParticle;
  62923. /**
  62924. * Represents the shape of the model used by one particle of a solid particle system.
  62925. * SPS internal tool, don't use it manually.
  62926. */
  62927. var ModelShape = /** @class */ (function () {
  62928. /**
  62929. * 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.
  62930. * SPS internal tool, don't use it manually.
  62931. * @hidden
  62932. */
  62933. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62934. /**
  62935. * length of the shape in the model indices array (internal use)
  62936. * @hidden
  62937. */
  62938. this._indicesLength = 0;
  62939. this.shapeID = id;
  62940. this._shape = shape;
  62941. this._indicesLength = indicesLength;
  62942. this._shapeUV = shapeUV;
  62943. this._positionFunction = posFunction;
  62944. this._vertexFunction = vtxFunction;
  62945. }
  62946. return ModelShape;
  62947. }());
  62948. BABYLON.ModelShape = ModelShape;
  62949. /**
  62950. * Represents a Depth Sorted Particle in the solid particle system.
  62951. */
  62952. var DepthSortedParticle = /** @class */ (function () {
  62953. function DepthSortedParticle() {
  62954. /**
  62955. * Index of the particle in the "indices" array
  62956. */
  62957. this.ind = 0;
  62958. /**
  62959. * Length of the particle shape in the "indices" array
  62960. */
  62961. this.indicesLength = 0;
  62962. /**
  62963. * Squared distance from the particle to the camera
  62964. */
  62965. this.sqDistance = 0.0;
  62966. }
  62967. return DepthSortedParticle;
  62968. }());
  62969. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62970. })(BABYLON || (BABYLON = {}));
  62971. //# sourceMappingURL=babylon.solidParticle.js.map
  62972. var BABYLON;
  62973. (function (BABYLON) {
  62974. /**
  62975. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62976. *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.
  62977. * The SPS is also a particle system. It provides some methods to manage the particles.
  62978. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62979. *
  62980. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62981. */
  62982. var SolidParticleSystem = /** @class */ (function () {
  62983. /**
  62984. * Creates a SPS (Solid Particle System) object.
  62985. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62986. * @param scene (Scene) is the scene in which the SPS is added.
  62987. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62988. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62989. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62990. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62991. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62992. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62993. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62994. */
  62995. function SolidParticleSystem(name, scene, options) {
  62996. /**
  62997. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62998. * Example : var p = SPS.particles[i];
  62999. */
  63000. this.particles = new Array();
  63001. /**
  63002. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  63003. */
  63004. this.nbParticles = 0;
  63005. /**
  63006. * If the particles must ever face the camera (default false). Useful for planar particles.
  63007. */
  63008. this.billboard = false;
  63009. /**
  63010. * Recompute normals when adding a shape
  63011. */
  63012. this.recomputeNormals = true;
  63013. /**
  63014. * This a counter ofr your own usage. It's not set by any SPS functions.
  63015. */
  63016. this.counter = 0;
  63017. /**
  63018. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  63019. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  63020. */
  63021. this.vars = {};
  63022. /**
  63023. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  63024. * @hidden
  63025. */
  63026. this._bSphereOnly = false;
  63027. /**
  63028. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  63029. * @hidden
  63030. */
  63031. this._bSphereRadiusFactor = 1.0;
  63032. this._positions = new Array();
  63033. this._indices = new Array();
  63034. this._normals = new Array();
  63035. this._colors = new Array();
  63036. this._uvs = new Array();
  63037. this._index = 0; // indices index
  63038. this._updatable = true;
  63039. this._pickable = false;
  63040. this._isVisibilityBoxLocked = false;
  63041. this._alwaysVisible = false;
  63042. this._depthSort = false;
  63043. this._shapeCounter = 0;
  63044. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  63045. this._color = new BABYLON.Color4(0, 0, 0, 0);
  63046. this._computeParticleColor = true;
  63047. this._computeParticleTexture = true;
  63048. this._computeParticleRotation = true;
  63049. this._computeParticleVertex = false;
  63050. this._computeBoundingBox = false;
  63051. this._depthSortParticles = true;
  63052. this._cam_axisZ = BABYLON.Vector3.Zero();
  63053. this._cam_axisY = BABYLON.Vector3.Zero();
  63054. this._cam_axisX = BABYLON.Vector3.Zero();
  63055. this._axisZ = BABYLON.Axis.Z;
  63056. this._camDir = BABYLON.Vector3.Zero();
  63057. this._camInvertedPosition = BABYLON.Vector3.Zero();
  63058. this._rotMatrix = new BABYLON.Matrix();
  63059. this._invertMatrix = new BABYLON.Matrix();
  63060. this._rotated = BABYLON.Vector3.Zero();
  63061. this._quaternion = new BABYLON.Quaternion();
  63062. this._vertex = BABYLON.Vector3.Zero();
  63063. this._normal = BABYLON.Vector3.Zero();
  63064. this._yaw = 0.0;
  63065. this._pitch = 0.0;
  63066. this._roll = 0.0;
  63067. this._halfroll = 0.0;
  63068. this._halfpitch = 0.0;
  63069. this._halfyaw = 0.0;
  63070. this._sinRoll = 0.0;
  63071. this._cosRoll = 0.0;
  63072. this._sinPitch = 0.0;
  63073. this._cosPitch = 0.0;
  63074. this._sinYaw = 0.0;
  63075. this._cosYaw = 0.0;
  63076. this._mustUnrotateFixedNormals = false;
  63077. this._minimum = BABYLON.Vector3.Zero();
  63078. this._maximum = BABYLON.Vector3.Zero();
  63079. this._minBbox = BABYLON.Vector3.Zero();
  63080. this._maxBbox = BABYLON.Vector3.Zero();
  63081. this._particlesIntersect = false;
  63082. this._depthSortFunction = function (p1, p2) {
  63083. return (p2.sqDistance - p1.sqDistance);
  63084. };
  63085. this._needs32Bits = false;
  63086. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  63087. this._scaledPivot = BABYLON.Vector3.Zero();
  63088. this._particleHasParent = false;
  63089. this.name = name;
  63090. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63091. this._camera = scene.activeCamera;
  63092. this._pickable = options ? options.isPickable : false;
  63093. this._depthSort = options ? options.enableDepthSort : false;
  63094. this._particlesIntersect = options ? options.particleIntersection : false;
  63095. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  63096. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  63097. if (options && options.updatable !== undefined) {
  63098. this._updatable = options.updatable;
  63099. }
  63100. else {
  63101. this._updatable = true;
  63102. }
  63103. if (this._pickable) {
  63104. this.pickedParticles = [];
  63105. }
  63106. if (this._depthSort) {
  63107. this.depthSortedParticles = [];
  63108. }
  63109. }
  63110. /**
  63111. * Builds the SPS underlying mesh. Returns a standard Mesh.
  63112. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  63113. * @returns the created mesh
  63114. */
  63115. SolidParticleSystem.prototype.buildMesh = function () {
  63116. if (this.nbParticles === 0) {
  63117. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  63118. this.addShape(triangle, 1);
  63119. triangle.dispose();
  63120. }
  63121. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  63122. this._positions32 = new Float32Array(this._positions);
  63123. this._uvs32 = new Float32Array(this._uvs);
  63124. this._colors32 = new Float32Array(this._colors);
  63125. if (this.recomputeNormals) {
  63126. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  63127. }
  63128. this._normals32 = new Float32Array(this._normals);
  63129. this._fixedNormal32 = new Float32Array(this._normals);
  63130. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  63131. this._unrotateFixedNormals();
  63132. }
  63133. var vertexData = new BABYLON.VertexData();
  63134. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  63135. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  63136. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  63137. if (this._uvs32.length > 0) {
  63138. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  63139. }
  63140. if (this._colors32.length > 0) {
  63141. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  63142. }
  63143. var mesh = new BABYLON.Mesh(this.name, this._scene);
  63144. vertexData.applyToMesh(mesh, this._updatable);
  63145. this.mesh = mesh;
  63146. this.mesh.isPickable = this._pickable;
  63147. // free memory
  63148. if (!this._depthSort) {
  63149. this._indices = null;
  63150. }
  63151. this._positions = null;
  63152. this._normals = null;
  63153. this._uvs = null;
  63154. this._colors = null;
  63155. if (!this._updatable) {
  63156. this.particles.length = 0;
  63157. }
  63158. return mesh;
  63159. };
  63160. /**
  63161. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  63162. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  63163. * Thus the particles generated from `digest()` have their property `position` set yet.
  63164. * @param mesh ( Mesh ) is the mesh to be digested
  63165. * @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
  63166. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  63167. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  63168. * @returns the current SPS
  63169. */
  63170. SolidParticleSystem.prototype.digest = function (mesh, options) {
  63171. var size = (options && options.facetNb) || 1;
  63172. var number = (options && options.number) || 0;
  63173. var delta = (options && options.delta) || 0;
  63174. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63175. var meshInd = mesh.getIndices();
  63176. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63177. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63178. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63179. var f = 0; // facet counter
  63180. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  63181. // compute size from number
  63182. if (number) {
  63183. number = (number > totalFacets) ? totalFacets : number;
  63184. size = Math.round(totalFacets / number);
  63185. delta = 0;
  63186. }
  63187. else {
  63188. size = (size > totalFacets) ? totalFacets : size;
  63189. }
  63190. var facetPos = []; // submesh positions
  63191. var facetInd = []; // submesh indices
  63192. var facetUV = []; // submesh UV
  63193. var facetCol = []; // submesh colors
  63194. var barycenter = BABYLON.Vector3.Zero();
  63195. var sizeO = size;
  63196. while (f < totalFacets) {
  63197. size = sizeO + Math.floor((1 + delta) * Math.random());
  63198. if (f > totalFacets - size) {
  63199. size = totalFacets - f;
  63200. }
  63201. // reset temp arrays
  63202. facetPos.length = 0;
  63203. facetInd.length = 0;
  63204. facetUV.length = 0;
  63205. facetCol.length = 0;
  63206. // iterate over "size" facets
  63207. var fi = 0;
  63208. for (var j = f * 3; j < (f + size) * 3; j++) {
  63209. facetInd.push(fi);
  63210. var i = meshInd[j];
  63211. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  63212. if (meshUV) {
  63213. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  63214. }
  63215. if (meshCol) {
  63216. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  63217. }
  63218. fi++;
  63219. }
  63220. // create a model shape for each single particle
  63221. var idx = this.nbParticles;
  63222. var shape = this._posToShape(facetPos);
  63223. var shapeUV = this._uvsToShapeUV(facetUV);
  63224. // compute the barycenter of the shape
  63225. var v;
  63226. for (v = 0; v < shape.length; v++) {
  63227. barycenter.addInPlace(shape[v]);
  63228. }
  63229. barycenter.scaleInPlace(1 / shape.length);
  63230. // shift the shape from its barycenter to the origin
  63231. for (v = 0; v < shape.length; v++) {
  63232. shape[v].subtractInPlace(barycenter);
  63233. }
  63234. var bInfo;
  63235. if (this._particlesIntersect) {
  63236. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  63237. }
  63238. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  63239. // add the particle in the SPS
  63240. var currentPos = this._positions.length;
  63241. var currentInd = this._indices.length;
  63242. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  63243. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  63244. // initialize the particle position
  63245. this.particles[this.nbParticles].position.addInPlace(barycenter);
  63246. this._index += shape.length;
  63247. idx++;
  63248. this.nbParticles++;
  63249. this._shapeCounter++;
  63250. f += size;
  63251. }
  63252. return this;
  63253. };
  63254. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  63255. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  63256. var index = 0;
  63257. var idx = 0;
  63258. for (var p = 0; p < this.particles.length; p++) {
  63259. this._particle = this.particles[p];
  63260. this._shape = this._particle._model._shape;
  63261. if (this._particle.rotationQuaternion) {
  63262. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63263. }
  63264. else {
  63265. this._yaw = this._particle.rotation.y;
  63266. this._pitch = this._particle.rotation.x;
  63267. this._roll = this._particle.rotation.z;
  63268. this._quaternionRotationYPR();
  63269. }
  63270. this._quaternionToRotationMatrix();
  63271. this._rotMatrix.invertToRef(this._invertMatrix);
  63272. for (var pt = 0; pt < this._shape.length; pt++) {
  63273. idx = index + pt * 3;
  63274. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  63275. this._fixedNormal32[idx] = this._normal.x;
  63276. this._fixedNormal32[idx + 1] = this._normal.y;
  63277. this._fixedNormal32[idx + 2] = this._normal.z;
  63278. }
  63279. index = idx + 3;
  63280. }
  63281. };
  63282. //reset copy
  63283. SolidParticleSystem.prototype._resetCopy = function () {
  63284. this._copy.position.x = 0;
  63285. this._copy.position.y = 0;
  63286. this._copy.position.z = 0;
  63287. this._copy.rotation.x = 0;
  63288. this._copy.rotation.y = 0;
  63289. this._copy.rotation.z = 0;
  63290. this._copy.rotationQuaternion = null;
  63291. this._copy.scaling.x = 1.0;
  63292. this._copy.scaling.y = 1.0;
  63293. this._copy.scaling.z = 1.0;
  63294. this._copy.uvs.x = 0;
  63295. this._copy.uvs.y = 0;
  63296. this._copy.uvs.z = 1.0;
  63297. this._copy.uvs.w = 1.0;
  63298. this._copy.color = null;
  63299. this._copy.translateFromPivot = false;
  63300. };
  63301. // _meshBuilder : inserts the shape model in the global SPS mesh
  63302. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  63303. var i;
  63304. var u = 0;
  63305. var c = 0;
  63306. var n = 0;
  63307. this._resetCopy();
  63308. if (options && options.positionFunction) { // call to custom positionFunction
  63309. options.positionFunction(this._copy, idx, idxInShape);
  63310. this._mustUnrotateFixedNormals = true;
  63311. }
  63312. if (this._copy.rotationQuaternion) {
  63313. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63314. }
  63315. else {
  63316. this._yaw = this._copy.rotation.y;
  63317. this._pitch = this._copy.rotation.x;
  63318. this._roll = this._copy.rotation.z;
  63319. this._quaternionRotationYPR();
  63320. }
  63321. this._quaternionToRotationMatrix();
  63322. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  63323. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  63324. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  63325. if (this._copy.translateFromPivot) {
  63326. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63327. }
  63328. else {
  63329. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63330. }
  63331. for (i = 0; i < shape.length; i++) {
  63332. this._vertex.x = shape[i].x;
  63333. this._vertex.y = shape[i].y;
  63334. this._vertex.z = shape[i].z;
  63335. if (options && options.vertexFunction) {
  63336. options.vertexFunction(this._copy, this._vertex, i);
  63337. }
  63338. this._vertex.x *= this._copy.scaling.x;
  63339. this._vertex.y *= this._copy.scaling.y;
  63340. this._vertex.z *= this._copy.scaling.z;
  63341. this._vertex.x -= this._scaledPivot.x;
  63342. this._vertex.y -= this._scaledPivot.y;
  63343. this._vertex.z -= this._scaledPivot.z;
  63344. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63345. this._rotated.addInPlace(this._pivotBackTranslation);
  63346. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  63347. if (meshUV) {
  63348. 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);
  63349. u += 2;
  63350. }
  63351. if (this._copy.color) {
  63352. this._color = this._copy.color;
  63353. }
  63354. else if (meshCol && meshCol[c] !== undefined) {
  63355. this._color.r = meshCol[c];
  63356. this._color.g = meshCol[c + 1];
  63357. this._color.b = meshCol[c + 2];
  63358. this._color.a = meshCol[c + 3];
  63359. }
  63360. else {
  63361. this._color.r = 1.0;
  63362. this._color.g = 1.0;
  63363. this._color.b = 1.0;
  63364. this._color.a = 1.0;
  63365. }
  63366. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  63367. c += 4;
  63368. if (!this.recomputeNormals && meshNor) {
  63369. this._normal.x = meshNor[n];
  63370. this._normal.y = meshNor[n + 1];
  63371. this._normal.z = meshNor[n + 2];
  63372. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  63373. normals.push(this._normal.x, this._normal.y, this._normal.z);
  63374. n += 3;
  63375. }
  63376. }
  63377. for (i = 0; i < meshInd.length; i++) {
  63378. var current_ind = p + meshInd[i];
  63379. indices.push(current_ind);
  63380. if (current_ind > 65535) {
  63381. this._needs32Bits = true;
  63382. }
  63383. }
  63384. if (this._pickable) {
  63385. var nbfaces = meshInd.length / 3;
  63386. for (i = 0; i < nbfaces; i++) {
  63387. this.pickedParticles.push({ idx: idx, faceId: i });
  63388. }
  63389. }
  63390. if (this._depthSort) {
  63391. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  63392. }
  63393. return this._copy;
  63394. };
  63395. // returns a shape array from positions array
  63396. SolidParticleSystem.prototype._posToShape = function (positions) {
  63397. var shape = [];
  63398. for (var i = 0; i < positions.length; i += 3) {
  63399. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  63400. }
  63401. return shape;
  63402. };
  63403. // returns a shapeUV array from a Vector4 uvs
  63404. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  63405. var shapeUV = [];
  63406. if (uvs) {
  63407. for (var i = 0; i < uvs.length; i++)
  63408. shapeUV.push(uvs[i]);
  63409. }
  63410. return shapeUV;
  63411. };
  63412. // adds a new particle object in the particles array
  63413. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  63414. if (bInfo === void 0) { bInfo = null; }
  63415. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  63416. this.particles.push(sp);
  63417. return sp;
  63418. };
  63419. /**
  63420. * Adds some particles to the SPS from the model shape. Returns the shape id.
  63421. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  63422. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  63423. * @param nb (positive integer) the number of particles to be created from this model
  63424. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  63425. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  63426. * @returns the number of shapes in the system
  63427. */
  63428. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  63429. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63430. var meshInd = mesh.getIndices();
  63431. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63432. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63433. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63434. var bbInfo;
  63435. if (this._particlesIntersect) {
  63436. bbInfo = mesh.getBoundingInfo();
  63437. }
  63438. var shape = this._posToShape(meshPos);
  63439. var shapeUV = this._uvsToShapeUV(meshUV);
  63440. var posfunc = options ? options.positionFunction : null;
  63441. var vtxfunc = options ? options.vertexFunction : null;
  63442. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  63443. // particles
  63444. var sp;
  63445. var currentCopy;
  63446. var idx = this.nbParticles;
  63447. for (var i = 0; i < nb; i++) {
  63448. var currentPos = this._positions.length;
  63449. var currentInd = this._indices.length;
  63450. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  63451. if (this._updatable) {
  63452. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  63453. sp.position.copyFrom(currentCopy.position);
  63454. sp.rotation.copyFrom(currentCopy.rotation);
  63455. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  63456. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  63457. }
  63458. if (currentCopy.color && sp.color) {
  63459. sp.color.copyFrom(currentCopy.color);
  63460. }
  63461. sp.scaling.copyFrom(currentCopy.scaling);
  63462. sp.uvs.copyFrom(currentCopy.uvs);
  63463. }
  63464. this._index += shape.length;
  63465. idx++;
  63466. }
  63467. this.nbParticles += nb;
  63468. this._shapeCounter++;
  63469. return this._shapeCounter - 1;
  63470. };
  63471. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  63472. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  63473. this._resetCopy();
  63474. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  63475. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  63476. }
  63477. if (this._copy.rotationQuaternion) {
  63478. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63479. }
  63480. else {
  63481. this._yaw = this._copy.rotation.y;
  63482. this._pitch = this._copy.rotation.x;
  63483. this._roll = this._copy.rotation.z;
  63484. this._quaternionRotationYPR();
  63485. }
  63486. this._quaternionToRotationMatrix();
  63487. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63488. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63489. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63490. if (this._copy.translateFromPivot) {
  63491. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63492. }
  63493. else {
  63494. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63495. }
  63496. this._shape = particle._model._shape;
  63497. for (var pt = 0; pt < this._shape.length; pt++) {
  63498. this._vertex.x = this._shape[pt].x;
  63499. this._vertex.y = this._shape[pt].y;
  63500. this._vertex.z = this._shape[pt].z;
  63501. if (particle._model._vertexFunction) {
  63502. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  63503. }
  63504. this._vertex.x *= this._copy.scaling.x;
  63505. this._vertex.y *= this._copy.scaling.y;
  63506. this._vertex.z *= this._copy.scaling.z;
  63507. this._vertex.x -= this._scaledPivot.x;
  63508. this._vertex.y -= this._scaledPivot.y;
  63509. this._vertex.z -= this._scaledPivot.z;
  63510. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63511. this._rotated.addInPlace(this._pivotBackTranslation);
  63512. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  63513. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  63514. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  63515. }
  63516. particle.position.x = 0.0;
  63517. particle.position.y = 0.0;
  63518. particle.position.z = 0.0;
  63519. particle.rotation.x = 0.0;
  63520. particle.rotation.y = 0.0;
  63521. particle.rotation.z = 0.0;
  63522. particle.rotationQuaternion = null;
  63523. particle.scaling.x = 1.0;
  63524. particle.scaling.y = 1.0;
  63525. particle.scaling.z = 1.0;
  63526. particle.uvs.x = 0.0;
  63527. particle.uvs.y = 0.0;
  63528. particle.uvs.z = 1.0;
  63529. particle.uvs.w = 1.0;
  63530. particle.pivot.x = 0.0;
  63531. particle.pivot.y = 0.0;
  63532. particle.pivot.z = 0.0;
  63533. particle.translateFromPivot = false;
  63534. particle.parentId = null;
  63535. };
  63536. /**
  63537. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63538. * @returns the SPS.
  63539. */
  63540. SolidParticleSystem.prototype.rebuildMesh = function () {
  63541. for (var p = 0; p < this.particles.length; p++) {
  63542. this._rebuildParticle(this.particles[p]);
  63543. }
  63544. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63545. return this;
  63546. };
  63547. /**
  63548. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63549. * This method calls `updateParticle()` for each particle of the SPS.
  63550. * For an animated SPS, it is usually called within the render loop.
  63551. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63552. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63553. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63554. * @returns the SPS.
  63555. */
  63556. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63557. if (start === void 0) { start = 0; }
  63558. if (end === void 0) { end = this.nbParticles - 1; }
  63559. if (update === void 0) { update = true; }
  63560. if (!this._updatable) {
  63561. return this;
  63562. }
  63563. // custom beforeUpdate
  63564. this.beforeUpdateParticles(start, end, update);
  63565. this._cam_axisX.x = 1.0;
  63566. this._cam_axisX.y = 0.0;
  63567. this._cam_axisX.z = 0.0;
  63568. this._cam_axisY.x = 0.0;
  63569. this._cam_axisY.y = 1.0;
  63570. this._cam_axisY.z = 0.0;
  63571. this._cam_axisZ.x = 0.0;
  63572. this._cam_axisZ.y = 0.0;
  63573. this._cam_axisZ.z = 1.0;
  63574. // cases when the World Matrix is to be computed first
  63575. if (this.billboard || this._depthSort) {
  63576. this.mesh.computeWorldMatrix(true);
  63577. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63578. }
  63579. // if the particles will always face the camera
  63580. if (this.billboard) {
  63581. // compute the camera position and un-rotate it by the current mesh rotation
  63582. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63583. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63584. this._cam_axisZ.normalize();
  63585. // same for camera up vector extracted from the cam view matrix
  63586. var view = this._camera.getViewMatrix(true);
  63587. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63588. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63589. this._cam_axisY.normalize();
  63590. this._cam_axisX.normalize();
  63591. }
  63592. // if depthSort, compute the camera global position in the mesh local system
  63593. if (this._depthSort) {
  63594. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63595. }
  63596. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63597. var idx = 0; // current position index in the global array positions32
  63598. var index = 0; // position start index in the global array positions32 of the current particle
  63599. var colidx = 0; // current color index in the global array colors32
  63600. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63601. var uvidx = 0; // current uv index in the global array uvs32
  63602. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63603. var pt = 0; // current index in the particle model shape
  63604. if (this.mesh.isFacetDataEnabled) {
  63605. this._computeBoundingBox = true;
  63606. }
  63607. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63608. if (this._computeBoundingBox) {
  63609. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63610. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63611. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63612. }
  63613. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63614. if (this.mesh._boundingInfo) {
  63615. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63616. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63617. }
  63618. }
  63619. }
  63620. // particle loop
  63621. index = this.particles[start]._pos;
  63622. var vpos = (index / 3) | 0;
  63623. colorIndex = vpos * 4;
  63624. uvIndex = vpos * 2;
  63625. for (var p = start; p <= end; p++) {
  63626. this._particle = this.particles[p];
  63627. this._shape = this._particle._model._shape;
  63628. this._shapeUV = this._particle._model._shapeUV;
  63629. // call to custom user function to update the particle properties
  63630. this.updateParticle(this._particle);
  63631. // camera-particle distance for depth sorting
  63632. if (this._depthSort && this._depthSortParticles) {
  63633. var dsp = this.depthSortedParticles[p];
  63634. dsp.ind = this._particle._ind;
  63635. dsp.indicesLength = this._particle._model._indicesLength;
  63636. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63637. }
  63638. // skip the computations for inactive or already invisible particles
  63639. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63640. // increment indexes for the next particle
  63641. pt = this._shape.length;
  63642. index += pt * 3;
  63643. colorIndex += pt * 4;
  63644. uvIndex += pt * 2;
  63645. continue;
  63646. }
  63647. if (this._particle.isVisible) {
  63648. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63649. this._particleHasParent = (this._particle.parentId !== null);
  63650. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63651. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63652. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63653. // particle rotation matrix
  63654. if (this.billboard) {
  63655. this._particle.rotation.x = 0.0;
  63656. this._particle.rotation.y = 0.0;
  63657. }
  63658. if (this._computeParticleRotation || this.billboard) {
  63659. if (this._particle.rotationQuaternion) {
  63660. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63661. }
  63662. else {
  63663. this._yaw = this._particle.rotation.y;
  63664. this._pitch = this._particle.rotation.x;
  63665. this._roll = this._particle.rotation.z;
  63666. this._quaternionRotationYPR();
  63667. }
  63668. this._quaternionToRotationMatrix();
  63669. }
  63670. if (this._particleHasParent) {
  63671. this._parent = this.particles[this._particle.parentId];
  63672. 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];
  63673. 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];
  63674. 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];
  63675. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63676. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63677. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63678. if (this._computeParticleRotation || this.billboard) {
  63679. 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];
  63680. 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];
  63681. 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];
  63682. 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];
  63683. 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];
  63684. 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];
  63685. 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];
  63686. 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];
  63687. 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];
  63688. }
  63689. }
  63690. else {
  63691. this._particle._globalPosition.x = this._particle.position.x;
  63692. this._particle._globalPosition.y = this._particle.position.y;
  63693. this._particle._globalPosition.z = this._particle.position.z;
  63694. if (this._computeParticleRotation || this.billboard) {
  63695. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63696. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63697. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63698. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63699. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63700. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63701. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63702. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63703. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63704. }
  63705. }
  63706. if (this._particle.translateFromPivot) {
  63707. this._pivotBackTranslation.x = 0.0;
  63708. this._pivotBackTranslation.y = 0.0;
  63709. this._pivotBackTranslation.z = 0.0;
  63710. }
  63711. else {
  63712. this._pivotBackTranslation.x = this._scaledPivot.x;
  63713. this._pivotBackTranslation.y = this._scaledPivot.y;
  63714. this._pivotBackTranslation.z = this._scaledPivot.z;
  63715. }
  63716. // particle vertex loop
  63717. for (pt = 0; pt < this._shape.length; pt++) {
  63718. idx = index + pt * 3;
  63719. colidx = colorIndex + pt * 4;
  63720. uvidx = uvIndex + pt * 2;
  63721. this._vertex.x = this._shape[pt].x;
  63722. this._vertex.y = this._shape[pt].y;
  63723. this._vertex.z = this._shape[pt].z;
  63724. if (this._computeParticleVertex) {
  63725. this.updateParticleVertex(this._particle, this._vertex, pt);
  63726. }
  63727. // positions
  63728. this._vertex.x *= this._particle.scaling.x;
  63729. this._vertex.y *= this._particle.scaling.y;
  63730. this._vertex.z *= this._particle.scaling.z;
  63731. this._vertex.x -= this._scaledPivot.x;
  63732. this._vertex.y -= this._scaledPivot.y;
  63733. this._vertex.z -= this._scaledPivot.z;
  63734. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63735. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63736. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63737. this._rotated.x += this._pivotBackTranslation.x;
  63738. this._rotated.y += this._pivotBackTranslation.y;
  63739. this._rotated.z += this._pivotBackTranslation.z;
  63740. 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;
  63741. 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;
  63742. 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;
  63743. if (this._computeBoundingBox) {
  63744. if (this._positions32[idx] < this._minimum.x) {
  63745. this._minimum.x = this._positions32[idx];
  63746. }
  63747. if (this._positions32[idx] > this._maximum.x) {
  63748. this._maximum.x = this._positions32[idx];
  63749. }
  63750. if (this._positions32[idx + 1] < this._minimum.y) {
  63751. this._minimum.y = this._positions32[idx + 1];
  63752. }
  63753. if (this._positions32[idx + 1] > this._maximum.y) {
  63754. this._maximum.y = this._positions32[idx + 1];
  63755. }
  63756. if (this._positions32[idx + 2] < this._minimum.z) {
  63757. this._minimum.z = this._positions32[idx + 2];
  63758. }
  63759. if (this._positions32[idx + 2] > this._maximum.z) {
  63760. this._maximum.z = this._positions32[idx + 2];
  63761. }
  63762. }
  63763. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63764. if (!this._computeParticleVertex) {
  63765. this._normal.x = this._fixedNormal32[idx];
  63766. this._normal.y = this._fixedNormal32[idx + 1];
  63767. this._normal.z = this._fixedNormal32[idx + 2];
  63768. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63769. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63770. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63771. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63772. 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;
  63773. 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;
  63774. }
  63775. if (this._computeParticleColor && this._particle.color) {
  63776. this._colors32[colidx] = this._particle.color.r;
  63777. this._colors32[colidx + 1] = this._particle.color.g;
  63778. this._colors32[colidx + 2] = this._particle.color.b;
  63779. this._colors32[colidx + 3] = this._particle.color.a;
  63780. }
  63781. if (this._computeParticleTexture) {
  63782. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63783. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63784. }
  63785. }
  63786. }
  63787. // particle just set invisible : scaled to zero and positioned at the origin
  63788. else {
  63789. this._particle._stillInvisible = true; // mark the particle as invisible
  63790. for (pt = 0; pt < this._shape.length; pt++) {
  63791. idx = index + pt * 3;
  63792. colidx = colorIndex + pt * 4;
  63793. uvidx = uvIndex + pt * 2;
  63794. this._positions32[idx] = 0.0;
  63795. this._positions32[idx + 1] = 0.0;
  63796. this._positions32[idx + 2] = 0.0;
  63797. this._normals32[idx] = 0.0;
  63798. this._normals32[idx + 1] = 0.0;
  63799. this._normals32[idx + 2] = 0.0;
  63800. if (this._computeParticleColor && this._particle.color) {
  63801. this._colors32[colidx] = this._particle.color.r;
  63802. this._colors32[colidx + 1] = this._particle.color.g;
  63803. this._colors32[colidx + 2] = this._particle.color.b;
  63804. this._colors32[colidx + 3] = this._particle.color.a;
  63805. }
  63806. if (this._computeParticleTexture) {
  63807. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63808. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63809. }
  63810. }
  63811. }
  63812. // if the particle intersections must be computed : update the bbInfo
  63813. if (this._particlesIntersect) {
  63814. var bInfo = this._particle._boundingInfo;
  63815. var bBox = bInfo.boundingBox;
  63816. var bSphere = bInfo.boundingSphere;
  63817. if (!this._bSphereOnly) {
  63818. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63819. for (var b = 0; b < bBox.vectors.length; b++) {
  63820. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63821. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63822. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63823. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63824. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63825. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63826. 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;
  63827. 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;
  63828. 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;
  63829. }
  63830. bBox._update(this.mesh._worldMatrix);
  63831. }
  63832. // place and scale the particle bouding sphere in the SPS local system, then update it
  63833. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63834. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63835. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63836. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63837. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63838. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63839. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63840. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63841. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63842. 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));
  63843. bSphere._update(this.mesh._worldMatrix);
  63844. }
  63845. // increment indexes for the next particle
  63846. index = idx + 3;
  63847. colorIndex = colidx + 4;
  63848. uvIndex = uvidx + 2;
  63849. }
  63850. // if the VBO must be updated
  63851. if (update) {
  63852. if (this._computeParticleColor) {
  63853. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63854. }
  63855. if (this._computeParticleTexture) {
  63856. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63857. }
  63858. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63859. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63860. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63861. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63862. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63863. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63864. for (var i = 0; i < this._normals32.length; i++) {
  63865. this._fixedNormal32[i] = this._normals32[i];
  63866. }
  63867. }
  63868. if (!this.mesh.areNormalsFrozen) {
  63869. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63870. }
  63871. }
  63872. if (this._depthSort && this._depthSortParticles) {
  63873. this.depthSortedParticles.sort(this._depthSortFunction);
  63874. var dspl = this.depthSortedParticles.length;
  63875. var sorted = 0;
  63876. var lind = 0;
  63877. var sind = 0;
  63878. var sid = 0;
  63879. for (sorted = 0; sorted < dspl; sorted++) {
  63880. lind = this.depthSortedParticles[sorted].indicesLength;
  63881. sind = this.depthSortedParticles[sorted].ind;
  63882. for (var i = 0; i < lind; i++) {
  63883. this._indices32[sid] = this._indices[sind + i];
  63884. sid++;
  63885. }
  63886. }
  63887. this.mesh.updateIndices(this._indices32);
  63888. }
  63889. }
  63890. if (this._computeBoundingBox) {
  63891. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63892. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63893. }
  63894. this.afterUpdateParticles(start, end, update);
  63895. return this;
  63896. };
  63897. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63898. this._halfroll = this._roll * 0.5;
  63899. this._halfpitch = this._pitch * 0.5;
  63900. this._halfyaw = this._yaw * 0.5;
  63901. this._sinRoll = Math.sin(this._halfroll);
  63902. this._cosRoll = Math.cos(this._halfroll);
  63903. this._sinPitch = Math.sin(this._halfpitch);
  63904. this._cosPitch = Math.cos(this._halfpitch);
  63905. this._sinYaw = Math.sin(this._halfyaw);
  63906. this._cosYaw = Math.cos(this._halfyaw);
  63907. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63908. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63909. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63910. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63911. };
  63912. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63913. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63914. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63915. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63916. this._rotMatrix.m[3] = 0;
  63917. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63918. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63919. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63920. this._rotMatrix.m[7] = 0;
  63921. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63922. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63923. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63924. this._rotMatrix.m[11] = 0;
  63925. this._rotMatrix.m[12] = 0;
  63926. this._rotMatrix.m[13] = 0;
  63927. this._rotMatrix.m[14] = 0;
  63928. this._rotMatrix.m[15] = 1.0;
  63929. };
  63930. /**
  63931. * Disposes the SPS.
  63932. */
  63933. SolidParticleSystem.prototype.dispose = function () {
  63934. this.mesh.dispose();
  63935. this.vars = null;
  63936. // drop references to internal big arrays for the GC
  63937. this._positions = null;
  63938. this._indices = null;
  63939. this._normals = null;
  63940. this._uvs = null;
  63941. this._colors = null;
  63942. this._indices32 = null;
  63943. this._positions32 = null;
  63944. this._normals32 = null;
  63945. this._fixedNormal32 = null;
  63946. this._uvs32 = null;
  63947. this._colors32 = null;
  63948. this.pickedParticles = null;
  63949. };
  63950. /**
  63951. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63952. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63953. * @returns the SPS.
  63954. */
  63955. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63956. if (!this._isVisibilityBoxLocked) {
  63957. this.mesh.refreshBoundingInfo();
  63958. }
  63959. return this;
  63960. };
  63961. /**
  63962. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63963. * @param size the size (float) of the visibility box
  63964. * note : this doesn't lock the SPS mesh bounding box.
  63965. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63966. */
  63967. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63968. var vis = size / 2;
  63969. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63970. };
  63971. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63972. /**
  63973. * Gets whether the SPS as always visible or not
  63974. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63975. */
  63976. get: function () {
  63977. return this._alwaysVisible;
  63978. },
  63979. /**
  63980. * Sets the SPS as always visible or not
  63981. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63982. */
  63983. set: function (val) {
  63984. this._alwaysVisible = val;
  63985. this.mesh.alwaysSelectAsActiveMesh = val;
  63986. },
  63987. enumerable: true,
  63988. configurable: true
  63989. });
  63990. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63991. /**
  63992. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63993. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63994. */
  63995. get: function () {
  63996. return this._isVisibilityBoxLocked;
  63997. },
  63998. /**
  63999. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  64000. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64001. */
  64002. set: function (val) {
  64003. this._isVisibilityBoxLocked = val;
  64004. var boundingInfo = this.mesh.getBoundingInfo();
  64005. boundingInfo.isLocked = val;
  64006. },
  64007. enumerable: true,
  64008. configurable: true
  64009. });
  64010. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  64011. /**
  64012. * Gets if `setParticles()` computes the particle rotations or not.
  64013. * Default value : true. The SPS is faster when it's set to false.
  64014. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  64015. */
  64016. get: function () {
  64017. return this._computeParticleRotation;
  64018. },
  64019. /**
  64020. * Tells to `setParticles()` to compute the particle rotations or not.
  64021. * Default value : true. The SPS is faster when it's set to false.
  64022. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  64023. */
  64024. set: function (val) {
  64025. this._computeParticleRotation = val;
  64026. },
  64027. enumerable: true,
  64028. configurable: true
  64029. });
  64030. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  64031. /**
  64032. * Gets if `setParticles()` computes the particle colors or not.
  64033. * Default value : true. The SPS is faster when it's set to false.
  64034. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  64035. */
  64036. get: function () {
  64037. return this._computeParticleColor;
  64038. },
  64039. /**
  64040. * Tells to `setParticles()` to compute the particle colors or not.
  64041. * Default value : true. The SPS is faster when it's set to false.
  64042. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  64043. */
  64044. set: function (val) {
  64045. this._computeParticleColor = val;
  64046. },
  64047. enumerable: true,
  64048. configurable: true
  64049. });
  64050. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  64051. /**
  64052. * Gets if `setParticles()` computes the particle textures or not.
  64053. * Default value : true. The SPS is faster when it's set to false.
  64054. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  64055. */
  64056. get: function () {
  64057. return this._computeParticleTexture;
  64058. },
  64059. set: function (val) {
  64060. this._computeParticleTexture = val;
  64061. },
  64062. enumerable: true,
  64063. configurable: true
  64064. });
  64065. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  64066. /**
  64067. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  64068. * Default value : false. The SPS is faster when it's set to false.
  64069. * Note : the particle custom vertex positions aren't stored values.
  64070. */
  64071. get: function () {
  64072. return this._computeParticleVertex;
  64073. },
  64074. /**
  64075. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  64076. * Default value : false. The SPS is faster when it's set to false.
  64077. * Note : the particle custom vertex positions aren't stored values.
  64078. */
  64079. set: function (val) {
  64080. this._computeParticleVertex = val;
  64081. },
  64082. enumerable: true,
  64083. configurable: true
  64084. });
  64085. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  64086. /**
  64087. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  64088. */
  64089. get: function () {
  64090. return this._computeBoundingBox;
  64091. },
  64092. /**
  64093. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  64094. */
  64095. set: function (val) {
  64096. this._computeBoundingBox = val;
  64097. },
  64098. enumerable: true,
  64099. configurable: true
  64100. });
  64101. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  64102. /**
  64103. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  64104. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64105. * Default : `true`
  64106. */
  64107. get: function () {
  64108. return this._depthSortParticles;
  64109. },
  64110. /**
  64111. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  64112. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64113. * Default : `true`
  64114. */
  64115. set: function (val) {
  64116. this._depthSortParticles = val;
  64117. },
  64118. enumerable: true,
  64119. configurable: true
  64120. });
  64121. // =======================================================================
  64122. // Particle behavior logic
  64123. // these following methods may be overwritten by the user to fit his needs
  64124. /**
  64125. * This function does nothing. It may be overwritten to set all the particle first values.
  64126. * The SPS doesn't call this function, you may have to call it by your own.
  64127. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64128. */
  64129. SolidParticleSystem.prototype.initParticles = function () {
  64130. };
  64131. /**
  64132. * This function does nothing. It may be overwritten to recycle a particle.
  64133. * The SPS doesn't call this function, you may have to call it by your own.
  64134. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64135. * @param particle The particle to recycle
  64136. * @returns the recycled particle
  64137. */
  64138. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  64139. return particle;
  64140. };
  64141. /**
  64142. * Updates a particle : this function should be overwritten by the user.
  64143. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  64144. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64145. * @example : just set a particle position or velocity and recycle conditions
  64146. * @param particle The particle to update
  64147. * @returns the updated particle
  64148. */
  64149. SolidParticleSystem.prototype.updateParticle = function (particle) {
  64150. return particle;
  64151. };
  64152. /**
  64153. * Updates a vertex of a particle : it can be overwritten by the user.
  64154. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  64155. * @param particle the current particle
  64156. * @param vertex the current index of the current particle
  64157. * @param pt the index of the current vertex in the particle shape
  64158. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  64159. * @example : just set a vertex particle position
  64160. * @returns the updated vertex
  64161. */
  64162. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  64163. return vertex;
  64164. };
  64165. /**
  64166. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  64167. * This does nothing and may be overwritten by the user.
  64168. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64169. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64170. * @param update the boolean update value actually passed to setParticles()
  64171. */
  64172. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  64173. };
  64174. /**
  64175. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  64176. * This will be passed three parameters.
  64177. * This does nothing and may be overwritten by the user.
  64178. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64179. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64180. * @param update the boolean update value actually passed to setParticles()
  64181. */
  64182. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  64183. };
  64184. return SolidParticleSystem;
  64185. }());
  64186. BABYLON.SolidParticleSystem = SolidParticleSystem;
  64187. })(BABYLON || (BABYLON = {}));
  64188. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  64189. var BABYLON;
  64190. (function (BABYLON) {
  64191. /**
  64192. * Class containing static functions to help procedurally build meshes
  64193. */
  64194. var MeshBuilder = /** @class */ (function () {
  64195. function MeshBuilder() {
  64196. }
  64197. MeshBuilder.updateSideOrientation = function (orientation) {
  64198. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  64199. return BABYLON.Mesh.DOUBLESIDE;
  64200. }
  64201. if (orientation === undefined || orientation === null) {
  64202. return BABYLON.Mesh.FRONTSIDE;
  64203. }
  64204. return orientation;
  64205. };
  64206. /**
  64207. * Creates a box mesh
  64208. * * The parameter `size` sets the size (float) of each box side (default 1)
  64209. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  64210. * * 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)
  64211. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64212. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64213. * * 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
  64214. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64215. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  64216. * @param name defines the name of the mesh
  64217. * @param options defines the options used to create the mesh
  64218. * @param scene defines the hosting scene
  64219. * @returns the box mesh
  64220. */
  64221. MeshBuilder.CreateBox = function (name, options, scene) {
  64222. if (scene === void 0) { scene = null; }
  64223. var box = new BABYLON.Mesh(name, scene);
  64224. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64225. box._originalBuilderSideOrientation = options.sideOrientation;
  64226. var vertexData = BABYLON.VertexData.CreateBox(options);
  64227. vertexData.applyToMesh(box, options.updatable);
  64228. return box;
  64229. };
  64230. /**
  64231. * Creates a sphere mesh
  64232. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  64233. * * 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`)
  64234. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  64235. * * 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
  64236. * * 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)
  64237. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64238. * * 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
  64239. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64240. * @param name defines the name of the mesh
  64241. * @param options defines the options used to create the mesh
  64242. * @param scene defines the hosting scene
  64243. * @returns the sphere mesh
  64244. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  64245. */
  64246. MeshBuilder.CreateSphere = function (name, options, scene) {
  64247. var sphere = new BABYLON.Mesh(name, scene);
  64248. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64249. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64250. var vertexData = BABYLON.VertexData.CreateSphere(options);
  64251. vertexData.applyToMesh(sphere, options.updatable);
  64252. return sphere;
  64253. };
  64254. /**
  64255. * Creates a plane polygonal mesh. By default, this is a disc
  64256. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  64257. * * 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
  64258. * * 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
  64259. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64260. * * 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
  64261. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64262. * @param name defines the name of the mesh
  64263. * @param options defines the options used to create the mesh
  64264. * @param scene defines the hosting scene
  64265. * @returns the plane polygonal mesh
  64266. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  64267. */
  64268. MeshBuilder.CreateDisc = function (name, options, scene) {
  64269. if (scene === void 0) { scene = null; }
  64270. var disc = new BABYLON.Mesh(name, scene);
  64271. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64272. disc._originalBuilderSideOrientation = options.sideOrientation;
  64273. var vertexData = BABYLON.VertexData.CreateDisc(options);
  64274. vertexData.applyToMesh(disc, options.updatable);
  64275. return disc;
  64276. };
  64277. /**
  64278. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  64279. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  64280. * * 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`)
  64281. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  64282. * * 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
  64283. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64284. * * 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
  64285. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64286. * @param name defines the name of the mesh
  64287. * @param options defines the options used to create the mesh
  64288. * @param scene defines the hosting scene
  64289. * @returns the icosahedron mesh
  64290. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  64291. */
  64292. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  64293. var sphere = new BABYLON.Mesh(name, scene);
  64294. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64295. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64296. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  64297. vertexData.applyToMesh(sphere, options.updatable);
  64298. return sphere;
  64299. };
  64300. ;
  64301. /**
  64302. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64303. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  64304. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  64305. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  64306. * * 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
  64307. * * 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
  64308. * * 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
  64309. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64310. * * 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
  64311. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64312. * * 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
  64313. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  64314. * * 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
  64315. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  64316. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64317. * @param name defines the name of the mesh
  64318. * @param options defines the options used to create the mesh
  64319. * @param scene defines the hosting scene
  64320. * @returns the ribbon mesh
  64321. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  64322. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64323. */
  64324. MeshBuilder.CreateRibbon = function (name, options, scene) {
  64325. if (scene === void 0) { scene = null; }
  64326. var pathArray = options.pathArray;
  64327. var closeArray = options.closeArray;
  64328. var closePath = options.closePath;
  64329. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64330. var instance = options.instance;
  64331. var updatable = options.updatable;
  64332. if (instance) { // existing ribbon instance update
  64333. // positionFunction : ribbon case
  64334. // only pathArray and sideOrientation parameters are taken into account for positions update
  64335. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  64336. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  64337. var positionFunction = function (positions) {
  64338. var minlg = pathArray[0].length;
  64339. var i = 0;
  64340. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  64341. for (var si = 1; si <= ns; si++) {
  64342. for (var p = 0; p < pathArray.length; p++) {
  64343. var path = pathArray[p];
  64344. var l = path.length;
  64345. minlg = (minlg < l) ? minlg : l;
  64346. var j = 0;
  64347. while (j < minlg) {
  64348. positions[i] = path[j].x;
  64349. positions[i + 1] = path[j].y;
  64350. positions[i + 2] = path[j].z;
  64351. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  64352. BABYLON.Tmp.Vector3[0].x = path[j].x;
  64353. }
  64354. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  64355. BABYLON.Tmp.Vector3[1].x = path[j].x;
  64356. }
  64357. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  64358. BABYLON.Tmp.Vector3[0].y = path[j].y;
  64359. }
  64360. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  64361. BABYLON.Tmp.Vector3[1].y = path[j].y;
  64362. }
  64363. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  64364. BABYLON.Tmp.Vector3[0].z = path[j].z;
  64365. }
  64366. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  64367. BABYLON.Tmp.Vector3[1].z = path[j].z;
  64368. }
  64369. j++;
  64370. i += 3;
  64371. }
  64372. if (instance._closePath) {
  64373. positions[i] = path[0].x;
  64374. positions[i + 1] = path[0].y;
  64375. positions[i + 2] = path[0].z;
  64376. i += 3;
  64377. }
  64378. }
  64379. }
  64380. };
  64381. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64382. positionFunction(positions);
  64383. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  64384. instance._boundingInfo.update(instance._worldMatrix);
  64385. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64386. if (options.colors) {
  64387. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64388. for (var c = 0; c < options.colors.length; c++) {
  64389. colors[c * 4] = options.colors[c].r;
  64390. colors[c * 4 + 1] = options.colors[c].g;
  64391. colors[c * 4 + 2] = options.colors[c].b;
  64392. colors[c * 4 + 3] = options.colors[c].a;
  64393. }
  64394. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  64395. }
  64396. if (options.uvs) {
  64397. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64398. for (var i = 0; i < options.uvs.length; i++) {
  64399. uvs[i * 2] = options.uvs[i].x;
  64400. uvs[i * 2 + 1] = options.uvs[i].y;
  64401. }
  64402. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  64403. }
  64404. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  64405. var indices = instance.getIndices();
  64406. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64407. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  64408. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  64409. if (instance._closePath) {
  64410. var indexFirst = 0;
  64411. var indexLast = 0;
  64412. for (var p = 0; p < pathArray.length; p++) {
  64413. indexFirst = instance._idx[p] * 3;
  64414. if (p + 1 < pathArray.length) {
  64415. indexLast = (instance._idx[p + 1] - 1) * 3;
  64416. }
  64417. else {
  64418. indexLast = normals.length - 3;
  64419. }
  64420. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  64421. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  64422. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  64423. normals[indexLast] = normals[indexFirst];
  64424. normals[indexLast + 1] = normals[indexFirst + 1];
  64425. normals[indexLast + 2] = normals[indexFirst + 2];
  64426. }
  64427. }
  64428. if (!(instance.areNormalsFrozen)) {
  64429. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  64430. }
  64431. }
  64432. return instance;
  64433. }
  64434. else { // new ribbon creation
  64435. var ribbon = new BABYLON.Mesh(name, scene);
  64436. ribbon._originalBuilderSideOrientation = sideOrientation;
  64437. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  64438. if (closePath) {
  64439. ribbon._idx = vertexData._idx;
  64440. }
  64441. ribbon._closePath = closePath;
  64442. ribbon._closeArray = closeArray;
  64443. vertexData.applyToMesh(ribbon, updatable);
  64444. return ribbon;
  64445. }
  64446. };
  64447. /**
  64448. * Creates a cylinder or a cone mesh
  64449. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  64450. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  64451. * * 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.
  64452. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  64453. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  64454. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  64455. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  64456. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  64457. * * 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).
  64458. * * 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
  64459. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  64460. * * 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
  64461. * * 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.
  64462. * * If `enclose` is false, a ring surface is one element.
  64463. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  64464. * * 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
  64465. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64466. * * 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
  64467. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64468. * @param name defines the name of the mesh
  64469. * @param options defines the options used to create the mesh
  64470. * @param scene defines the hosting scene
  64471. * @returns the cylinder mesh
  64472. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  64473. */
  64474. MeshBuilder.CreateCylinder = function (name, options, scene) {
  64475. var cylinder = new BABYLON.Mesh(name, scene);
  64476. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64477. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  64478. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  64479. vertexData.applyToMesh(cylinder, options.updatable);
  64480. return cylinder;
  64481. };
  64482. /**
  64483. * Creates a torus mesh
  64484. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  64485. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  64486. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  64487. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64488. * * 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
  64489. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64490. * @param name defines the name of the mesh
  64491. * @param options defines the options used to create the mesh
  64492. * @param scene defines the hosting scene
  64493. * @returns the torus mesh
  64494. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  64495. */
  64496. MeshBuilder.CreateTorus = function (name, options, scene) {
  64497. var torus = new BABYLON.Mesh(name, scene);
  64498. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64499. torus._originalBuilderSideOrientation = options.sideOrientation;
  64500. var vertexData = BABYLON.VertexData.CreateTorus(options);
  64501. vertexData.applyToMesh(torus, options.updatable);
  64502. return torus;
  64503. };
  64504. /**
  64505. * Creates a torus knot mesh
  64506. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  64507. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  64508. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  64509. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  64510. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64511. * * 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
  64512. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64513. * @param name defines the name of the mesh
  64514. * @param options defines the options used to create the mesh
  64515. * @param scene defines the hosting scene
  64516. * @returns the torus knot mesh
  64517. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  64518. */
  64519. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  64520. var torusKnot = new BABYLON.Mesh(name, scene);
  64521. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64522. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  64523. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  64524. vertexData.applyToMesh(torusKnot, options.updatable);
  64525. return torusKnot;
  64526. };
  64527. /**
  64528. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64529. * * 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
  64530. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64531. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64532. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64533. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64534. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64535. * * 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
  64536. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64537. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64538. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64539. * @param name defines the name of the new line system
  64540. * @param options defines the options used to create the line system
  64541. * @param scene defines the hosting scene
  64542. * @returns a new line system mesh
  64543. */
  64544. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64545. var instance = options.instance;
  64546. var lines = options.lines;
  64547. var colors = options.colors;
  64548. if (instance) { // lines update
  64549. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64550. var vertexColor;
  64551. var lineColors;
  64552. if (colors) {
  64553. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64554. }
  64555. var i = 0;
  64556. var c = 0;
  64557. for (var l = 0; l < lines.length; l++) {
  64558. var points = lines[l];
  64559. for (var p = 0; p < points.length; p++) {
  64560. positions[i] = points[p].x;
  64561. positions[i + 1] = points[p].y;
  64562. positions[i + 2] = points[p].z;
  64563. if (colors && vertexColor) {
  64564. lineColors = colors[l];
  64565. vertexColor[c] = lineColors[p].r;
  64566. vertexColor[c + 1] = lineColors[p].g;
  64567. vertexColor[c + 2] = lineColors[p].b;
  64568. vertexColor[c + 3] = lineColors[p].a;
  64569. c += 4;
  64570. }
  64571. i += 3;
  64572. }
  64573. }
  64574. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64575. if (colors && vertexColor) {
  64576. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64577. }
  64578. return instance;
  64579. }
  64580. // line system creation
  64581. var useVertexColor = (colors) ? true : false;
  64582. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64583. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64584. vertexData.applyToMesh(lineSystem, options.updatable);
  64585. return lineSystem;
  64586. };
  64587. /**
  64588. * Creates a line mesh
  64589. * 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
  64590. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64591. * * The parameter `points` is an array successive Vector3
  64592. * * 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
  64593. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64594. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64595. * * When updating an instance, remember that only point positions can change, not the number of points
  64596. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64597. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64598. * @param name defines the name of the new line system
  64599. * @param options defines the options used to create the line system
  64600. * @param scene defines the hosting scene
  64601. * @returns a new line mesh
  64602. */
  64603. MeshBuilder.CreateLines = function (name, options, scene) {
  64604. if (scene === void 0) { scene = null; }
  64605. var colors = (options.colors) ? [options.colors] : null;
  64606. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64607. return lines;
  64608. };
  64609. /**
  64610. * Creates a dashed line mesh
  64611. * * 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
  64612. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64613. * * The parameter `points` is an array successive Vector3
  64614. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64615. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64616. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64617. * * 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
  64618. * * When updating an instance, remember that only point positions can change, not the number of points
  64619. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64620. * @param name defines the name of the mesh
  64621. * @param options defines the options used to create the mesh
  64622. * @param scene defines the hosting scene
  64623. * @returns the dashed line mesh
  64624. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64625. */
  64626. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64627. if (scene === void 0) { scene = null; }
  64628. var points = options.points;
  64629. var instance = options.instance;
  64630. var gapSize = options.gapSize || 1;
  64631. var dashSize = options.dashSize || 3;
  64632. if (instance) { // dashed lines update
  64633. var positionFunction = function (positions) {
  64634. var curvect = BABYLON.Vector3.Zero();
  64635. var nbSeg = positions.length / 6;
  64636. var lg = 0;
  64637. var nb = 0;
  64638. var shft = 0;
  64639. var dashshft = 0;
  64640. var curshft = 0;
  64641. var p = 0;
  64642. var i = 0;
  64643. var j = 0;
  64644. for (i = 0; i < points.length - 1; i++) {
  64645. points[i + 1].subtractToRef(points[i], curvect);
  64646. lg += curvect.length();
  64647. }
  64648. shft = lg / nbSeg;
  64649. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64650. for (i = 0; i < points.length - 1; i++) {
  64651. points[i + 1].subtractToRef(points[i], curvect);
  64652. nb = Math.floor(curvect.length() / shft);
  64653. curvect.normalize();
  64654. j = 0;
  64655. while (j < nb && p < positions.length) {
  64656. curshft = shft * j;
  64657. positions[p] = points[i].x + curshft * curvect.x;
  64658. positions[p + 1] = points[i].y + curshft * curvect.y;
  64659. positions[p + 2] = points[i].z + curshft * curvect.z;
  64660. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64661. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64662. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64663. p += 6;
  64664. j++;
  64665. }
  64666. }
  64667. while (p < positions.length) {
  64668. positions[p] = points[i].x;
  64669. positions[p + 1] = points[i].y;
  64670. positions[p + 2] = points[i].z;
  64671. p += 3;
  64672. }
  64673. };
  64674. instance.updateMeshPositions(positionFunction, false);
  64675. return instance;
  64676. }
  64677. // dashed lines creation
  64678. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64679. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64680. vertexData.applyToMesh(dashedLines, options.updatable);
  64681. dashedLines.dashSize = dashSize;
  64682. dashedLines.gapSize = gapSize;
  64683. return dashedLines;
  64684. };
  64685. /**
  64686. * 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.
  64687. * * 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.
  64688. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64689. * * 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.
  64690. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64691. * * 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
  64692. * * 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
  64693. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64694. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64695. * * 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
  64696. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64697. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64698. * @param name defines the name of the mesh
  64699. * @param options defines the options used to create the mesh
  64700. * @param scene defines the hosting scene
  64701. * @returns the extruded shape mesh
  64702. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64703. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64704. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64705. */
  64706. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64707. if (scene === void 0) { scene = null; }
  64708. var path = options.path;
  64709. var shape = options.shape;
  64710. var scale = options.scale || 1;
  64711. var rotation = options.rotation || 0;
  64712. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64713. var updatable = options.updatable;
  64714. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64715. var instance = options.instance || null;
  64716. var invertUV = options.invertUV || false;
  64717. 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);
  64718. };
  64719. /**
  64720. * Creates an custom extruded shape mesh.
  64721. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64722. * * 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.
  64723. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64724. * * 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
  64725. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64726. * * 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
  64727. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64728. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64729. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64730. * * 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
  64731. * * 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
  64732. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64733. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64734. * * 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
  64735. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64736. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64737. * @param name defines the name of the mesh
  64738. * @param options defines the options used to create the mesh
  64739. * @param scene defines the hosting scene
  64740. * @returns the custom extruded shape mesh
  64741. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64742. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64743. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64744. */
  64745. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64746. var path = options.path;
  64747. var shape = options.shape;
  64748. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64749. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64750. var ribbonCloseArray = options.ribbonCloseArray || false;
  64751. var ribbonClosePath = options.ribbonClosePath || false;
  64752. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64753. var updatable = options.updatable;
  64754. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64755. var instance = options.instance;
  64756. var invertUV = options.invertUV || false;
  64757. 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);
  64758. };
  64759. /**
  64760. * Creates lathe mesh.
  64761. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64762. * * 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
  64763. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64764. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64765. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64766. * * 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
  64767. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64768. * * 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
  64769. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64770. * * 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
  64771. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64772. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64773. * @param name defines the name of the mesh
  64774. * @param options defines the options used to create the mesh
  64775. * @param scene defines the hosting scene
  64776. * @returns the lathe mesh
  64777. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64778. */
  64779. MeshBuilder.CreateLathe = function (name, options, scene) {
  64780. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64781. var closed = (options.closed === undefined) ? true : options.closed;
  64782. var shape = options.shape;
  64783. var radius = options.radius || 1;
  64784. var tessellation = options.tessellation || 64;
  64785. var clip = options.clip || 0;
  64786. var updatable = options.updatable;
  64787. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64788. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64789. var pi2 = Math.PI * 2;
  64790. var paths = new Array();
  64791. var invertUV = options.invertUV || false;
  64792. var i = 0;
  64793. var p = 0;
  64794. var step = pi2 / tessellation * arc;
  64795. var rotated;
  64796. var path = new Array();
  64797. for (i = 0; i <= tessellation - clip; i++) {
  64798. var path = [];
  64799. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64800. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64801. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64802. }
  64803. for (p = 0; p < shape.length; p++) {
  64804. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64805. path.push(rotated);
  64806. }
  64807. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64808. 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));
  64809. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64810. }
  64811. paths.push(path);
  64812. }
  64813. // lathe ribbon
  64814. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64815. return lathe;
  64816. };
  64817. /**
  64818. * Creates a plane mesh
  64819. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64820. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64821. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64822. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64823. * * 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
  64824. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64825. * @param name defines the name of the mesh
  64826. * @param options defines the options used to create the mesh
  64827. * @param scene defines the hosting scene
  64828. * @returns the plane mesh
  64829. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64830. */
  64831. MeshBuilder.CreatePlane = function (name, options, scene) {
  64832. var plane = new BABYLON.Mesh(name, scene);
  64833. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64834. plane._originalBuilderSideOrientation = options.sideOrientation;
  64835. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64836. vertexData.applyToMesh(plane, options.updatable);
  64837. if (options.sourcePlane) {
  64838. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64839. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64840. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64841. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  64842. plane.rotate(vectorProduct, product);
  64843. }
  64844. }
  64845. return plane;
  64846. };
  64847. /**
  64848. * Creates a ground mesh
  64849. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64850. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64851. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64852. * @param name defines the name of the mesh
  64853. * @param options defines the options used to create the mesh
  64854. * @param scene defines the hosting scene
  64855. * @returns the ground mesh
  64856. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64857. */
  64858. MeshBuilder.CreateGround = function (name, options, scene) {
  64859. var ground = new BABYLON.GroundMesh(name, scene);
  64860. ground._setReady(false);
  64861. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64862. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64863. ground._width = options.width || 1;
  64864. ground._height = options.height || 1;
  64865. ground._maxX = ground._width / 2;
  64866. ground._maxZ = ground._height / 2;
  64867. ground._minX = -ground._maxX;
  64868. ground._minZ = -ground._maxZ;
  64869. var vertexData = BABYLON.VertexData.CreateGround(options);
  64870. vertexData.applyToMesh(ground, options.updatable);
  64871. ground._setReady(true);
  64872. return ground;
  64873. };
  64874. /**
  64875. * Creates a tiled ground mesh
  64876. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64877. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64878. * * 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
  64879. * * 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
  64880. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64881. * @param name defines the name of the mesh
  64882. * @param options defines the options used to create the mesh
  64883. * @param scene defines the hosting scene
  64884. * @returns the tiled ground mesh
  64885. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64886. */
  64887. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64888. var tiledGround = new BABYLON.Mesh(name, scene);
  64889. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64890. vertexData.applyToMesh(tiledGround, options.updatable);
  64891. return tiledGround;
  64892. };
  64893. /**
  64894. * Creates a ground mesh from a height map
  64895. * * The parameter `url` sets the URL of the height map image resource.
  64896. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64897. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64898. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64899. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64900. * * 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.
  64901. * * 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).
  64902. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64903. * @param name defines the name of the mesh
  64904. * @param url defines the url to the height map
  64905. * @param options defines the options used to create the mesh
  64906. * @param scene defines the hosting scene
  64907. * @returns the ground mesh
  64908. * @see http://doc.babylonjs.com/babylon101/height_map
  64909. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64910. */
  64911. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64912. var width = options.width || 10.0;
  64913. var height = options.height || 10.0;
  64914. var subdivisions = options.subdivisions || 1 | 0;
  64915. var minHeight = options.minHeight || 0.0;
  64916. var maxHeight = options.maxHeight || 1.0;
  64917. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64918. var updatable = options.updatable;
  64919. var onReady = options.onReady;
  64920. var ground = new BABYLON.GroundMesh(name, scene);
  64921. ground._subdivisionsX = subdivisions;
  64922. ground._subdivisionsY = subdivisions;
  64923. ground._width = width;
  64924. ground._height = height;
  64925. ground._maxX = ground._width / 2.0;
  64926. ground._maxZ = ground._height / 2.0;
  64927. ground._minX = -ground._maxX;
  64928. ground._minZ = -ground._maxZ;
  64929. ground._setReady(false);
  64930. var onload = function (img) {
  64931. // Getting height map data
  64932. var canvas = document.createElement("canvas");
  64933. var context = canvas.getContext("2d");
  64934. if (!context) {
  64935. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64936. }
  64937. if (scene.isDisposed) {
  64938. return;
  64939. }
  64940. var bufferWidth = img.width;
  64941. var bufferHeight = img.height;
  64942. canvas.width = bufferWidth;
  64943. canvas.height = bufferHeight;
  64944. context.drawImage(img, 0, 0);
  64945. // Create VertexData from map data
  64946. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64947. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64948. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64949. width: width, height: height,
  64950. subdivisions: subdivisions,
  64951. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64952. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  64953. });
  64954. vertexData.applyToMesh(ground, updatable);
  64955. //execute ready callback, if set
  64956. if (onReady) {
  64957. onReady(ground);
  64958. }
  64959. ground._setReady(true);
  64960. };
  64961. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64962. return ground;
  64963. };
  64964. /**
  64965. * Creates a polygon mesh
  64966. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64967. * * 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
  64968. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64969. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64970. * * 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)
  64971. * * Remember you can only change the shape positions, not their number when updating a polygon
  64972. * @param name defines the name of the mesh
  64973. * @param options defines the options used to create the mesh
  64974. * @param scene defines the hosting scene
  64975. * @returns the polygon mesh
  64976. */
  64977. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64978. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64979. var shape = options.shape;
  64980. var holes = options.holes || [];
  64981. var depth = options.depth || 0;
  64982. var contours = [];
  64983. var hole = [];
  64984. for (var i = 0; i < shape.length; i++) {
  64985. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64986. }
  64987. var epsilon = 0.00000001;
  64988. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64989. contours.pop();
  64990. }
  64991. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64992. for (var hNb = 0; hNb < holes.length; hNb++) {
  64993. hole = [];
  64994. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64995. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64996. }
  64997. polygonTriangulation.addHole(hole);
  64998. }
  64999. var polygon = polygonTriangulation.build(options.updatable, depth);
  65000. polygon._originalBuilderSideOrientation = options.sideOrientation;
  65001. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  65002. vertexData.applyToMesh(polygon, options.updatable);
  65003. return polygon;
  65004. };
  65005. ;
  65006. /**
  65007. * Creates an extruded polygon mesh, with depth in the Y direction.
  65008. * * 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)
  65009. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65010. * @param name defines the name of the mesh
  65011. * @param options defines the options used to create the mesh
  65012. * @param scene defines the hosting scene
  65013. * @returns the polygon mesh
  65014. */
  65015. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  65016. return MeshBuilder.CreatePolygon(name, options, scene);
  65017. };
  65018. ;
  65019. /**
  65020. * Creates a tube mesh.
  65021. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65022. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  65023. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  65024. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  65025. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  65026. * * 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)
  65027. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  65028. * * 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
  65029. * * 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
  65030. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65031. * * 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
  65032. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65033. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65034. * @param name defines the name of the mesh
  65035. * @param options defines the options used to create the mesh
  65036. * @param scene defines the hosting scene
  65037. * @returns the tube mesh
  65038. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65039. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  65040. */
  65041. MeshBuilder.CreateTube = function (name, options, scene) {
  65042. var path = options.path;
  65043. var instance = options.instance;
  65044. var radius = 1.0;
  65045. if (instance) {
  65046. radius = instance.radius;
  65047. }
  65048. if (options.radius !== undefined) {
  65049. radius = options.radius;
  65050. }
  65051. ;
  65052. var tessellation = options.tessellation || 64 | 0;
  65053. var radiusFunction = options.radiusFunction || null;
  65054. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  65055. var invertUV = options.invertUV || false;
  65056. var updatable = options.updatable;
  65057. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65058. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  65059. // tube geometry
  65060. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  65061. var tangents = path3D.getTangents();
  65062. var normals = path3D.getNormals();
  65063. var distances = path3D.getDistances();
  65064. var pi2 = Math.PI * 2;
  65065. var step = pi2 / tessellation * arc;
  65066. var returnRadius = function () { return radius; };
  65067. var radiusFunctionFinal = radiusFunction || returnRadius;
  65068. var circlePath;
  65069. var rad;
  65070. var normal;
  65071. var rotated;
  65072. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65073. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65074. for (var i = 0; i < path.length; i++) {
  65075. rad = radiusFunctionFinal(i, distances[i]); // current radius
  65076. circlePath = Array(); // current circle array
  65077. normal = normals[i]; // current normal
  65078. for (var t = 0; t < tessellation; t++) {
  65079. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  65080. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  65081. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  65082. rotated.scaleInPlace(rad).addInPlace(path[i]);
  65083. circlePath[t] = rotated;
  65084. }
  65085. circlePaths[index] = circlePath;
  65086. index++;
  65087. }
  65088. // cap
  65089. var capPath = function (nbPoints, pathIndex) {
  65090. var pointCap = Array();
  65091. for (var i = 0; i < nbPoints; i++) {
  65092. pointCap.push(path[pathIndex]);
  65093. }
  65094. return pointCap;
  65095. };
  65096. switch (cap) {
  65097. case BABYLON.Mesh.NO_CAP:
  65098. break;
  65099. case BABYLON.Mesh.CAP_START:
  65100. circlePaths[0] = capPath(tessellation, 0);
  65101. circlePaths[1] = circlePaths[2].slice(0);
  65102. break;
  65103. case BABYLON.Mesh.CAP_END:
  65104. circlePaths[index] = circlePaths[index - 1].slice(0);
  65105. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65106. break;
  65107. case BABYLON.Mesh.CAP_ALL:
  65108. circlePaths[0] = capPath(tessellation, 0);
  65109. circlePaths[1] = circlePaths[2].slice(0);
  65110. circlePaths[index] = circlePaths[index - 1].slice(0);
  65111. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65112. break;
  65113. default:
  65114. break;
  65115. }
  65116. return circlePaths;
  65117. };
  65118. var path3D;
  65119. var pathArray;
  65120. if (instance) { // tube update
  65121. var arc = options.arc || instance.arc;
  65122. path3D = (instance.path3D).update(path);
  65123. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  65124. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  65125. instance.path3D = path3D;
  65126. instance.pathArray = pathArray;
  65127. instance.arc = arc;
  65128. instance.radius = radius;
  65129. return instance;
  65130. }
  65131. // tube creation
  65132. path3D = new BABYLON.Path3D(path);
  65133. var newPathArray = new Array();
  65134. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65135. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  65136. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  65137. tube.pathArray = pathArray;
  65138. tube.path3D = path3D;
  65139. tube.tessellation = tessellation;
  65140. tube.cap = cap;
  65141. tube.arc = options.arc;
  65142. tube.radius = radius;
  65143. return tube;
  65144. };
  65145. /**
  65146. * Creates a polyhedron mesh
  65147. * * 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
  65148. * * The parameter `size` (positive float, default 1) sets the polygon size
  65149. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  65150. * * 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`
  65151. * * 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
  65152. * * 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)`)
  65153. * * 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
  65154. * * 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
  65155. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65156. * * 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
  65157. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65158. * @param name defines the name of the mesh
  65159. * @param options defines the options used to create the mesh
  65160. * @param scene defines the hosting scene
  65161. * @returns the polyhedron mesh
  65162. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  65163. */
  65164. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  65165. var polyhedron = new BABYLON.Mesh(name, scene);
  65166. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65167. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  65168. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  65169. vertexData.applyToMesh(polyhedron, options.updatable);
  65170. return polyhedron;
  65171. };
  65172. /**
  65173. * Creates a decal mesh.
  65174. * 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
  65175. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  65176. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  65177. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  65178. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  65179. * @param name defines the name of the mesh
  65180. * @param sourceMesh defines the mesh where the decal must be applied
  65181. * @param options defines the options used to create the mesh
  65182. * @param scene defines the hosting scene
  65183. * @returns the decal mesh
  65184. * @see http://doc.babylonjs.com/how_to/decals
  65185. */
  65186. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  65187. var indices = sourceMesh.getIndices();
  65188. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65189. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65190. var position = options.position || BABYLON.Vector3.Zero();
  65191. var normal = options.normal || BABYLON.Vector3.Up();
  65192. var size = options.size || BABYLON.Vector3.One();
  65193. var angle = options.angle || 0;
  65194. // Getting correct rotation
  65195. if (!normal) {
  65196. var target = new BABYLON.Vector3(0, 0, 1);
  65197. var camera = sourceMesh.getScene().activeCamera;
  65198. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  65199. normal = camera.globalPosition.subtract(cameraWorldTarget);
  65200. }
  65201. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  65202. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  65203. var pitch = Math.atan2(normal.y, len);
  65204. // Matrix
  65205. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  65206. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  65207. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  65208. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  65209. var vertexData = new BABYLON.VertexData();
  65210. vertexData.indices = [];
  65211. vertexData.positions = [];
  65212. vertexData.normals = [];
  65213. vertexData.uvs = [];
  65214. var currentVertexDataIndex = 0;
  65215. var extractDecalVector3 = function (indexId) {
  65216. var result = new BABYLON.PositionNormalVertex();
  65217. if (!indices || !positions || !normals) {
  65218. return result;
  65219. }
  65220. var vertexId = indices[indexId];
  65221. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  65222. // Send vector to decal local world
  65223. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  65224. // Get normal
  65225. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  65226. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  65227. return result;
  65228. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  65229. var clip = function (vertices, axis) {
  65230. if (vertices.length === 0) {
  65231. return vertices;
  65232. }
  65233. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  65234. var clipVertices = function (v0, v1) {
  65235. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  65236. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  65237. };
  65238. var result = new Array();
  65239. for (var index = 0; index < vertices.length; index += 3) {
  65240. var v1Out;
  65241. var v2Out;
  65242. var v3Out;
  65243. var total = 0;
  65244. var nV1 = null;
  65245. var nV2 = null;
  65246. var nV3 = null;
  65247. var nV4 = null;
  65248. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  65249. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  65250. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  65251. v1Out = d1 > 0;
  65252. v2Out = d2 > 0;
  65253. v3Out = d3 > 0;
  65254. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  65255. switch (total) {
  65256. case 0:
  65257. result.push(vertices[index]);
  65258. result.push(vertices[index + 1]);
  65259. result.push(vertices[index + 2]);
  65260. break;
  65261. case 1:
  65262. if (v1Out) {
  65263. nV1 = vertices[index + 1];
  65264. nV2 = vertices[index + 2];
  65265. nV3 = clipVertices(vertices[index], nV1);
  65266. nV4 = clipVertices(vertices[index], nV2);
  65267. }
  65268. if (v2Out) {
  65269. nV1 = vertices[index];
  65270. nV2 = vertices[index + 2];
  65271. nV3 = clipVertices(vertices[index + 1], nV1);
  65272. nV4 = clipVertices(vertices[index + 1], nV2);
  65273. result.push(nV3);
  65274. result.push(nV2.clone());
  65275. result.push(nV1.clone());
  65276. result.push(nV2.clone());
  65277. result.push(nV3.clone());
  65278. result.push(nV4);
  65279. break;
  65280. }
  65281. if (v3Out) {
  65282. nV1 = vertices[index];
  65283. nV2 = vertices[index + 1];
  65284. nV3 = clipVertices(vertices[index + 2], nV1);
  65285. nV4 = clipVertices(vertices[index + 2], nV2);
  65286. }
  65287. if (nV1 && nV2 && nV3 && nV4) {
  65288. result.push(nV1.clone());
  65289. result.push(nV2.clone());
  65290. result.push(nV3);
  65291. result.push(nV4);
  65292. result.push(nV3.clone());
  65293. result.push(nV2.clone());
  65294. }
  65295. break;
  65296. case 2:
  65297. if (!v1Out) {
  65298. nV1 = vertices[index].clone();
  65299. nV2 = clipVertices(nV1, vertices[index + 1]);
  65300. nV3 = clipVertices(nV1, vertices[index + 2]);
  65301. result.push(nV1);
  65302. result.push(nV2);
  65303. result.push(nV3);
  65304. }
  65305. if (!v2Out) {
  65306. nV1 = vertices[index + 1].clone();
  65307. nV2 = clipVertices(nV1, vertices[index + 2]);
  65308. nV3 = clipVertices(nV1, vertices[index]);
  65309. result.push(nV1);
  65310. result.push(nV2);
  65311. result.push(nV3);
  65312. }
  65313. if (!v3Out) {
  65314. nV1 = vertices[index + 2].clone();
  65315. nV2 = clipVertices(nV1, vertices[index]);
  65316. nV3 = clipVertices(nV1, vertices[index + 1]);
  65317. result.push(nV1);
  65318. result.push(nV2);
  65319. result.push(nV3);
  65320. }
  65321. break;
  65322. case 3:
  65323. break;
  65324. }
  65325. }
  65326. return result;
  65327. };
  65328. for (var index = 0; index < indices.length; index += 3) {
  65329. var faceVertices = new Array();
  65330. faceVertices.push(extractDecalVector3(index));
  65331. faceVertices.push(extractDecalVector3(index + 1));
  65332. faceVertices.push(extractDecalVector3(index + 2));
  65333. // Clip
  65334. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  65335. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  65336. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  65337. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  65338. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  65339. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  65340. if (faceVertices.length === 0) {
  65341. continue;
  65342. }
  65343. // Add UVs and get back to world
  65344. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  65345. var vertex = faceVertices[vIndex];
  65346. //TODO check for Int32Array | Uint32Array | Uint16Array
  65347. vertexData.indices.push(currentVertexDataIndex);
  65348. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  65349. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  65350. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  65351. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  65352. currentVertexDataIndex++;
  65353. }
  65354. }
  65355. // Return mesh
  65356. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  65357. vertexData.applyToMesh(decal);
  65358. decal.position = position.clone();
  65359. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  65360. return decal;
  65361. };
  65362. // Privates
  65363. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  65364. // extrusion geometry
  65365. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  65366. var tangents = path3D.getTangents();
  65367. var normals = path3D.getNormals();
  65368. var binormals = path3D.getBinormals();
  65369. var distances = path3D.getDistances();
  65370. var angle = 0;
  65371. var returnScale = function () { return scale !== null ? scale : 1; };
  65372. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  65373. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  65374. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  65375. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65376. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65377. for (var i = 0; i < curve.length; i++) {
  65378. var shapePath = new Array();
  65379. var angleStep = rotate(i, distances[i]);
  65380. var scaleRatio = scl(i, distances[i]);
  65381. for (var p = 0; p < shape.length; p++) {
  65382. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  65383. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  65384. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  65385. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  65386. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  65387. shapePath[p] = rotated;
  65388. }
  65389. shapePaths[index] = shapePath;
  65390. angle += angleStep;
  65391. index++;
  65392. }
  65393. // cap
  65394. var capPath = function (shapePath) {
  65395. var pointCap = Array();
  65396. var barycenter = BABYLON.Vector3.Zero();
  65397. var i;
  65398. for (i = 0; i < shapePath.length; i++) {
  65399. barycenter.addInPlace(shapePath[i]);
  65400. }
  65401. barycenter.scaleInPlace(1.0 / shapePath.length);
  65402. for (i = 0; i < shapePath.length; i++) {
  65403. pointCap.push(barycenter);
  65404. }
  65405. return pointCap;
  65406. };
  65407. switch (cap) {
  65408. case BABYLON.Mesh.NO_CAP:
  65409. break;
  65410. case BABYLON.Mesh.CAP_START:
  65411. shapePaths[0] = capPath(shapePaths[2]);
  65412. shapePaths[1] = shapePaths[2];
  65413. break;
  65414. case BABYLON.Mesh.CAP_END:
  65415. shapePaths[index] = shapePaths[index - 1];
  65416. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65417. break;
  65418. case BABYLON.Mesh.CAP_ALL:
  65419. shapePaths[0] = capPath(shapePaths[2]);
  65420. shapePaths[1] = shapePaths[2];
  65421. shapePaths[index] = shapePaths[index - 1];
  65422. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65423. break;
  65424. default:
  65425. break;
  65426. }
  65427. return shapePaths;
  65428. };
  65429. var path3D;
  65430. var pathArray;
  65431. if (instance) { // instance update
  65432. path3D = (instance.path3D).update(curve);
  65433. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  65434. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  65435. return instance;
  65436. }
  65437. // extruded shape creation
  65438. path3D = new BABYLON.Path3D(curve);
  65439. var newShapePaths = new Array();
  65440. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65441. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  65442. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  65443. extrudedGeneric.pathArray = pathArray;
  65444. extrudedGeneric.path3D = path3D;
  65445. extrudedGeneric.cap = cap;
  65446. return extrudedGeneric;
  65447. };
  65448. return MeshBuilder;
  65449. }());
  65450. BABYLON.MeshBuilder = MeshBuilder;
  65451. })(BABYLON || (BABYLON = {}));
  65452. //# sourceMappingURL=babylon.meshBuilder.js.map
  65453. var BABYLON;
  65454. (function (BABYLON) {
  65455. /**
  65456. * Draco compression (https://google.github.io/draco/)
  65457. *
  65458. * This class wraps the Draco module.
  65459. *
  65460. * **Encoder**
  65461. *
  65462. * The encoder is not currently implemented.
  65463. *
  65464. * **Decoder**
  65465. *
  65466. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  65467. *
  65468. * To update the configuration, use the following code:
  65469. * ```javascript
  65470. * BABYLON.DracoCompression.Configuration = {
  65471. * decoder: {
  65472. * wasmUrl: "<url to the WebAssembly library>",
  65473. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  65474. * fallbackUrl: "<url to the fallback JavaScript library>",
  65475. * }
  65476. * };
  65477. * ```
  65478. *
  65479. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  65480. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  65481. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  65482. *
  65483. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  65484. * ```javascript
  65485. * var dracoCompression = new BABYLON.DracoCompression();
  65486. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  65487. * [BABYLON.VertexBuffer.PositionKind]: 0
  65488. * });
  65489. * ```
  65490. *
  65491. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  65492. */
  65493. var DracoCompression = /** @class */ (function () {
  65494. /**
  65495. * Constructor
  65496. */
  65497. function DracoCompression() {
  65498. }
  65499. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  65500. /**
  65501. * Returns true if the decoder is available.
  65502. */
  65503. get: function () {
  65504. if (typeof DracoDecoderModule !== "undefined") {
  65505. return true;
  65506. }
  65507. var decoder = DracoCompression.Configuration.decoder;
  65508. if (decoder) {
  65509. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65510. return true;
  65511. }
  65512. if (decoder.fallbackUrl) {
  65513. return true;
  65514. }
  65515. }
  65516. return false;
  65517. },
  65518. enumerable: true,
  65519. configurable: true
  65520. });
  65521. /**
  65522. * Stop all async operations and release resources.
  65523. */
  65524. DracoCompression.prototype.dispose = function () {
  65525. };
  65526. /**
  65527. * Decode Draco compressed mesh data to vertex data.
  65528. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65529. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65530. * @returns A promise that resolves with the decoded vertex data
  65531. */
  65532. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65533. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65534. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65535. var module = wrappedModule.module;
  65536. var vertexData = new BABYLON.VertexData();
  65537. var buffer = new module.DecoderBuffer();
  65538. buffer.Init(dataView, dataView.byteLength);
  65539. var decoder = new module.Decoder();
  65540. var geometry;
  65541. var status;
  65542. try {
  65543. var type = decoder.GetEncodedGeometryType(buffer);
  65544. switch (type) {
  65545. case module.TRIANGULAR_MESH:
  65546. geometry = new module.Mesh();
  65547. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65548. break;
  65549. case module.POINT_CLOUD:
  65550. geometry = new module.PointCloud();
  65551. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65552. break;
  65553. default:
  65554. throw new Error("Invalid geometry type " + type);
  65555. }
  65556. if (!status.ok() || !geometry.ptr) {
  65557. throw new Error(status.error_msg());
  65558. }
  65559. var numPoints = geometry.num_points();
  65560. if (type === module.TRIANGULAR_MESH) {
  65561. var numFaces = geometry.num_faces();
  65562. var faceIndices = new module.DracoInt32Array();
  65563. try {
  65564. var indices = new Uint32Array(numFaces * 3);
  65565. for (var i = 0; i < numFaces; i++) {
  65566. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65567. var offset = i * 3;
  65568. indices[offset + 0] = faceIndices.GetValue(0);
  65569. indices[offset + 1] = faceIndices.GetValue(1);
  65570. indices[offset + 2] = faceIndices.GetValue(2);
  65571. }
  65572. vertexData.indices = indices;
  65573. }
  65574. finally {
  65575. module.destroy(faceIndices);
  65576. }
  65577. }
  65578. for (var kind in attributes) {
  65579. var uniqueId = attributes[kind];
  65580. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65581. var dracoData = new module.DracoFloat32Array();
  65582. try {
  65583. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65584. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65585. for (var i = 0; i < babylonData.length; i++) {
  65586. babylonData[i] = dracoData.GetValue(i);
  65587. }
  65588. vertexData.set(babylonData, kind);
  65589. }
  65590. finally {
  65591. module.destroy(dracoData);
  65592. }
  65593. }
  65594. }
  65595. finally {
  65596. if (geometry) {
  65597. module.destroy(geometry);
  65598. }
  65599. module.destroy(decoder);
  65600. module.destroy(buffer);
  65601. }
  65602. return vertexData;
  65603. });
  65604. };
  65605. DracoCompression._GetDecoderModule = function () {
  65606. if (!DracoCompression._DecoderModulePromise) {
  65607. var promise = null;
  65608. var config_1 = {};
  65609. if (typeof DracoDecoderModule !== "undefined") {
  65610. promise = Promise.resolve();
  65611. }
  65612. else {
  65613. var decoder = DracoCompression.Configuration.decoder;
  65614. if (decoder) {
  65615. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65616. promise = Promise.all([
  65617. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65618. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65619. config_1.wasmBinary = data;
  65620. })
  65621. ]);
  65622. }
  65623. else if (decoder.fallbackUrl) {
  65624. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65625. }
  65626. }
  65627. }
  65628. if (!promise) {
  65629. throw new Error("Draco decoder module is not available");
  65630. }
  65631. DracoCompression._DecoderModulePromise = promise.then(function () {
  65632. return new Promise(function (resolve) {
  65633. config_1.onModuleLoaded = function (decoderModule) {
  65634. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65635. resolve({ module: decoderModule });
  65636. };
  65637. DracoDecoderModule(config_1);
  65638. });
  65639. });
  65640. }
  65641. return DracoCompression._DecoderModulePromise;
  65642. };
  65643. DracoCompression._LoadScriptAsync = function (url) {
  65644. return new Promise(function (resolve, reject) {
  65645. BABYLON.Tools.LoadScript(url, function () {
  65646. resolve();
  65647. }, function (message) {
  65648. reject(new Error(message));
  65649. });
  65650. });
  65651. };
  65652. DracoCompression._LoadFileAsync = function (url) {
  65653. return new Promise(function (resolve, reject) {
  65654. BABYLON.Tools.LoadFile(url, function (data) {
  65655. resolve(data);
  65656. }, undefined, undefined, true, function (request, exception) {
  65657. reject(exception);
  65658. });
  65659. });
  65660. };
  65661. /**
  65662. * The configuration. Defaults to the following urls:
  65663. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65664. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65665. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65666. */
  65667. DracoCompression.Configuration = {
  65668. decoder: {
  65669. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65670. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65671. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65672. }
  65673. };
  65674. return DracoCompression;
  65675. }());
  65676. BABYLON.DracoCompression = DracoCompression;
  65677. })(BABYLON || (BABYLON = {}));
  65678. //# sourceMappingURL=babylon.dracoCompression.js.map
  65679. var BABYLON;
  65680. (function (BABYLON) {
  65681. var AudioEngine = /** @class */ (function () {
  65682. function AudioEngine() {
  65683. this._audioContext = null;
  65684. this._audioContextInitialized = false;
  65685. this.canUseWebAudio = false;
  65686. this.WarnedWebAudioUnsupported = false;
  65687. this.unlocked = false;
  65688. this.isMP3supported = false;
  65689. this.isOGGsupported = false;
  65690. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65691. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65692. this.canUseWebAudio = true;
  65693. }
  65694. var audioElem = document.createElement('audio');
  65695. try {
  65696. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65697. this.isMP3supported = true;
  65698. }
  65699. }
  65700. catch (e) {
  65701. // protect error during capability check.
  65702. }
  65703. try {
  65704. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65705. this.isOGGsupported = true;
  65706. }
  65707. }
  65708. catch (e) {
  65709. // protect error during capability check.
  65710. }
  65711. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65712. this._unlockiOSaudio();
  65713. }
  65714. else {
  65715. this.unlocked = true;
  65716. }
  65717. }
  65718. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65719. get: function () {
  65720. if (!this._audioContextInitialized) {
  65721. this._initializeAudioContext();
  65722. }
  65723. return this._audioContext;
  65724. },
  65725. enumerable: true,
  65726. configurable: true
  65727. });
  65728. AudioEngine.prototype._unlockiOSaudio = function () {
  65729. var _this = this;
  65730. var unlockaudio = function () {
  65731. if (!_this.audioContext) {
  65732. return;
  65733. }
  65734. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65735. var source = _this.audioContext.createBufferSource();
  65736. source.buffer = buffer;
  65737. source.connect(_this.audioContext.destination);
  65738. source.start(0);
  65739. setTimeout(function () {
  65740. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65741. _this.unlocked = true;
  65742. window.removeEventListener('touchend', unlockaudio, false);
  65743. if (_this.onAudioUnlocked) {
  65744. _this.onAudioUnlocked();
  65745. }
  65746. }
  65747. }, 0);
  65748. };
  65749. window.addEventListener('touchend', unlockaudio, false);
  65750. };
  65751. AudioEngine.prototype._initializeAudioContext = function () {
  65752. try {
  65753. if (this.canUseWebAudio) {
  65754. this._audioContext = new AudioContext();
  65755. // create a global volume gain node
  65756. this.masterGain = this._audioContext.createGain();
  65757. this.masterGain.gain.value = 1;
  65758. this.masterGain.connect(this._audioContext.destination);
  65759. this._audioContextInitialized = true;
  65760. }
  65761. }
  65762. catch (e) {
  65763. this.canUseWebAudio = false;
  65764. BABYLON.Tools.Error("Web Audio: " + e.message);
  65765. }
  65766. };
  65767. AudioEngine.prototype.dispose = function () {
  65768. if (this.canUseWebAudio && this._audioContextInitialized) {
  65769. if (this._connectedAnalyser && this._audioContext) {
  65770. this._connectedAnalyser.stopDebugCanvas();
  65771. this._connectedAnalyser.dispose();
  65772. this.masterGain.disconnect();
  65773. this.masterGain.connect(this._audioContext.destination);
  65774. this._connectedAnalyser = null;
  65775. }
  65776. this.masterGain.gain.value = 1;
  65777. }
  65778. this.WarnedWebAudioUnsupported = false;
  65779. };
  65780. AudioEngine.prototype.getGlobalVolume = function () {
  65781. if (this.canUseWebAudio && this._audioContextInitialized) {
  65782. return this.masterGain.gain.value;
  65783. }
  65784. else {
  65785. return -1;
  65786. }
  65787. };
  65788. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65789. if (this.canUseWebAudio && this._audioContextInitialized) {
  65790. this.masterGain.gain.value = newVolume;
  65791. }
  65792. };
  65793. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65794. if (this._connectedAnalyser) {
  65795. this._connectedAnalyser.stopDebugCanvas();
  65796. }
  65797. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65798. this._connectedAnalyser = analyser;
  65799. this.masterGain.disconnect();
  65800. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65801. }
  65802. };
  65803. return AudioEngine;
  65804. }());
  65805. BABYLON.AudioEngine = AudioEngine;
  65806. })(BABYLON || (BABYLON = {}));
  65807. //# sourceMappingURL=babylon.audioEngine.js.map
  65808. var BABYLON;
  65809. (function (BABYLON) {
  65810. var Sound = /** @class */ (function () {
  65811. /**
  65812. * Create a sound and attach it to a scene
  65813. * @param name Name of your sound
  65814. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65815. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65816. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65817. */
  65818. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65819. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65820. var _this = this;
  65821. this.autoplay = false;
  65822. this.loop = false;
  65823. this.useCustomAttenuation = false;
  65824. this.spatialSound = false;
  65825. this.refDistance = 1;
  65826. this.rolloffFactor = 1;
  65827. this.maxDistance = 100;
  65828. this.distanceModel = "linear";
  65829. this._panningModel = "equalpower";
  65830. /**
  65831. * Observable event when the current playing sound finishes.
  65832. */
  65833. this.onEndedObservable = new BABYLON.Observable();
  65834. this._playbackRate = 1;
  65835. this._streaming = false;
  65836. this._startTime = 0;
  65837. this._startOffset = 0;
  65838. this._position = BABYLON.Vector3.Zero();
  65839. /** @hidden */
  65840. this._positionInEmitterSpace = false;
  65841. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65842. this._volume = 1;
  65843. this._isReadyToPlay = false;
  65844. this.isPlaying = false;
  65845. this.isPaused = false;
  65846. this._isDirectional = false;
  65847. // Used if you'd like to create a directional sound.
  65848. // If not set, the sound will be omnidirectional
  65849. this._coneInnerAngle = 360;
  65850. this._coneOuterAngle = 360;
  65851. this._coneOuterGain = 0;
  65852. this._isOutputConnected = false;
  65853. this._urlType = "Unknown";
  65854. this.name = name;
  65855. this._scene = scene;
  65856. this._readyToPlayCallback = readyToPlayCallback;
  65857. // Default custom attenuation function is a linear attenuation
  65858. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65859. if (currentDistance < maxDistance) {
  65860. return currentVolume * (1 - currentDistance / maxDistance);
  65861. }
  65862. else {
  65863. return 0;
  65864. }
  65865. };
  65866. if (options) {
  65867. this.autoplay = options.autoplay || false;
  65868. this.loop = options.loop || false;
  65869. // if volume === 0, we need another way to check this option
  65870. if (options.volume !== undefined) {
  65871. this._volume = options.volume;
  65872. }
  65873. this.spatialSound = options.spatialSound || false;
  65874. this.maxDistance = options.maxDistance || 100;
  65875. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65876. this.rolloffFactor = options.rolloffFactor || 1;
  65877. this.refDistance = options.refDistance || 1;
  65878. this.distanceModel = options.distanceModel || "linear";
  65879. this._playbackRate = options.playbackRate || 1;
  65880. this._streaming = options.streaming || false;
  65881. }
  65882. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65883. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65884. this._soundGain.gain.value = this._volume;
  65885. this._inputAudioNode = this._soundGain;
  65886. this._outputAudioNode = this._soundGain;
  65887. if (this.spatialSound) {
  65888. this._createSpatialParameters();
  65889. }
  65890. this._scene.mainSoundTrack.AddSound(this);
  65891. var validParameter = true;
  65892. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65893. if (urlOrArrayBuffer) {
  65894. try {
  65895. if (typeof (urlOrArrayBuffer) === "string") {
  65896. this._urlType = "String";
  65897. }
  65898. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65899. this._urlType = "ArrayBuffer";
  65900. }
  65901. else if (urlOrArrayBuffer instanceof MediaStream) {
  65902. this._urlType = "MediaStream";
  65903. }
  65904. else if (Array.isArray(urlOrArrayBuffer)) {
  65905. this._urlType = "Array";
  65906. }
  65907. var urls = [];
  65908. var codecSupportedFound = false;
  65909. switch (this._urlType) {
  65910. case "MediaStream":
  65911. this._streaming = true;
  65912. this._isReadyToPlay = true;
  65913. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65914. if (this.autoplay) {
  65915. this.play();
  65916. }
  65917. if (this._readyToPlayCallback) {
  65918. this._readyToPlayCallback();
  65919. }
  65920. break;
  65921. case "ArrayBuffer":
  65922. if (urlOrArrayBuffer.byteLength > 0) {
  65923. codecSupportedFound = true;
  65924. this._soundLoaded(urlOrArrayBuffer);
  65925. }
  65926. break;
  65927. case "String":
  65928. urls.push(urlOrArrayBuffer);
  65929. case "Array":
  65930. if (urls.length === 0)
  65931. urls = urlOrArrayBuffer;
  65932. // If we found a supported format, we load it immediately and stop the loop
  65933. for (var i = 0; i < urls.length; i++) {
  65934. var url = urls[i];
  65935. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65936. codecSupportedFound = true;
  65937. }
  65938. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65939. codecSupportedFound = true;
  65940. }
  65941. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65942. codecSupportedFound = true;
  65943. }
  65944. if (url.indexOf("blob:") !== -1) {
  65945. codecSupportedFound = true;
  65946. }
  65947. if (codecSupportedFound) {
  65948. // Loading sound using XHR2
  65949. if (!this._streaming) {
  65950. this._scene._loadFile(url, function (data) {
  65951. _this._soundLoaded(data);
  65952. }, undefined, true, true, function (exception) {
  65953. if (exception) {
  65954. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65955. }
  65956. BABYLON.Tools.Error("Sound creation aborted.");
  65957. _this._scene.mainSoundTrack.RemoveSound(_this);
  65958. });
  65959. }
  65960. // Streaming sound using HTML5 Audio tag
  65961. else {
  65962. this._htmlAudioElement = new Audio(url);
  65963. this._htmlAudioElement.controls = false;
  65964. this._htmlAudioElement.loop = this.loop;
  65965. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65966. this._htmlAudioElement.preload = "auto";
  65967. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65968. _this._isReadyToPlay = true;
  65969. if (_this.autoplay) {
  65970. _this.play();
  65971. }
  65972. if (_this._readyToPlayCallback) {
  65973. _this._readyToPlayCallback();
  65974. }
  65975. });
  65976. document.body.appendChild(this._htmlAudioElement);
  65977. }
  65978. break;
  65979. }
  65980. }
  65981. break;
  65982. default:
  65983. validParameter = false;
  65984. break;
  65985. }
  65986. if (!validParameter) {
  65987. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65988. }
  65989. else {
  65990. if (!codecSupportedFound) {
  65991. this._isReadyToPlay = true;
  65992. // Simulating a ready to play event to avoid breaking code path
  65993. if (this._readyToPlayCallback) {
  65994. window.setTimeout(function () {
  65995. if (_this._readyToPlayCallback) {
  65996. _this._readyToPlayCallback();
  65997. }
  65998. }, 1000);
  65999. }
  66000. }
  66001. }
  66002. }
  66003. catch (ex) {
  66004. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  66005. this._scene.mainSoundTrack.RemoveSound(this);
  66006. }
  66007. }
  66008. }
  66009. else {
  66010. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  66011. this._scene.mainSoundTrack.AddSound(this);
  66012. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  66013. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  66014. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  66015. }
  66016. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  66017. if (this._readyToPlayCallback) {
  66018. window.setTimeout(function () {
  66019. if (_this._readyToPlayCallback) {
  66020. _this._readyToPlayCallback();
  66021. }
  66022. }, 1000);
  66023. }
  66024. }
  66025. }
  66026. Sound.prototype.dispose = function () {
  66027. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66028. if (this.isPlaying) {
  66029. this.stop();
  66030. }
  66031. this._isReadyToPlay = false;
  66032. if (this.soundTrackId === -1) {
  66033. this._scene.mainSoundTrack.RemoveSound(this);
  66034. }
  66035. else {
  66036. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  66037. }
  66038. if (this._soundGain) {
  66039. this._soundGain.disconnect();
  66040. this._soundGain = null;
  66041. }
  66042. if (this._soundPanner) {
  66043. this._soundPanner.disconnect();
  66044. this._soundPanner = null;
  66045. }
  66046. if (this._soundSource) {
  66047. this._soundSource.disconnect();
  66048. this._soundSource = null;
  66049. }
  66050. this._audioBuffer = null;
  66051. if (this._htmlAudioElement) {
  66052. this._htmlAudioElement.pause();
  66053. this._htmlAudioElement.src = "";
  66054. document.body.removeChild(this._htmlAudioElement);
  66055. }
  66056. if (this._streamingSource) {
  66057. this._streamingSource.disconnect();
  66058. }
  66059. if (this._connectedMesh && this._registerFunc) {
  66060. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66061. this._connectedMesh = null;
  66062. }
  66063. }
  66064. };
  66065. Sound.prototype.isReady = function () {
  66066. return this._isReadyToPlay;
  66067. };
  66068. Sound.prototype._soundLoaded = function (audioData) {
  66069. var _this = this;
  66070. if (!BABYLON.Engine.audioEngine.audioContext) {
  66071. return;
  66072. }
  66073. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  66074. _this._audioBuffer = buffer;
  66075. _this._isReadyToPlay = true;
  66076. if (_this.autoplay) {
  66077. _this.play();
  66078. }
  66079. if (_this._readyToPlayCallback) {
  66080. _this._readyToPlayCallback();
  66081. }
  66082. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  66083. };
  66084. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  66085. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66086. this._audioBuffer = audioBuffer;
  66087. this._isReadyToPlay = true;
  66088. }
  66089. };
  66090. Sound.prototype.updateOptions = function (options) {
  66091. if (options) {
  66092. this.loop = options.loop || this.loop;
  66093. this.maxDistance = options.maxDistance || this.maxDistance;
  66094. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  66095. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  66096. this.refDistance = options.refDistance || this.refDistance;
  66097. this.distanceModel = options.distanceModel || this.distanceModel;
  66098. this._playbackRate = options.playbackRate || this._playbackRate;
  66099. this._updateSpatialParameters();
  66100. if (this.isPlaying) {
  66101. if (this._streaming && this._htmlAudioElement) {
  66102. this._htmlAudioElement.playbackRate = this._playbackRate;
  66103. }
  66104. else {
  66105. if (this._soundSource) {
  66106. this._soundSource.playbackRate.value = this._playbackRate;
  66107. }
  66108. }
  66109. }
  66110. }
  66111. };
  66112. Sound.prototype._createSpatialParameters = function () {
  66113. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66114. if (this._scene.headphone) {
  66115. this._panningModel = "HRTF";
  66116. }
  66117. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  66118. this._updateSpatialParameters();
  66119. this._soundPanner.connect(this._outputAudioNode);
  66120. this._inputAudioNode = this._soundPanner;
  66121. }
  66122. };
  66123. Sound.prototype._updateSpatialParameters = function () {
  66124. if (this.spatialSound && this._soundPanner) {
  66125. if (this.useCustomAttenuation) {
  66126. // Tricks to disable in a way embedded Web Audio attenuation
  66127. this._soundPanner.distanceModel = "linear";
  66128. this._soundPanner.maxDistance = Number.MAX_VALUE;
  66129. this._soundPanner.refDistance = 1;
  66130. this._soundPanner.rolloffFactor = 1;
  66131. this._soundPanner.panningModel = this._panningModel;
  66132. }
  66133. else {
  66134. this._soundPanner.distanceModel = this.distanceModel;
  66135. this._soundPanner.maxDistance = this.maxDistance;
  66136. this._soundPanner.refDistance = this.refDistance;
  66137. this._soundPanner.rolloffFactor = this.rolloffFactor;
  66138. this._soundPanner.panningModel = this._panningModel;
  66139. }
  66140. }
  66141. };
  66142. Sound.prototype.switchPanningModelToHRTF = function () {
  66143. this._panningModel = "HRTF";
  66144. this._switchPanningModel();
  66145. };
  66146. Sound.prototype.switchPanningModelToEqualPower = function () {
  66147. this._panningModel = "equalpower";
  66148. this._switchPanningModel();
  66149. };
  66150. Sound.prototype._switchPanningModel = function () {
  66151. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66152. this._soundPanner.panningModel = this._panningModel;
  66153. }
  66154. };
  66155. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  66156. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66157. if (this._isOutputConnected) {
  66158. this._outputAudioNode.disconnect();
  66159. }
  66160. this._outputAudioNode.connect(soundTrackAudioNode);
  66161. this._isOutputConnected = true;
  66162. }
  66163. };
  66164. /**
  66165. * Transform this sound into a directional source
  66166. * @param coneInnerAngle Size of the inner cone in degree
  66167. * @param coneOuterAngle Size of the outer cone in degree
  66168. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  66169. */
  66170. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  66171. if (coneOuterAngle < coneInnerAngle) {
  66172. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  66173. return;
  66174. }
  66175. this._coneInnerAngle = coneInnerAngle;
  66176. this._coneOuterAngle = coneOuterAngle;
  66177. this._coneOuterGain = coneOuterGain;
  66178. this._isDirectional = true;
  66179. if (this.isPlaying && this.loop) {
  66180. this.stop();
  66181. this.play();
  66182. }
  66183. };
  66184. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  66185. /**
  66186. * Gets or sets the inner angle for the directional cone.
  66187. */
  66188. get: function () {
  66189. return this._coneInnerAngle;
  66190. },
  66191. /**
  66192. * Gets or sets the inner angle for the directional cone.
  66193. */
  66194. set: function (value) {
  66195. if (value != this._coneInnerAngle) {
  66196. if (this._coneOuterAngle < value) {
  66197. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66198. return;
  66199. }
  66200. this._coneInnerAngle = value;
  66201. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66202. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66203. }
  66204. }
  66205. },
  66206. enumerable: true,
  66207. configurable: true
  66208. });
  66209. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  66210. /**
  66211. * Gets or sets the outer angle for the directional cone.
  66212. */
  66213. get: function () {
  66214. return this._coneOuterAngle;
  66215. },
  66216. /**
  66217. * Gets or sets the outer angle for the directional cone.
  66218. */
  66219. set: function (value) {
  66220. if (value != this._coneOuterAngle) {
  66221. if (value < this._coneInnerAngle) {
  66222. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66223. return;
  66224. }
  66225. this._coneOuterAngle = value;
  66226. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66227. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66228. }
  66229. }
  66230. },
  66231. enumerable: true,
  66232. configurable: true
  66233. });
  66234. Sound.prototype.setPosition = function (newPosition) {
  66235. this._position = newPosition;
  66236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66237. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66238. }
  66239. };
  66240. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  66241. this._localDirection = newLocalDirection;
  66242. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  66243. this._updateDirection();
  66244. }
  66245. };
  66246. Sound.prototype._updateDirection = function () {
  66247. if (!this._connectedMesh || !this._soundPanner) {
  66248. return;
  66249. }
  66250. var mat = this._connectedMesh.getWorldMatrix();
  66251. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  66252. direction.normalize();
  66253. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  66254. };
  66255. Sound.prototype.updateDistanceFromListener = function () {
  66256. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  66257. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  66258. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  66259. }
  66260. };
  66261. Sound.prototype.setAttenuationFunction = function (callback) {
  66262. this._customAttenuationFunction = callback;
  66263. };
  66264. /**
  66265. * Play the sound
  66266. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  66267. * @param offset (optional) Start the sound setting it at a specific time
  66268. */
  66269. Sound.prototype.play = function (time, offset) {
  66270. var _this = this;
  66271. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  66272. try {
  66273. if (this._startOffset < 0) {
  66274. time = -this._startOffset;
  66275. this._startOffset = 0;
  66276. }
  66277. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66278. if (!this._soundSource || !this._streamingSource) {
  66279. if (this.spatialSound && this._soundPanner) {
  66280. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66281. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66282. }
  66283. if (this._isDirectional) {
  66284. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66285. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66286. this._soundPanner.coneOuterGain = this._coneOuterGain;
  66287. if (this._connectedMesh) {
  66288. this._updateDirection();
  66289. }
  66290. else {
  66291. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  66292. }
  66293. }
  66294. }
  66295. }
  66296. if (this._streaming) {
  66297. if (!this._streamingSource) {
  66298. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  66299. this._htmlAudioElement.onended = function () { _this._onended(); };
  66300. this._htmlAudioElement.playbackRate = this._playbackRate;
  66301. }
  66302. this._streamingSource.disconnect();
  66303. this._streamingSource.connect(this._inputAudioNode);
  66304. if (this._htmlAudioElement) {
  66305. this._htmlAudioElement.play();
  66306. }
  66307. }
  66308. else {
  66309. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  66310. this._soundSource.buffer = this._audioBuffer;
  66311. this._soundSource.connect(this._inputAudioNode);
  66312. this._soundSource.loop = this.loop;
  66313. this._soundSource.playbackRate.value = this._playbackRate;
  66314. this._soundSource.onended = function () { _this._onended(); };
  66315. if (this._soundSource.buffer) {
  66316. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  66317. }
  66318. }
  66319. this._startTime = startTime;
  66320. this.isPlaying = true;
  66321. this.isPaused = false;
  66322. }
  66323. catch (ex) {
  66324. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  66325. }
  66326. }
  66327. };
  66328. Sound.prototype._onended = function () {
  66329. this.isPlaying = false;
  66330. if (this.onended) {
  66331. this.onended();
  66332. }
  66333. this.onEndedObservable.notifyObservers(this);
  66334. };
  66335. /**
  66336. * Stop the sound
  66337. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  66338. */
  66339. Sound.prototype.stop = function (time) {
  66340. if (this.isPlaying) {
  66341. if (this._streaming) {
  66342. if (this._htmlAudioElement) {
  66343. this._htmlAudioElement.pause();
  66344. // Test needed for Firefox or it will generate an Invalid State Error
  66345. if (this._htmlAudioElement.currentTime > 0) {
  66346. this._htmlAudioElement.currentTime = 0;
  66347. }
  66348. }
  66349. else {
  66350. this._streamingSource.disconnect();
  66351. }
  66352. }
  66353. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  66354. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66355. this._soundSource.stop(stopTime);
  66356. this._soundSource.onended = function () { };
  66357. if (!this.isPaused) {
  66358. this._startOffset = 0;
  66359. }
  66360. }
  66361. this.isPlaying = false;
  66362. }
  66363. };
  66364. Sound.prototype.pause = function () {
  66365. if (this.isPlaying) {
  66366. this.isPaused = true;
  66367. if (this._streaming) {
  66368. if (this._htmlAudioElement) {
  66369. this._htmlAudioElement.pause();
  66370. }
  66371. else {
  66372. this._streamingSource.disconnect();
  66373. }
  66374. }
  66375. else if (BABYLON.Engine.audioEngine.audioContext) {
  66376. this.stop(0);
  66377. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  66378. }
  66379. }
  66380. };
  66381. Sound.prototype.setVolume = function (newVolume, time) {
  66382. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  66383. if (time && BABYLON.Engine.audioEngine.audioContext) {
  66384. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  66385. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  66386. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  66387. }
  66388. else {
  66389. this._soundGain.gain.value = newVolume;
  66390. }
  66391. }
  66392. this._volume = newVolume;
  66393. };
  66394. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  66395. this._playbackRate = newPlaybackRate;
  66396. if (this.isPlaying) {
  66397. if (this._streaming && this._htmlAudioElement) {
  66398. this._htmlAudioElement.playbackRate = this._playbackRate;
  66399. }
  66400. else if (this._soundSource) {
  66401. this._soundSource.playbackRate.value = this._playbackRate;
  66402. }
  66403. }
  66404. };
  66405. Sound.prototype.getVolume = function () {
  66406. return this._volume;
  66407. };
  66408. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  66409. var _this = this;
  66410. if (this._connectedMesh && this._registerFunc) {
  66411. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66412. this._registerFunc = null;
  66413. }
  66414. this._connectedMesh = meshToConnectTo;
  66415. if (!this.spatialSound) {
  66416. this.spatialSound = true;
  66417. this._createSpatialParameters();
  66418. if (this.isPlaying && this.loop) {
  66419. this.stop();
  66420. this.play();
  66421. }
  66422. }
  66423. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  66424. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  66425. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  66426. };
  66427. Sound.prototype.detachFromMesh = function () {
  66428. if (this._connectedMesh && this._registerFunc) {
  66429. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66430. this._registerFunc = null;
  66431. this._connectedMesh = null;
  66432. }
  66433. };
  66434. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  66435. if (!node.getBoundingInfo) {
  66436. return;
  66437. }
  66438. var mesh = node;
  66439. if (this._positionInEmitterSpace) {
  66440. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  66441. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  66442. }
  66443. else {
  66444. var boundingInfo = mesh.getBoundingInfo();
  66445. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  66446. }
  66447. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  66448. this._updateDirection();
  66449. }
  66450. };
  66451. Sound.prototype.clone = function () {
  66452. var _this = this;
  66453. if (!this._streaming) {
  66454. var setBufferAndRun = function () {
  66455. if (_this._isReadyToPlay) {
  66456. clonedSound._audioBuffer = _this.getAudioBuffer();
  66457. clonedSound._isReadyToPlay = true;
  66458. if (clonedSound.autoplay) {
  66459. clonedSound.play();
  66460. }
  66461. }
  66462. else {
  66463. window.setTimeout(setBufferAndRun, 300);
  66464. }
  66465. };
  66466. var currentOptions = {
  66467. autoplay: this.autoplay, loop: this.loop,
  66468. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  66469. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  66470. refDistance: this.refDistance, distanceModel: this.distanceModel
  66471. };
  66472. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  66473. if (this.useCustomAttenuation) {
  66474. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  66475. }
  66476. clonedSound.setPosition(this._position);
  66477. clonedSound.setPlaybackRate(this._playbackRate);
  66478. setBufferAndRun();
  66479. return clonedSound;
  66480. }
  66481. // Can't clone a streaming sound
  66482. else {
  66483. return null;
  66484. }
  66485. };
  66486. Sound.prototype.getAudioBuffer = function () {
  66487. return this._audioBuffer;
  66488. };
  66489. Sound.prototype.serialize = function () {
  66490. var serializationObject = {
  66491. name: this.name,
  66492. url: this.name,
  66493. autoplay: this.autoplay,
  66494. loop: this.loop,
  66495. volume: this._volume,
  66496. spatialSound: this.spatialSound,
  66497. maxDistance: this.maxDistance,
  66498. rolloffFactor: this.rolloffFactor,
  66499. refDistance: this.refDistance,
  66500. distanceModel: this.distanceModel,
  66501. playbackRate: this._playbackRate,
  66502. panningModel: this._panningModel,
  66503. soundTrackId: this.soundTrackId
  66504. };
  66505. if (this.spatialSound) {
  66506. if (this._connectedMesh)
  66507. serializationObject.connectedMeshId = this._connectedMesh.id;
  66508. serializationObject.position = this._position.asArray();
  66509. serializationObject.refDistance = this.refDistance;
  66510. serializationObject.distanceModel = this.distanceModel;
  66511. serializationObject.isDirectional = this._isDirectional;
  66512. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  66513. serializationObject.coneInnerAngle = this._coneInnerAngle;
  66514. serializationObject.coneOuterAngle = this._coneOuterAngle;
  66515. serializationObject.coneOuterGain = this._coneOuterGain;
  66516. }
  66517. return serializationObject;
  66518. };
  66519. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  66520. var soundName = parsedSound.name;
  66521. var soundUrl;
  66522. if (parsedSound.url) {
  66523. soundUrl = rootUrl + parsedSound.url;
  66524. }
  66525. else {
  66526. soundUrl = rootUrl + soundName;
  66527. }
  66528. var options = {
  66529. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66530. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66531. rolloffFactor: parsedSound.rolloffFactor,
  66532. refDistance: parsedSound.refDistance,
  66533. distanceModel: parsedSound.distanceModel,
  66534. playbackRate: parsedSound.playbackRate
  66535. };
  66536. var newSound;
  66537. if (!sourceSound) {
  66538. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66539. scene._addPendingData(newSound);
  66540. }
  66541. else {
  66542. var setBufferAndRun = function () {
  66543. if (sourceSound._isReadyToPlay) {
  66544. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66545. newSound._isReadyToPlay = true;
  66546. if (newSound.autoplay) {
  66547. newSound.play();
  66548. }
  66549. }
  66550. else {
  66551. window.setTimeout(setBufferAndRun, 300);
  66552. }
  66553. };
  66554. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66555. setBufferAndRun();
  66556. }
  66557. if (parsedSound.position) {
  66558. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66559. newSound.setPosition(soundPosition);
  66560. }
  66561. if (parsedSound.isDirectional) {
  66562. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66563. if (parsedSound.localDirectionToMesh) {
  66564. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66565. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66566. }
  66567. }
  66568. if (parsedSound.connectedMeshId) {
  66569. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66570. if (connectedMesh) {
  66571. newSound.attachToMesh(connectedMesh);
  66572. }
  66573. }
  66574. return newSound;
  66575. };
  66576. return Sound;
  66577. }());
  66578. BABYLON.Sound = Sound;
  66579. })(BABYLON || (BABYLON = {}));
  66580. //# sourceMappingURL=babylon.sound.js.map
  66581. var BABYLON;
  66582. (function (BABYLON) {
  66583. var SoundTrack = /** @class */ (function () {
  66584. function SoundTrack(scene, options) {
  66585. this.id = -1;
  66586. this._isMainTrack = false;
  66587. this._isInitialized = false;
  66588. this._scene = scene;
  66589. this.soundCollection = new Array();
  66590. this._options = options;
  66591. if (!this._isMainTrack) {
  66592. this._scene.soundTracks.push(this);
  66593. this.id = this._scene.soundTracks.length - 1;
  66594. }
  66595. }
  66596. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66597. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66598. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66599. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66600. if (this._options) {
  66601. if (this._options.volume) {
  66602. this._outputAudioNode.gain.value = this._options.volume;
  66603. }
  66604. if (this._options.mainTrack) {
  66605. this._isMainTrack = this._options.mainTrack;
  66606. }
  66607. }
  66608. this._isInitialized = true;
  66609. }
  66610. };
  66611. SoundTrack.prototype.dispose = function () {
  66612. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66613. if (this._connectedAnalyser) {
  66614. this._connectedAnalyser.stopDebugCanvas();
  66615. }
  66616. while (this.soundCollection.length) {
  66617. this.soundCollection[0].dispose();
  66618. }
  66619. if (this._outputAudioNode) {
  66620. this._outputAudioNode.disconnect();
  66621. }
  66622. this._outputAudioNode = null;
  66623. }
  66624. };
  66625. SoundTrack.prototype.AddSound = function (sound) {
  66626. if (!this._isInitialized) {
  66627. this._initializeSoundTrackAudioGraph();
  66628. }
  66629. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66630. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66631. }
  66632. if (sound.soundTrackId) {
  66633. if (sound.soundTrackId === -1) {
  66634. this._scene.mainSoundTrack.RemoveSound(sound);
  66635. }
  66636. else {
  66637. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66638. }
  66639. }
  66640. this.soundCollection.push(sound);
  66641. sound.soundTrackId = this.id;
  66642. };
  66643. SoundTrack.prototype.RemoveSound = function (sound) {
  66644. var index = this.soundCollection.indexOf(sound);
  66645. if (index !== -1) {
  66646. this.soundCollection.splice(index, 1);
  66647. }
  66648. };
  66649. SoundTrack.prototype.setVolume = function (newVolume) {
  66650. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66651. this._outputAudioNode.gain.value = newVolume;
  66652. }
  66653. };
  66654. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66655. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66656. for (var i = 0; i < this.soundCollection.length; i++) {
  66657. this.soundCollection[i].switchPanningModelToHRTF();
  66658. }
  66659. }
  66660. };
  66661. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66662. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66663. for (var i = 0; i < this.soundCollection.length; i++) {
  66664. this.soundCollection[i].switchPanningModelToEqualPower();
  66665. }
  66666. }
  66667. };
  66668. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66669. if (this._connectedAnalyser) {
  66670. this._connectedAnalyser.stopDebugCanvas();
  66671. }
  66672. this._connectedAnalyser = analyser;
  66673. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66674. this._outputAudioNode.disconnect();
  66675. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66676. }
  66677. };
  66678. return SoundTrack;
  66679. }());
  66680. BABYLON.SoundTrack = SoundTrack;
  66681. })(BABYLON || (BABYLON = {}));
  66682. //# sourceMappingURL=babylon.soundtrack.js.map
  66683. var BABYLON;
  66684. (function (BABYLON) {
  66685. /**
  66686. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66687. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66688. */
  66689. var Analyser = /** @class */ (function () {
  66690. /**
  66691. * Creates a new analyser
  66692. * @param scene defines hosting scene
  66693. */
  66694. function Analyser(scene) {
  66695. /**
  66696. * Gets or sets the smoothing
  66697. * @ignorenaming
  66698. */
  66699. this.SMOOTHING = 0.75;
  66700. /**
  66701. * Gets or sets the FFT table size
  66702. * @ignorenaming
  66703. */
  66704. this.FFT_SIZE = 512;
  66705. /**
  66706. * Gets or sets the bar graph amplitude
  66707. * @ignorenaming
  66708. */
  66709. this.BARGRAPHAMPLITUDE = 256;
  66710. /**
  66711. * Gets or sets the position of the debug canvas
  66712. * @ignorenaming
  66713. */
  66714. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66715. /**
  66716. * Gets or sets the debug canvas size
  66717. * @ignorenaming
  66718. */
  66719. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66720. this._scene = scene;
  66721. this._audioEngine = BABYLON.Engine.audioEngine;
  66722. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66723. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66724. this._webAudioAnalyser.minDecibels = -140;
  66725. this._webAudioAnalyser.maxDecibels = 0;
  66726. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66727. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66728. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66729. }
  66730. }
  66731. /**
  66732. * Get the number of data values you will have to play with for the visualization
  66733. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66734. * @returns a number
  66735. */
  66736. Analyser.prototype.getFrequencyBinCount = function () {
  66737. if (this._audioEngine.canUseWebAudio) {
  66738. return this._webAudioAnalyser.frequencyBinCount;
  66739. }
  66740. else {
  66741. return 0;
  66742. }
  66743. };
  66744. /**
  66745. * Gets the current frequency data as a byte array
  66746. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66747. * @returns a Uint8Array
  66748. */
  66749. Analyser.prototype.getByteFrequencyData = function () {
  66750. if (this._audioEngine.canUseWebAudio) {
  66751. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66752. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66753. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66754. }
  66755. return this._byteFreqs;
  66756. };
  66757. /**
  66758. * Gets the current waveform as a byte array
  66759. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66760. * @returns a Uint8Array
  66761. */
  66762. Analyser.prototype.getByteTimeDomainData = function () {
  66763. if (this._audioEngine.canUseWebAudio) {
  66764. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66765. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66766. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66767. }
  66768. return this._byteTime;
  66769. };
  66770. /**
  66771. * Gets the current frequency data as a float array
  66772. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66773. * @returns a Float32Array
  66774. */
  66775. Analyser.prototype.getFloatFrequencyData = function () {
  66776. if (this._audioEngine.canUseWebAudio) {
  66777. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66778. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66779. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66780. }
  66781. return this._floatFreqs;
  66782. };
  66783. /**
  66784. * Renders the debug canvas
  66785. */
  66786. Analyser.prototype.drawDebugCanvas = function () {
  66787. var _this = this;
  66788. if (this._audioEngine.canUseWebAudio) {
  66789. if (!this._debugCanvas) {
  66790. this._debugCanvas = document.createElement("canvas");
  66791. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66792. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66793. this._debugCanvas.style.position = "absolute";
  66794. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66795. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66796. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66797. document.body.appendChild(this._debugCanvas);
  66798. this._registerFunc = function () {
  66799. _this.drawDebugCanvas();
  66800. };
  66801. this._scene.registerBeforeRender(this._registerFunc);
  66802. }
  66803. if (this._registerFunc && this._debugCanvasContext) {
  66804. var workingArray = this.getByteFrequencyData();
  66805. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66806. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66807. // Draw the frequency domain chart.
  66808. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66809. var value = workingArray[i];
  66810. var percent = value / this.BARGRAPHAMPLITUDE;
  66811. var height = this.DEBUGCANVASSIZE.height * percent;
  66812. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66813. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66814. var hue = i / this.getFrequencyBinCount() * 360;
  66815. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66816. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66817. }
  66818. }
  66819. }
  66820. };
  66821. /**
  66822. * Stops rendering the debug canvas and removes it
  66823. */
  66824. Analyser.prototype.stopDebugCanvas = function () {
  66825. if (this._debugCanvas) {
  66826. if (this._registerFunc) {
  66827. this._scene.unregisterBeforeRender(this._registerFunc);
  66828. this._registerFunc = null;
  66829. }
  66830. document.body.removeChild(this._debugCanvas);
  66831. this._debugCanvas = null;
  66832. this._debugCanvasContext = null;
  66833. }
  66834. };
  66835. /**
  66836. * Connects two audio nodes
  66837. * @param inputAudioNode defines first node to connect
  66838. * @param outputAudioNode defines second node to connect
  66839. */
  66840. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66841. if (this._audioEngine.canUseWebAudio) {
  66842. inputAudioNode.connect(this._webAudioAnalyser);
  66843. this._webAudioAnalyser.connect(outputAudioNode);
  66844. }
  66845. };
  66846. /**
  66847. * Releases all associated resources
  66848. */
  66849. Analyser.prototype.dispose = function () {
  66850. if (this._audioEngine.canUseWebAudio) {
  66851. this._webAudioAnalyser.disconnect();
  66852. }
  66853. };
  66854. return Analyser;
  66855. }());
  66856. BABYLON.Analyser = Analyser;
  66857. })(BABYLON || (BABYLON = {}));
  66858. //# sourceMappingURL=babylon.analyser.js.map
  66859. var BABYLON;
  66860. (function (BABYLON) {
  66861. /**
  66862. * Wraps one or more Sound objects and selects one with random weight for playback.
  66863. */
  66864. var WeightedSound = /** @class */ (function () {
  66865. /**
  66866. * Creates a new WeightedSound from the list of sounds given.
  66867. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66868. * @param sounds Array of Sounds that will be selected from.
  66869. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66870. */
  66871. function WeightedSound(loop, sounds, weights) {
  66872. var _this = this;
  66873. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66874. this.loop = false;
  66875. this._coneInnerAngle = 360;
  66876. this._coneOuterAngle = 360;
  66877. this._volume = 1;
  66878. /** A Sound is currently playing. */
  66879. this.isPlaying = false;
  66880. /** A Sound is currently paused. */
  66881. this.isPaused = false;
  66882. this._sounds = [];
  66883. this._weights = [];
  66884. if (sounds.length !== weights.length) {
  66885. throw new Error('Sounds length does not equal weights length');
  66886. }
  66887. this.loop = loop;
  66888. this._weights = weights;
  66889. // Normalize the weights
  66890. var weightSum = 0;
  66891. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66892. var weight = weights_1[_i];
  66893. weightSum += weight;
  66894. }
  66895. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66896. for (var i = 0; i < this._weights.length; i++) {
  66897. this._weights[i] *= invWeightSum;
  66898. }
  66899. this._sounds = sounds;
  66900. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66901. var sound = _b[_a];
  66902. sound.onEndedObservable.add(function () { _this._onended(); });
  66903. }
  66904. }
  66905. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66906. /**
  66907. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66908. */
  66909. get: function () {
  66910. return this._coneInnerAngle;
  66911. },
  66912. /**
  66913. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66914. */
  66915. set: function (value) {
  66916. if (value !== this._coneInnerAngle) {
  66917. if (this._coneOuterAngle < value) {
  66918. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66919. return;
  66920. }
  66921. this._coneInnerAngle = value;
  66922. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66923. var sound = _a[_i];
  66924. sound.directionalConeInnerAngle = value;
  66925. }
  66926. }
  66927. },
  66928. enumerable: true,
  66929. configurable: true
  66930. });
  66931. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66932. /**
  66933. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66934. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66935. */
  66936. get: function () {
  66937. return this._coneOuterAngle;
  66938. },
  66939. /**
  66940. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66941. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66942. */
  66943. set: function (value) {
  66944. if (value !== this._coneOuterAngle) {
  66945. if (value < this._coneInnerAngle) {
  66946. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66947. return;
  66948. }
  66949. this._coneOuterAngle = value;
  66950. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66951. var sound = _a[_i];
  66952. sound.directionalConeOuterAngle = value;
  66953. }
  66954. }
  66955. },
  66956. enumerable: true,
  66957. configurable: true
  66958. });
  66959. Object.defineProperty(WeightedSound.prototype, "volume", {
  66960. /**
  66961. * Playback volume.
  66962. */
  66963. get: function () {
  66964. return this._volume;
  66965. },
  66966. /**
  66967. * Playback volume.
  66968. */
  66969. set: function (value) {
  66970. if (value !== this._volume) {
  66971. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66972. var sound = _a[_i];
  66973. sound.setVolume(value);
  66974. }
  66975. }
  66976. },
  66977. enumerable: true,
  66978. configurable: true
  66979. });
  66980. WeightedSound.prototype._onended = function () {
  66981. if (this._currentIndex !== undefined) {
  66982. this._sounds[this._currentIndex].autoplay = false;
  66983. }
  66984. if (this.loop && this.isPlaying) {
  66985. this.play();
  66986. }
  66987. else {
  66988. this.isPlaying = false;
  66989. }
  66990. };
  66991. /**
  66992. * Suspend playback
  66993. */
  66994. WeightedSound.prototype.pause = function () {
  66995. this.isPaused = true;
  66996. if (this._currentIndex !== undefined) {
  66997. this._sounds[this._currentIndex].pause();
  66998. }
  66999. };
  67000. /**
  67001. * Stop playback
  67002. */
  67003. WeightedSound.prototype.stop = function () {
  67004. this.isPlaying = false;
  67005. if (this._currentIndex !== undefined) {
  67006. this._sounds[this._currentIndex].stop();
  67007. }
  67008. };
  67009. /**
  67010. * Start playback.
  67011. * @param startOffset Position the clip head at a specific time in seconds.
  67012. */
  67013. WeightedSound.prototype.play = function (startOffset) {
  67014. if (!this.isPaused) {
  67015. this.stop();
  67016. var randomValue = Math.random();
  67017. var total = 0;
  67018. for (var i = 0; i < this._weights.length; i++) {
  67019. total += this._weights[i];
  67020. if (randomValue <= total) {
  67021. this._currentIndex = i;
  67022. break;
  67023. }
  67024. }
  67025. }
  67026. var sound = this._sounds[this._currentIndex];
  67027. if (sound.isReady()) {
  67028. sound.play(0, this.isPaused ? undefined : startOffset);
  67029. }
  67030. else {
  67031. sound.autoplay = true;
  67032. }
  67033. this.isPlaying = true;
  67034. this.isPaused = false;
  67035. };
  67036. return WeightedSound;
  67037. }());
  67038. BABYLON.WeightedSound = WeightedSound;
  67039. })(BABYLON || (BABYLON = {}));
  67040. //# sourceMappingURL=babylon.weightedsound.js.map
  67041. var BABYLON;
  67042. (function (BABYLON) {
  67043. var CubeTexture = /** @class */ (function (_super) {
  67044. __extends(CubeTexture, _super);
  67045. /**
  67046. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  67047. * as prefiltered data.
  67048. * @param rootUrl defines the url of the texture or the root name of the six images
  67049. * @param scene defines the scene the texture is attached to
  67050. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  67051. * @param noMipmap defines if mipmaps should be created or not
  67052. * @param files defines the six files to load for the different faces
  67053. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  67054. * @param onError defines a callback triggered in case of error during load
  67055. * @param format defines the internal format to use for the texture once loaded
  67056. * @param prefiltered defines whether or not the texture is created from prefiltered data
  67057. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  67058. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67059. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67060. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67061. * @return the cube texture
  67062. */
  67063. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  67064. if (extensions === void 0) { extensions = null; }
  67065. if (noMipmap === void 0) { noMipmap = false; }
  67066. if (files === void 0) { files = null; }
  67067. if (onLoad === void 0) { onLoad = null; }
  67068. if (onError === void 0) { onError = null; }
  67069. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67070. if (prefiltered === void 0) { prefiltered = false; }
  67071. if (forcedExtension === void 0) { forcedExtension = null; }
  67072. if (createPolynomials === void 0) { createPolynomials = false; }
  67073. if (lodScale === void 0) { lodScale = 0.8; }
  67074. if (lodOffset === void 0) { lodOffset = 0; }
  67075. var _this = _super.call(this, scene) || this;
  67076. /**
  67077. * Gets or sets the center of the bounding box associated with the cube texture
  67078. * It must define where the camera used to render the texture was set
  67079. */
  67080. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67081. _this._rotationY = 0;
  67082. /** @hidden */
  67083. _this._prefiltered = false;
  67084. _this.name = rootUrl;
  67085. _this.url = rootUrl;
  67086. _this._noMipmap = noMipmap;
  67087. _this.hasAlpha = false;
  67088. _this._format = format;
  67089. _this.isCube = true;
  67090. _this._textureMatrix = BABYLON.Matrix.Identity();
  67091. _this._createPolynomials = createPolynomials;
  67092. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67093. if (!rootUrl && !files) {
  67094. return _this;
  67095. }
  67096. var lastDot = rootUrl.lastIndexOf(".");
  67097. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  67098. var isDDS = (extension === ".dds");
  67099. var isEnv = (extension === ".env");
  67100. if (isEnv) {
  67101. _this.gammaSpace = false;
  67102. _this._prefiltered = false;
  67103. }
  67104. else {
  67105. _this._prefiltered = prefiltered;
  67106. if (prefiltered) {
  67107. _this.gammaSpace = false;
  67108. }
  67109. }
  67110. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  67111. if (!files) {
  67112. if (!isEnv && !isDDS && !extensions) {
  67113. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  67114. }
  67115. files = [];
  67116. if (extensions) {
  67117. for (var index = 0; index < extensions.length; index++) {
  67118. files.push(rootUrl + extensions[index]);
  67119. }
  67120. }
  67121. }
  67122. _this._files = files;
  67123. if (!_this._texture) {
  67124. if (!scene.useDelayedTextureLoading) {
  67125. if (prefiltered) {
  67126. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  67127. }
  67128. else {
  67129. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  67130. }
  67131. }
  67132. else {
  67133. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67134. }
  67135. }
  67136. else if (onLoad) {
  67137. if (_this._texture.isReady) {
  67138. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  67139. }
  67140. else {
  67141. _this._texture.onLoadedObservable.add(onLoad);
  67142. }
  67143. }
  67144. return _this;
  67145. }
  67146. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  67147. get: function () {
  67148. return this._boundingBoxSize;
  67149. },
  67150. /**
  67151. * Gets or sets the size of the bounding box associated with the cube texture
  67152. * When defined, the cubemap will switch to local mode
  67153. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67154. * @example https://www.babylonjs-playground.com/#RNASML
  67155. */
  67156. set: function (value) {
  67157. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67158. return;
  67159. }
  67160. this._boundingBoxSize = value;
  67161. var scene = this.getScene();
  67162. if (scene) {
  67163. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67164. }
  67165. },
  67166. enumerable: true,
  67167. configurable: true
  67168. });
  67169. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  67170. /**
  67171. * Gets texture matrix rotation angle around Y axis radians.
  67172. */
  67173. get: function () {
  67174. return this._rotationY;
  67175. },
  67176. /**
  67177. * Sets texture matrix rotation angle around Y axis in radians.
  67178. */
  67179. set: function (value) {
  67180. this._rotationY = value;
  67181. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  67182. },
  67183. enumerable: true,
  67184. configurable: true
  67185. });
  67186. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  67187. var rootUrlKey = "";
  67188. files.forEach(function (url) { return rootUrlKey += url; });
  67189. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  67190. };
  67191. /**
  67192. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  67193. * @param url defines the url of the prefiltered texture
  67194. * @param scene defines the scene the texture is attached to
  67195. * @param forcedExtension defines the extension of the file if different from the url
  67196. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67197. * @return the prefiltered texture
  67198. */
  67199. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  67200. if (forcedExtension === void 0) { forcedExtension = null; }
  67201. if (createPolynomials === void 0) { createPolynomials = true; }
  67202. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  67203. };
  67204. // Methods
  67205. CubeTexture.prototype.delayLoad = function () {
  67206. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67207. return;
  67208. }
  67209. var scene = this.getScene();
  67210. if (!scene) {
  67211. return;
  67212. }
  67213. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67214. this._texture = this._getFromCache(this.url, this._noMipmap);
  67215. if (!this._texture) {
  67216. if (this._prefiltered) {
  67217. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  67218. }
  67219. else {
  67220. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  67221. }
  67222. }
  67223. };
  67224. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  67225. return this._textureMatrix;
  67226. };
  67227. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67228. this._textureMatrix = value;
  67229. };
  67230. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67231. var texture = BABYLON.SerializationHelper.Parse(function () {
  67232. var prefiltered = false;
  67233. if (parsedTexture.prefiltered) {
  67234. prefiltered = parsedTexture.prefiltered;
  67235. }
  67236. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  67237. }, parsedTexture, scene);
  67238. // Local Cubemaps
  67239. if (parsedTexture.boundingBoxPosition) {
  67240. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  67241. }
  67242. if (parsedTexture.boundingBoxSize) {
  67243. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  67244. }
  67245. // Animations
  67246. if (parsedTexture.animations) {
  67247. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  67248. var parsedAnimation = parsedTexture.animations[animationIndex];
  67249. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67250. }
  67251. }
  67252. return texture;
  67253. };
  67254. CubeTexture.prototype.clone = function () {
  67255. var _this = this;
  67256. return BABYLON.SerializationHelper.Clone(function () {
  67257. var scene = _this.getScene();
  67258. if (!scene) {
  67259. return _this;
  67260. }
  67261. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  67262. }, this);
  67263. };
  67264. __decorate([
  67265. BABYLON.serialize("rotationY")
  67266. ], CubeTexture.prototype, "rotationY", null);
  67267. return CubeTexture;
  67268. }(BABYLON.BaseTexture));
  67269. BABYLON.CubeTexture = CubeTexture;
  67270. })(BABYLON || (BABYLON = {}));
  67271. //# sourceMappingURL=babylon.cubeTexture.js.map
  67272. var BABYLON;
  67273. (function (BABYLON) {
  67274. /**
  67275. * Raw cube texture where the raw buffers are passed in
  67276. */
  67277. var RawCubeTexture = /** @class */ (function (_super) {
  67278. __extends(RawCubeTexture, _super);
  67279. /**
  67280. * Creates a cube texture where the raw buffers are passed in.
  67281. * @param scene defines the scene the texture is attached to
  67282. * @param data defines the array of data to use to create each face
  67283. * @param size defines the size of the textures
  67284. * @param format defines the format of the data
  67285. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  67286. * @param generateMipMaps defines if the engine should generate the mip levels
  67287. * @param invertY defines if data must be stored with Y axis inverted
  67288. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  67289. * @param compression defines the compression used (null by default)
  67290. */
  67291. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  67292. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67293. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67294. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67295. if (invertY === void 0) { invertY = false; }
  67296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67297. if (compression === void 0) { compression = null; }
  67298. var _this = _super.call(this, "", scene) || this;
  67299. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  67300. return _this;
  67301. }
  67302. /**
  67303. * Updates the raw cube texture.
  67304. * @param data defines the data to store
  67305. * @param format defines the data format
  67306. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  67307. * @param invertY defines if data must be stored with Y axis inverted
  67308. * @param compression defines the compression used (null by default)
  67309. * @param level defines which level of the texture to update
  67310. */
  67311. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  67312. if (compression === void 0) { compression = null; }
  67313. if (level === void 0) { level = 0; }
  67314. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  67315. };
  67316. /**
  67317. * Updates a raw cube texture with RGBD encoded data.
  67318. * @param data defines the array of data [mipmap][face] to use to create each face
  67319. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  67320. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67321. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67322. * @returns a promsie that resolves when the operation is complete
  67323. */
  67324. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  67325. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  67326. if (lodScale === void 0) { lodScale = 0.8; }
  67327. if (lodOffset === void 0) { lodOffset = 0; }
  67328. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  67329. };
  67330. /**
  67331. * Clones the raw cube texture.
  67332. * @return a new cube texture
  67333. */
  67334. RawCubeTexture.prototype.clone = function () {
  67335. var _this = this;
  67336. return BABYLON.SerializationHelper.Clone(function () {
  67337. var scene = _this.getScene();
  67338. var internalTexture = _this._texture;
  67339. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  67340. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  67341. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  67342. }
  67343. return texture;
  67344. }, this);
  67345. };
  67346. /** @hidden */
  67347. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  67348. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  67349. internalTexture._bufferViewArrayArray = data;
  67350. internalTexture._lodGenerationScale = lodScale;
  67351. internalTexture._lodGenerationOffset = lodOffset;
  67352. internalTexture._sphericalPolynomial = sphericalPolynomial;
  67353. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  67354. internalTexture.isReady = true;
  67355. });
  67356. };
  67357. return RawCubeTexture;
  67358. }(BABYLON.CubeTexture));
  67359. BABYLON.RawCubeTexture = RawCubeTexture;
  67360. })(BABYLON || (BABYLON = {}));
  67361. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  67362. var BABYLON;
  67363. (function (BABYLON) {
  67364. var RenderTargetTexture = /** @class */ (function (_super) {
  67365. __extends(RenderTargetTexture, _super);
  67366. /**
  67367. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  67368. * or used a shadow, depth texture...
  67369. * @param name The friendly name of the texture
  67370. * @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)
  67371. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  67372. * @param generateMipMaps True if mip maps need to be generated after render.
  67373. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  67374. * @param type The type of the buffer in the RTT (int, half float, float...)
  67375. * @param isCube True if a cube texture needs to be created
  67376. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  67377. * @param generateDepthBuffer True to generate a depth buffer
  67378. * @param generateStencilBuffer True to generate a stencil buffer
  67379. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  67380. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  67381. */
  67382. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  67383. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  67384. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67385. if (isCube === void 0) { isCube = false; }
  67386. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67387. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67388. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  67389. if (isMulti === void 0) { isMulti = false; }
  67390. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67391. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67392. _this.isCube = isCube;
  67393. _this.renderParticles = true;
  67394. _this.renderSprites = false;
  67395. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  67396. _this.ignoreCameraViewport = false;
  67397. // Events
  67398. /**
  67399. * An event triggered when the texture is unbind.
  67400. */
  67401. _this.onBeforeBindObservable = new BABYLON.Observable();
  67402. /**
  67403. * An event triggered when the texture is unbind.
  67404. */
  67405. _this.onAfterUnbindObservable = new BABYLON.Observable();
  67406. /**
  67407. * An event triggered before rendering the texture
  67408. */
  67409. _this.onBeforeRenderObservable = new BABYLON.Observable();
  67410. /**
  67411. * An event triggered after rendering the texture
  67412. */
  67413. _this.onAfterRenderObservable = new BABYLON.Observable();
  67414. /**
  67415. * An event triggered after the texture clear
  67416. */
  67417. _this.onClearObservable = new BABYLON.Observable();
  67418. _this._currentRefreshId = -1;
  67419. _this._refreshRate = 1;
  67420. _this._samples = 1;
  67421. /**
  67422. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  67423. * It must define where the camera used to render the texture is set
  67424. */
  67425. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67426. scene = _this.getScene();
  67427. if (!scene) {
  67428. return _this;
  67429. }
  67430. _this.renderList = new Array();
  67431. _this._engine = scene.getEngine();
  67432. _this.name = name;
  67433. _this.isRenderTarget = true;
  67434. _this._initialSizeParameter = size;
  67435. _this._processSizeParameter(size);
  67436. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  67437. });
  67438. _this._generateMipMaps = generateMipMaps ? true : false;
  67439. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  67440. // Rendering groups
  67441. _this._renderingManager = new BABYLON.RenderingManager(scene);
  67442. _this._renderingManager._useSceneAutoClearSetup = true;
  67443. if (isMulti) {
  67444. return _this;
  67445. }
  67446. _this._renderTargetOptions = {
  67447. generateMipMaps: generateMipMaps,
  67448. type: type,
  67449. format: format,
  67450. samplingMode: samplingMode,
  67451. generateDepthBuffer: generateDepthBuffer,
  67452. generateStencilBuffer: generateStencilBuffer
  67453. };
  67454. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  67455. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67456. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67457. }
  67458. if (isCube) {
  67459. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  67460. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  67461. _this._textureMatrix = BABYLON.Matrix.Identity();
  67462. }
  67463. else {
  67464. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  67465. }
  67466. return _this;
  67467. }
  67468. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  67469. get: function () {
  67470. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  67471. },
  67472. enumerable: true,
  67473. configurable: true
  67474. });
  67475. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  67476. get: function () {
  67477. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  67478. },
  67479. enumerable: true,
  67480. configurable: true
  67481. });
  67482. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  67483. get: function () {
  67484. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  67485. },
  67486. enumerable: true,
  67487. configurable: true
  67488. });
  67489. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  67490. /**
  67491. * Use this list to define the list of mesh you want to render.
  67492. */
  67493. get: function () {
  67494. return this._renderList;
  67495. },
  67496. set: function (value) {
  67497. this._renderList = value;
  67498. if (this._renderList) {
  67499. this._hookArray(this._renderList);
  67500. }
  67501. },
  67502. enumerable: true,
  67503. configurable: true
  67504. });
  67505. RenderTargetTexture.prototype._hookArray = function (array) {
  67506. var _this = this;
  67507. var oldPush = array.push;
  67508. array.push = function () {
  67509. var items = [];
  67510. for (var _i = 0; _i < arguments.length; _i++) {
  67511. items[_i] = arguments[_i];
  67512. }
  67513. var result = oldPush.apply(array, items);
  67514. _this.getScene().meshes.forEach(function (mesh) {
  67515. mesh._markSubMeshesAsLightDirty();
  67516. });
  67517. return result;
  67518. };
  67519. var oldSplice = array.splice;
  67520. array.splice = function (index, deleteCount) {
  67521. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67522. _this.getScene().meshes.forEach(function (mesh) {
  67523. mesh._markSubMeshesAsLightDirty();
  67524. });
  67525. return deleted;
  67526. };
  67527. };
  67528. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  67529. set: function (callback) {
  67530. if (this._onAfterUnbindObserver) {
  67531. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  67532. }
  67533. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  67534. },
  67535. enumerable: true,
  67536. configurable: true
  67537. });
  67538. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  67539. set: function (callback) {
  67540. if (this._onBeforeRenderObserver) {
  67541. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67542. }
  67543. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67544. },
  67545. enumerable: true,
  67546. configurable: true
  67547. });
  67548. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  67549. set: function (callback) {
  67550. if (this._onAfterRenderObserver) {
  67551. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67552. }
  67553. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67554. },
  67555. enumerable: true,
  67556. configurable: true
  67557. });
  67558. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  67559. set: function (callback) {
  67560. if (this._onClearObserver) {
  67561. this.onClearObservable.remove(this._onClearObserver);
  67562. }
  67563. this._onClearObserver = this.onClearObservable.add(callback);
  67564. },
  67565. enumerable: true,
  67566. configurable: true
  67567. });
  67568. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  67569. get: function () {
  67570. return this._renderTargetOptions;
  67571. },
  67572. enumerable: true,
  67573. configurable: true
  67574. });
  67575. RenderTargetTexture.prototype._onRatioRescale = function () {
  67576. if (this._sizeRatio) {
  67577. this.resize(this._initialSizeParameter);
  67578. }
  67579. };
  67580. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  67581. get: function () {
  67582. return this._boundingBoxSize;
  67583. },
  67584. /**
  67585. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  67586. * When defined, the cubemap will switch to local mode
  67587. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67588. * @example https://www.babylonjs-playground.com/#RNASML
  67589. */
  67590. set: function (value) {
  67591. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67592. return;
  67593. }
  67594. this._boundingBoxSize = value;
  67595. var scene = this.getScene();
  67596. if (scene) {
  67597. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67598. }
  67599. },
  67600. enumerable: true,
  67601. configurable: true
  67602. });
  67603. /**
  67604. * Creates a depth stencil texture.
  67605. * This is only available in WebGL 2 or with the depth texture extension available.
  67606. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  67607. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  67608. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  67609. */
  67610. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  67611. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  67612. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  67613. if (generateStencil === void 0) { generateStencil = false; }
  67614. if (!this.getScene()) {
  67615. return;
  67616. }
  67617. var engine = this.getScene().getEngine();
  67618. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  67619. bilinearFiltering: bilinearFiltering,
  67620. comparisonFunction: comparisonFunction,
  67621. generateStencil: generateStencil,
  67622. isCube: this.isCube
  67623. });
  67624. engine.setFrameBufferDepthStencilTexture(this);
  67625. };
  67626. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  67627. if (size.ratio) {
  67628. this._sizeRatio = size.ratio;
  67629. this._size = {
  67630. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  67631. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  67632. };
  67633. }
  67634. else {
  67635. this._size = size;
  67636. }
  67637. };
  67638. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  67639. get: function () {
  67640. return this._samples;
  67641. },
  67642. set: function (value) {
  67643. if (this._samples === value) {
  67644. return;
  67645. }
  67646. var scene = this.getScene();
  67647. if (!scene) {
  67648. return;
  67649. }
  67650. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  67651. },
  67652. enumerable: true,
  67653. configurable: true
  67654. });
  67655. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  67656. this._currentRefreshId = -1;
  67657. };
  67658. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  67659. get: function () {
  67660. return this._refreshRate;
  67661. },
  67662. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67663. set: function (value) {
  67664. this._refreshRate = value;
  67665. this.resetRefreshCounter();
  67666. },
  67667. enumerable: true,
  67668. configurable: true
  67669. });
  67670. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  67671. if (!this._postProcessManager) {
  67672. var scene = this.getScene();
  67673. if (!scene) {
  67674. return;
  67675. }
  67676. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  67677. this._postProcesses = new Array();
  67678. }
  67679. this._postProcesses.push(postProcess);
  67680. this._postProcesses[0].autoClear = false;
  67681. };
  67682. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  67683. if (!this._postProcesses) {
  67684. return;
  67685. }
  67686. if (dispose) {
  67687. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  67688. var postProcess = _a[_i];
  67689. postProcess.dispose();
  67690. }
  67691. }
  67692. this._postProcesses = [];
  67693. };
  67694. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  67695. if (!this._postProcesses) {
  67696. return;
  67697. }
  67698. var index = this._postProcesses.indexOf(postProcess);
  67699. if (index === -1) {
  67700. return;
  67701. }
  67702. this._postProcesses.splice(index, 1);
  67703. if (this._postProcesses.length > 0) {
  67704. this._postProcesses[0].autoClear = false;
  67705. }
  67706. };
  67707. /** @hidden */
  67708. RenderTargetTexture.prototype._shouldRender = function () {
  67709. if (this._currentRefreshId === -1) { // At least render once
  67710. this._currentRefreshId = 1;
  67711. return true;
  67712. }
  67713. if (this.refreshRate === this._currentRefreshId) {
  67714. this._currentRefreshId = 1;
  67715. return true;
  67716. }
  67717. this._currentRefreshId++;
  67718. return false;
  67719. };
  67720. RenderTargetTexture.prototype.getRenderSize = function () {
  67721. if (this._size.width) {
  67722. return this._size.width;
  67723. }
  67724. return this._size;
  67725. };
  67726. RenderTargetTexture.prototype.getRenderWidth = function () {
  67727. if (this._size.width) {
  67728. return this._size.width;
  67729. }
  67730. return this._size;
  67731. };
  67732. RenderTargetTexture.prototype.getRenderHeight = function () {
  67733. if (this._size.width) {
  67734. return this._size.height;
  67735. }
  67736. return this._size;
  67737. };
  67738. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  67739. get: function () {
  67740. return true;
  67741. },
  67742. enumerable: true,
  67743. configurable: true
  67744. });
  67745. RenderTargetTexture.prototype.scale = function (ratio) {
  67746. var newSize = this.getRenderSize() * ratio;
  67747. this.resize(newSize);
  67748. };
  67749. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  67750. if (this.isCube) {
  67751. return this._textureMatrix;
  67752. }
  67753. return _super.prototype.getReflectionTextureMatrix.call(this);
  67754. };
  67755. RenderTargetTexture.prototype.resize = function (size) {
  67756. this.releaseInternalTexture();
  67757. var scene = this.getScene();
  67758. if (!scene) {
  67759. return;
  67760. }
  67761. this._processSizeParameter(size);
  67762. if (this.isCube) {
  67763. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  67764. }
  67765. else {
  67766. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  67767. }
  67768. };
  67769. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  67770. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  67771. if (dumpForDebug === void 0) { dumpForDebug = false; }
  67772. var scene = this.getScene();
  67773. if (!scene) {
  67774. return;
  67775. }
  67776. var engine = scene.getEngine();
  67777. if (this.useCameraPostProcesses !== undefined) {
  67778. useCameraPostProcess = this.useCameraPostProcesses;
  67779. }
  67780. if (this._waitingRenderList) {
  67781. this.renderList = [];
  67782. for (var index = 0; index < this._waitingRenderList.length; index++) {
  67783. var id = this._waitingRenderList[index];
  67784. var mesh_1 = scene.getMeshByID(id);
  67785. if (mesh_1) {
  67786. this.renderList.push(mesh_1);
  67787. }
  67788. }
  67789. delete this._waitingRenderList;
  67790. }
  67791. // Is predicate defined?
  67792. if (this.renderListPredicate) {
  67793. if (this.renderList) {
  67794. this.renderList.splice(0); // Clear previous renderList
  67795. }
  67796. else {
  67797. this.renderList = [];
  67798. }
  67799. var scene = this.getScene();
  67800. if (!scene) {
  67801. return;
  67802. }
  67803. var sceneMeshes = scene.meshes;
  67804. for (var index = 0; index < sceneMeshes.length; index++) {
  67805. var mesh = sceneMeshes[index];
  67806. if (this.renderListPredicate(mesh)) {
  67807. this.renderList.push(mesh);
  67808. }
  67809. }
  67810. }
  67811. this.onBeforeBindObservable.notifyObservers(this);
  67812. // Set custom projection.
  67813. // Needs to be before binding to prevent changing the aspect ratio.
  67814. var camera;
  67815. if (this.activeCamera) {
  67816. camera = this.activeCamera;
  67817. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67818. if (this.activeCamera !== scene.activeCamera) {
  67819. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  67820. }
  67821. }
  67822. else {
  67823. camera = scene.activeCamera;
  67824. if (camera) {
  67825. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67826. }
  67827. }
  67828. // Prepare renderingManager
  67829. this._renderingManager.reset();
  67830. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  67831. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  67832. var sceneRenderId = scene.getRenderId();
  67833. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  67834. var mesh = currentRenderList[meshIndex];
  67835. if (mesh) {
  67836. if (!mesh.isReady(this.refreshRate === 0)) {
  67837. this.resetRefreshCounter();
  67838. continue;
  67839. }
  67840. mesh._preActivateForIntermediateRendering(sceneRenderId);
  67841. var isMasked = void 0;
  67842. if (!this.renderList && camera) {
  67843. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  67844. }
  67845. else {
  67846. isMasked = false;
  67847. }
  67848. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  67849. mesh._activate(sceneRenderId);
  67850. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  67851. var subMesh = mesh.subMeshes[subIndex];
  67852. scene._activeIndices.addCount(subMesh.indexCount, false);
  67853. this._renderingManager.dispatch(subMesh, mesh);
  67854. }
  67855. }
  67856. }
  67857. }
  67858. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  67859. var particleSystem = scene.particleSystems[particleIndex];
  67860. var emitter = particleSystem.emitter;
  67861. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  67862. continue;
  67863. }
  67864. if (currentRenderList.indexOf(emitter) >= 0) {
  67865. this._renderingManager.dispatchParticles(particleSystem);
  67866. }
  67867. }
  67868. if (this.isCube) {
  67869. for (var face = 0; face < 6; face++) {
  67870. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67871. scene.incrementRenderId();
  67872. scene.resetCachedMaterial();
  67873. }
  67874. }
  67875. else {
  67876. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67877. }
  67878. this.onAfterUnbindObservable.notifyObservers(this);
  67879. if (scene.activeCamera) {
  67880. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  67881. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  67882. }
  67883. engine.setViewport(scene.activeCamera.viewport);
  67884. }
  67885. scene.resetCachedMaterial();
  67886. };
  67887. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  67888. var minimum = 128;
  67889. var x = renderDimension * scale;
  67890. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  67891. // Ensure we don't exceed the render dimension (while staying POT)
  67892. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  67893. };
  67894. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67895. var _this = this;
  67896. if (!this._texture) {
  67897. return;
  67898. }
  67899. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  67900. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67901. });
  67902. };
  67903. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  67904. var scene = this.getScene();
  67905. if (!scene) {
  67906. return;
  67907. }
  67908. var engine = scene.getEngine();
  67909. if (!this._texture) {
  67910. return;
  67911. }
  67912. // Bind
  67913. if (this._postProcessManager) {
  67914. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  67915. }
  67916. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  67917. if (this._texture) {
  67918. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  67919. }
  67920. }
  67921. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  67922. // Clear
  67923. if (this.onClearObservable.hasObservers()) {
  67924. this.onClearObservable.notifyObservers(engine);
  67925. }
  67926. else {
  67927. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  67928. }
  67929. if (!this._doNotChangeAspectRatio) {
  67930. scene.updateTransformMatrix(true);
  67931. }
  67932. // Render
  67933. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  67934. if (this._postProcessManager) {
  67935. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  67936. }
  67937. else if (useCameraPostProcess) {
  67938. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  67939. }
  67940. if (!this._doNotChangeAspectRatio) {
  67941. scene.updateTransformMatrix(true);
  67942. }
  67943. // Dump ?
  67944. if (dumpForDebug) {
  67945. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  67946. }
  67947. // Unbind
  67948. if (!this.isCube || faceIndex === 5) {
  67949. if (this.isCube) {
  67950. if (faceIndex === 5) {
  67951. engine.generateMipMapsForCubemap(this._texture);
  67952. }
  67953. }
  67954. this.unbindFrameBuffer(engine, faceIndex);
  67955. }
  67956. else {
  67957. this.onAfterRenderObservable.notifyObservers(faceIndex);
  67958. }
  67959. };
  67960. /**
  67961. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  67962. * This allowed control for front to back rendering or reversly depending of the special needs.
  67963. *
  67964. * @param renderingGroupId The rendering group id corresponding to its index
  67965. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  67966. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  67967. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  67968. */
  67969. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  67970. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  67971. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  67972. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  67973. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  67974. };
  67975. /**
  67976. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67977. *
  67978. * @param renderingGroupId The rendering group id corresponding to its index
  67979. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67980. */
  67981. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67982. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67983. this._renderingManager._useSceneAutoClearSetup = false;
  67984. };
  67985. RenderTargetTexture.prototype.clone = function () {
  67986. var textureSize = this.getSize();
  67987. 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);
  67988. // Base texture
  67989. newTexture.hasAlpha = this.hasAlpha;
  67990. newTexture.level = this.level;
  67991. // RenderTarget Texture
  67992. newTexture.coordinatesMode = this.coordinatesMode;
  67993. if (this.renderList) {
  67994. newTexture.renderList = this.renderList.slice(0);
  67995. }
  67996. return newTexture;
  67997. };
  67998. RenderTargetTexture.prototype.serialize = function () {
  67999. if (!this.name) {
  68000. return null;
  68001. }
  68002. var serializationObject = _super.prototype.serialize.call(this);
  68003. serializationObject.renderTargetSize = this.getRenderSize();
  68004. serializationObject.renderList = [];
  68005. if (this.renderList) {
  68006. for (var index = 0; index < this.renderList.length; index++) {
  68007. serializationObject.renderList.push(this.renderList[index].id);
  68008. }
  68009. }
  68010. return serializationObject;
  68011. };
  68012. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  68013. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  68014. var objBuffer = this.getInternalTexture();
  68015. var scene = this.getScene();
  68016. if (objBuffer && scene) {
  68017. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  68018. }
  68019. };
  68020. RenderTargetTexture.prototype.dispose = function () {
  68021. if (this._postProcessManager) {
  68022. this._postProcessManager.dispose();
  68023. this._postProcessManager = null;
  68024. }
  68025. this.clearPostProcesses(true);
  68026. if (this._resizeObserver) {
  68027. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  68028. this._resizeObserver = null;
  68029. }
  68030. this.renderList = null;
  68031. // Remove from custom render targets
  68032. var scene = this.getScene();
  68033. if (!scene) {
  68034. return;
  68035. }
  68036. var index = scene.customRenderTargets.indexOf(this);
  68037. if (index >= 0) {
  68038. scene.customRenderTargets.splice(index, 1);
  68039. }
  68040. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  68041. var camera = _a[_i];
  68042. index = camera.customRenderTargets.indexOf(this);
  68043. if (index >= 0) {
  68044. camera.customRenderTargets.splice(index, 1);
  68045. }
  68046. }
  68047. _super.prototype.dispose.call(this);
  68048. };
  68049. /** @hidden */
  68050. RenderTargetTexture.prototype._rebuild = function () {
  68051. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68052. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68053. }
  68054. if (this._postProcessManager) {
  68055. this._postProcessManager._rebuild();
  68056. }
  68057. };
  68058. /**
  68059. * Clear the info related to rendering groups preventing retention point in material dispose.
  68060. */
  68061. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  68062. if (this._renderingManager) {
  68063. this._renderingManager.freeRenderingGroups();
  68064. }
  68065. };
  68066. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  68067. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  68068. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  68069. return RenderTargetTexture;
  68070. }(BABYLON.Texture));
  68071. BABYLON.RenderTargetTexture = RenderTargetTexture;
  68072. })(BABYLON || (BABYLON = {}));
  68073. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  68074. var BABYLON;
  68075. (function (BABYLON) {
  68076. ;
  68077. var MultiRenderTarget = /** @class */ (function (_super) {
  68078. __extends(MultiRenderTarget, _super);
  68079. function MultiRenderTarget(name, size, count, scene, options) {
  68080. var _this = this;
  68081. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  68082. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  68083. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  68084. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  68085. _this._engine = scene.getEngine();
  68086. if (!_this.isSupported) {
  68087. _this.dispose();
  68088. return;
  68089. }
  68090. var types = [];
  68091. var samplingModes = [];
  68092. for (var i = 0; i < count; i++) {
  68093. if (options && options.types && options.types[i] !== undefined) {
  68094. types.push(options.types[i]);
  68095. }
  68096. else {
  68097. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68098. }
  68099. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  68100. samplingModes.push(options.samplingModes[i]);
  68101. }
  68102. else {
  68103. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68104. }
  68105. }
  68106. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  68107. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  68108. _this._size = size;
  68109. _this._multiRenderTargetOptions = {
  68110. samplingModes: samplingModes,
  68111. generateMipMaps: generateMipMaps,
  68112. generateDepthBuffer: generateDepthBuffer,
  68113. generateStencilBuffer: generateStencilBuffer,
  68114. generateDepthTexture: generateDepthTexture,
  68115. types: types,
  68116. textureCount: count
  68117. };
  68118. _this._createInternalTextures();
  68119. _this._createTextures();
  68120. return _this;
  68121. }
  68122. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  68123. get: function () {
  68124. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  68125. },
  68126. enumerable: true,
  68127. configurable: true
  68128. });
  68129. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  68130. get: function () {
  68131. return this._textures;
  68132. },
  68133. enumerable: true,
  68134. configurable: true
  68135. });
  68136. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  68137. get: function () {
  68138. return this._textures[this._textures.length - 1];
  68139. },
  68140. enumerable: true,
  68141. configurable: true
  68142. });
  68143. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  68144. set: function (wrap) {
  68145. if (this._textures) {
  68146. for (var i = 0; i < this._textures.length; i++) {
  68147. this._textures[i].wrapU = wrap;
  68148. }
  68149. }
  68150. },
  68151. enumerable: true,
  68152. configurable: true
  68153. });
  68154. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  68155. set: function (wrap) {
  68156. if (this._textures) {
  68157. for (var i = 0; i < this._textures.length; i++) {
  68158. this._textures[i].wrapV = wrap;
  68159. }
  68160. }
  68161. },
  68162. enumerable: true,
  68163. configurable: true
  68164. });
  68165. /** @hidden */
  68166. MultiRenderTarget.prototype._rebuild = function () {
  68167. this.releaseInternalTextures();
  68168. this._createInternalTextures();
  68169. for (var i = 0; i < this._internalTextures.length; i++) {
  68170. var texture = this._textures[i];
  68171. texture._texture = this._internalTextures[i];
  68172. }
  68173. // Keeps references to frame buffer and stencil/depth buffer
  68174. this._texture = this._internalTextures[0];
  68175. };
  68176. MultiRenderTarget.prototype._createInternalTextures = function () {
  68177. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  68178. };
  68179. MultiRenderTarget.prototype._createTextures = function () {
  68180. this._textures = [];
  68181. for (var i = 0; i < this._internalTextures.length; i++) {
  68182. var texture = new BABYLON.Texture(null, this.getScene());
  68183. texture._texture = this._internalTextures[i];
  68184. this._textures.push(texture);
  68185. }
  68186. // Keeps references to frame buffer and stencil/depth buffer
  68187. this._texture = this._internalTextures[0];
  68188. };
  68189. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  68190. get: function () {
  68191. return this._samples;
  68192. },
  68193. set: function (value) {
  68194. if (this._samples === value) {
  68195. return;
  68196. }
  68197. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  68198. },
  68199. enumerable: true,
  68200. configurable: true
  68201. });
  68202. MultiRenderTarget.prototype.resize = function (size) {
  68203. this.releaseInternalTextures();
  68204. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  68205. this._createInternalTextures();
  68206. };
  68207. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68208. var _this = this;
  68209. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  68210. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68211. });
  68212. };
  68213. MultiRenderTarget.prototype.dispose = function () {
  68214. this.releaseInternalTextures();
  68215. _super.prototype.dispose.call(this);
  68216. };
  68217. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  68218. if (!this._internalTextures) {
  68219. return;
  68220. }
  68221. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  68222. if (this._internalTextures[i] !== undefined) {
  68223. this._internalTextures[i].dispose();
  68224. this._internalTextures.splice(i, 1);
  68225. }
  68226. }
  68227. };
  68228. return MultiRenderTarget;
  68229. }(BABYLON.RenderTargetTexture));
  68230. BABYLON.MultiRenderTarget = MultiRenderTarget;
  68231. })(BABYLON || (BABYLON = {}));
  68232. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  68233. var BABYLON;
  68234. (function (BABYLON) {
  68235. var MirrorTexture = /** @class */ (function (_super) {
  68236. __extends(MirrorTexture, _super);
  68237. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  68238. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68240. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  68241. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  68242. _this.scene = scene;
  68243. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  68244. _this._transformMatrix = BABYLON.Matrix.Zero();
  68245. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  68246. _this._adaptiveBlurKernel = 0;
  68247. _this._blurKernelX = 0;
  68248. _this._blurKernelY = 0;
  68249. _this._blurRatio = 1.0;
  68250. _this.ignoreCameraViewport = true;
  68251. _this._updateGammaSpace();
  68252. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  68253. _this._updateGammaSpace;
  68254. });
  68255. _this.onBeforeRenderObservable.add(function () {
  68256. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  68257. _this._savedViewMatrix = scene.getViewMatrix();
  68258. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  68259. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  68260. scene.clipPlane = _this.mirrorPlane;
  68261. scene.getEngine().cullBackFaces = false;
  68262. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  68263. });
  68264. _this.onAfterRenderObservable.add(function () {
  68265. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  68266. scene.getEngine().cullBackFaces = true;
  68267. scene._mirroredCameraPosition = null;
  68268. delete scene.clipPlane;
  68269. });
  68270. return _this;
  68271. }
  68272. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  68273. get: function () {
  68274. return this._blurRatio;
  68275. },
  68276. set: function (value) {
  68277. if (this._blurRatio === value) {
  68278. return;
  68279. }
  68280. this._blurRatio = value;
  68281. this._preparePostProcesses();
  68282. },
  68283. enumerable: true,
  68284. configurable: true
  68285. });
  68286. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  68287. set: function (value) {
  68288. this._adaptiveBlurKernel = value;
  68289. this._autoComputeBlurKernel();
  68290. },
  68291. enumerable: true,
  68292. configurable: true
  68293. });
  68294. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  68295. set: function (value) {
  68296. this.blurKernelX = value;
  68297. this.blurKernelY = value;
  68298. },
  68299. enumerable: true,
  68300. configurable: true
  68301. });
  68302. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  68303. get: function () {
  68304. return this._blurKernelX;
  68305. },
  68306. set: function (value) {
  68307. if (this._blurKernelX === value) {
  68308. return;
  68309. }
  68310. this._blurKernelX = value;
  68311. this._preparePostProcesses();
  68312. },
  68313. enumerable: true,
  68314. configurable: true
  68315. });
  68316. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  68317. get: function () {
  68318. return this._blurKernelY;
  68319. },
  68320. set: function (value) {
  68321. if (this._blurKernelY === value) {
  68322. return;
  68323. }
  68324. this._blurKernelY = value;
  68325. this._preparePostProcesses();
  68326. },
  68327. enumerable: true,
  68328. configurable: true
  68329. });
  68330. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  68331. var engine = this.getScene().getEngine();
  68332. var dw = this.getRenderWidth() / engine.getRenderWidth();
  68333. var dh = this.getRenderHeight() / engine.getRenderHeight();
  68334. this.blurKernelX = this._adaptiveBlurKernel * dw;
  68335. this.blurKernelY = this._adaptiveBlurKernel * dh;
  68336. };
  68337. MirrorTexture.prototype._onRatioRescale = function () {
  68338. if (this._sizeRatio) {
  68339. this.resize(this._initialSizeParameter);
  68340. if (!this._adaptiveBlurKernel) {
  68341. this._preparePostProcesses();
  68342. }
  68343. }
  68344. if (this._adaptiveBlurKernel) {
  68345. this._autoComputeBlurKernel();
  68346. }
  68347. };
  68348. MirrorTexture.prototype._updateGammaSpace = function () {
  68349. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  68350. };
  68351. MirrorTexture.prototype._preparePostProcesses = function () {
  68352. this.clearPostProcesses(true);
  68353. if (this._blurKernelX && this._blurKernelY) {
  68354. var engine = this.getScene().getEngine();
  68355. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68356. 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);
  68357. this._blurX.autoClear = false;
  68358. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  68359. this._blurX.inputTexture = this._texture;
  68360. }
  68361. else {
  68362. this._blurX.alwaysForcePOT = true;
  68363. }
  68364. 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);
  68365. this._blurY.autoClear = false;
  68366. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  68367. this.addPostProcess(this._blurX);
  68368. this.addPostProcess(this._blurY);
  68369. }
  68370. else {
  68371. if (this._blurY) {
  68372. this.removePostProcess(this._blurY);
  68373. this._blurY.dispose();
  68374. this._blurY = null;
  68375. }
  68376. if (this._blurX) {
  68377. this.removePostProcess(this._blurX);
  68378. this._blurX.dispose();
  68379. this._blurX = null;
  68380. }
  68381. }
  68382. };
  68383. MirrorTexture.prototype.clone = function () {
  68384. var scene = this.getScene();
  68385. if (!scene) {
  68386. return this;
  68387. }
  68388. var textureSize = this.getSize();
  68389. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  68390. // Base texture
  68391. newTexture.hasAlpha = this.hasAlpha;
  68392. newTexture.level = this.level;
  68393. // Mirror Texture
  68394. newTexture.mirrorPlane = this.mirrorPlane.clone();
  68395. if (this.renderList) {
  68396. newTexture.renderList = this.renderList.slice(0);
  68397. }
  68398. return newTexture;
  68399. };
  68400. MirrorTexture.prototype.serialize = function () {
  68401. if (!this.name) {
  68402. return null;
  68403. }
  68404. var serializationObject = _super.prototype.serialize.call(this);
  68405. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  68406. return serializationObject;
  68407. };
  68408. MirrorTexture.prototype.dispose = function () {
  68409. _super.prototype.dispose.call(this);
  68410. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  68411. };
  68412. return MirrorTexture;
  68413. }(BABYLON.RenderTargetTexture));
  68414. BABYLON.MirrorTexture = MirrorTexture;
  68415. })(BABYLON || (BABYLON = {}));
  68416. //# sourceMappingURL=babylon.mirrorTexture.js.map
  68417. var BABYLON;
  68418. (function (BABYLON) {
  68419. /**
  68420. * Creates a refraction texture used by refraction channel of the standard material.
  68421. * @param name the texture name
  68422. * @param size size of the underlying texture
  68423. * @param scene root scene
  68424. */
  68425. var RefractionTexture = /** @class */ (function (_super) {
  68426. __extends(RefractionTexture, _super);
  68427. function RefractionTexture(name, size, scene, generateMipMaps) {
  68428. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  68429. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  68430. _this.depth = 2.0;
  68431. _this.onBeforeRenderObservable.add(function () {
  68432. scene.clipPlane = _this.refractionPlane;
  68433. });
  68434. _this.onAfterRenderObservable.add(function () {
  68435. delete scene.clipPlane;
  68436. });
  68437. return _this;
  68438. }
  68439. RefractionTexture.prototype.clone = function () {
  68440. var scene = this.getScene();
  68441. if (!scene) {
  68442. return this;
  68443. }
  68444. var textureSize = this.getSize();
  68445. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  68446. // Base texture
  68447. newTexture.hasAlpha = this.hasAlpha;
  68448. newTexture.level = this.level;
  68449. // Refraction Texture
  68450. newTexture.refractionPlane = this.refractionPlane.clone();
  68451. if (this.renderList) {
  68452. newTexture.renderList = this.renderList.slice(0);
  68453. }
  68454. newTexture.depth = this.depth;
  68455. return newTexture;
  68456. };
  68457. RefractionTexture.prototype.serialize = function () {
  68458. if (!this.name) {
  68459. return null;
  68460. }
  68461. var serializationObject = _super.prototype.serialize.call(this);
  68462. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  68463. serializationObject.depth = this.depth;
  68464. return serializationObject;
  68465. };
  68466. return RefractionTexture;
  68467. }(BABYLON.RenderTargetTexture));
  68468. BABYLON.RefractionTexture = RefractionTexture;
  68469. })(BABYLON || (BABYLON = {}));
  68470. //# sourceMappingURL=babylon.refractionTexture.js.map
  68471. var BABYLON;
  68472. (function (BABYLON) {
  68473. /**
  68474. * A class extending {BABYLON.Texture} allowing drawing on a texture
  68475. * @see http://doc.babylonjs.com/how_to/dynamictexture
  68476. */
  68477. var DynamicTexture = /** @class */ (function (_super) {
  68478. __extends(DynamicTexture, _super);
  68479. /**
  68480. * Creates a {BABYLON.DynamicTexture}
  68481. * @param name defines the name of the texture
  68482. * @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
  68483. * @param scene defines the scene where you want the texture
  68484. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  68485. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  68486. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  68487. */
  68488. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  68489. if (scene === void 0) { scene = null; }
  68490. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68491. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68492. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  68493. _this.name = name;
  68494. _this._engine = _this.getScene().getEngine();
  68495. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68496. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68497. _this._generateMipMaps = generateMipMaps;
  68498. if (options.getContext) {
  68499. _this._canvas = options;
  68500. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68501. }
  68502. else {
  68503. _this._canvas = document.createElement("canvas");
  68504. if (options.width || options.width === 0) {
  68505. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68506. }
  68507. else {
  68508. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  68509. }
  68510. }
  68511. var textureSize = _this.getSize();
  68512. _this._canvas.width = textureSize.width;
  68513. _this._canvas.height = textureSize.height;
  68514. _this._context = _this._canvas.getContext("2d");
  68515. return _this;
  68516. }
  68517. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  68518. /**
  68519. * Gets the current state of canRescale
  68520. */
  68521. get: function () {
  68522. return true;
  68523. },
  68524. enumerable: true,
  68525. configurable: true
  68526. });
  68527. DynamicTexture.prototype._recreate = function (textureSize) {
  68528. this._canvas.width = textureSize.width;
  68529. this._canvas.height = textureSize.height;
  68530. this.releaseInternalTexture();
  68531. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  68532. };
  68533. /**
  68534. * Scales the texture
  68535. * @param ratio the scale factor to apply to both width and height
  68536. */
  68537. DynamicTexture.prototype.scale = function (ratio) {
  68538. var textureSize = this.getSize();
  68539. textureSize.width *= ratio;
  68540. textureSize.height *= ratio;
  68541. this._recreate(textureSize);
  68542. };
  68543. /**
  68544. * Resizes the texture
  68545. * @param width the new width
  68546. * @param height the new height
  68547. */
  68548. DynamicTexture.prototype.scaleTo = function (width, height) {
  68549. var textureSize = this.getSize();
  68550. textureSize.width = width;
  68551. textureSize.height = height;
  68552. this._recreate(textureSize);
  68553. };
  68554. /**
  68555. * Gets the context of the canvas used by the texture
  68556. * @returns the canvas context of the dynamic texture
  68557. */
  68558. DynamicTexture.prototype.getContext = function () {
  68559. return this._context;
  68560. };
  68561. /**
  68562. * Clears the texture
  68563. */
  68564. DynamicTexture.prototype.clear = function () {
  68565. var size = this.getSize();
  68566. this._context.fillRect(0, 0, size.width, size.height);
  68567. };
  68568. /**
  68569. * Updates the texture
  68570. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68571. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  68572. */
  68573. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  68574. if (premulAlpha === void 0) { premulAlpha = false; }
  68575. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  68576. };
  68577. /**
  68578. * Draws text onto the texture
  68579. * @param text defines the text to be drawn
  68580. * @param x defines the placement of the text from the left
  68581. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  68582. * @param font defines the font to be used with font-style, font-size, font-name
  68583. * @param color defines the color used for the text
  68584. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  68585. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68586. * @param update defines whether texture is immediately update (default is true)
  68587. */
  68588. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  68589. if (update === void 0) { update = true; }
  68590. var size = this.getSize();
  68591. if (clearColor) {
  68592. this._context.fillStyle = clearColor;
  68593. this._context.fillRect(0, 0, size.width, size.height);
  68594. }
  68595. this._context.font = font;
  68596. if (x === null || x === undefined) {
  68597. var textSize = this._context.measureText(text);
  68598. x = (size.width - textSize.width) / 2;
  68599. }
  68600. if (y === null || y === undefined) {
  68601. var fontSize = parseInt((font.replace(/\D/g, '')));
  68602. y = (size.height / 2) + (fontSize / 3.65);
  68603. }
  68604. this._context.fillStyle = color;
  68605. this._context.fillText(text, x, y);
  68606. if (update) {
  68607. this.update(invertY);
  68608. }
  68609. };
  68610. /**
  68611. * Clones the texture
  68612. * @returns the clone of the texture.
  68613. */
  68614. DynamicTexture.prototype.clone = function () {
  68615. var scene = this.getScene();
  68616. if (!scene) {
  68617. return this;
  68618. }
  68619. var textureSize = this.getSize();
  68620. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  68621. // Base texture
  68622. newTexture.hasAlpha = this.hasAlpha;
  68623. newTexture.level = this.level;
  68624. // Dynamic Texture
  68625. newTexture.wrapU = this.wrapU;
  68626. newTexture.wrapV = this.wrapV;
  68627. return newTexture;
  68628. };
  68629. /**
  68630. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  68631. * @returns a serialized dynamic texture object
  68632. */
  68633. DynamicTexture.prototype.serialize = function () {
  68634. var scene = this.getScene();
  68635. if (scene && !scene.isReady()) {
  68636. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  68637. }
  68638. var serializationObject = _super.prototype.serialize.call(this);
  68639. serializationObject.base64String = this._canvas.toDataURL();
  68640. serializationObject.invertY = this._invertY;
  68641. serializationObject.samplingMode = this.samplingMode;
  68642. return serializationObject;
  68643. };
  68644. /** @hidden */
  68645. DynamicTexture.prototype._rebuild = function () {
  68646. this.update();
  68647. };
  68648. return DynamicTexture;
  68649. }(BABYLON.Texture));
  68650. BABYLON.DynamicTexture = DynamicTexture;
  68651. })(BABYLON || (BABYLON = {}));
  68652. //# sourceMappingURL=babylon.dynamicTexture.js.map
  68653. var BABYLON;
  68654. (function (BABYLON) {
  68655. var VideoTexture = /** @class */ (function (_super) {
  68656. __extends(VideoTexture, _super);
  68657. /**
  68658. * Creates a video texture.
  68659. * Sample : https://doc.babylonjs.com/how_to/video_texture
  68660. * @param {string | null} name optional name, will detect from video source, if not defined
  68661. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  68662. * @param {BABYLON.Scene} scene is obviously the current scene.
  68663. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  68664. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  68665. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  68666. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  68667. */
  68668. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  68669. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68670. if (invertY === void 0) { invertY = false; }
  68671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68672. if (settings === void 0) { settings = {
  68673. autoPlay: true,
  68674. loop: true,
  68675. autoUpdateTexture: true,
  68676. }; }
  68677. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68678. _this._onUserActionRequestedObservable = null;
  68679. _this._stillImageCaptured = false;
  68680. _this._poster = false;
  68681. _this._createInternalTexture = function () {
  68682. if (_this._texture != null) {
  68683. if (_this._poster) {
  68684. _this._texture.dispose();
  68685. _this._poster = false;
  68686. }
  68687. else {
  68688. return;
  68689. }
  68690. }
  68691. if (!_this._engine.needPOTTextures ||
  68692. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  68693. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68694. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68695. }
  68696. else {
  68697. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68698. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68699. _this._generateMipMaps = false;
  68700. }
  68701. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  68702. if (!_this.video.autoplay) {
  68703. var oldHandler_1 = _this.video.onplaying;
  68704. var error_1 = false;
  68705. _this.video.onplaying = function () {
  68706. _this.video.onplaying = oldHandler_1;
  68707. _this._texture.isReady = true;
  68708. _this._updateInternalTexture();
  68709. if (!error_1) {
  68710. _this.video.pause();
  68711. }
  68712. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68713. _this.onLoadObservable.notifyObservers(_this);
  68714. }
  68715. };
  68716. var playing = _this.video.play();
  68717. if (playing) {
  68718. playing.then(function () {
  68719. // Everything is good.
  68720. })
  68721. .catch(function () {
  68722. error_1 = true;
  68723. // On Chrome for instance, new policies might prevent playing without user interaction.
  68724. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  68725. _this._onUserActionRequestedObservable.notifyObservers(_this);
  68726. }
  68727. });
  68728. }
  68729. else {
  68730. _this.video.onplaying = oldHandler_1;
  68731. _this._texture.isReady = true;
  68732. _this._updateInternalTexture();
  68733. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68734. _this.onLoadObservable.notifyObservers(_this);
  68735. }
  68736. }
  68737. }
  68738. else {
  68739. _this._texture.isReady = true;
  68740. _this._updateInternalTexture();
  68741. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68742. _this.onLoadObservable.notifyObservers(_this);
  68743. }
  68744. }
  68745. };
  68746. _this.reset = function () {
  68747. if (_this._texture == null) {
  68748. return;
  68749. }
  68750. if (!_this._poster) {
  68751. _this._texture.dispose();
  68752. _this._texture = null;
  68753. }
  68754. };
  68755. _this._updateInternalTexture = function (e) {
  68756. if (_this._texture == null || !_this._texture.isReady) {
  68757. return;
  68758. }
  68759. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  68760. return;
  68761. }
  68762. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  68763. };
  68764. _this._engine = _this.getScene().getEngine();
  68765. _this._generateMipMaps = generateMipMaps;
  68766. _this._samplingMode = samplingMode;
  68767. _this.autoUpdateTexture = settings.autoUpdateTexture;
  68768. _this.name = name || _this._getName(src);
  68769. _this.video = _this._getVideo(src);
  68770. if (settings.poster) {
  68771. _this.video.poster = settings.poster;
  68772. }
  68773. if (settings.autoPlay !== undefined) {
  68774. _this.video.autoplay = settings.autoPlay;
  68775. }
  68776. if (settings.loop !== undefined) {
  68777. _this.video.loop = settings.loop;
  68778. }
  68779. _this.video.setAttribute("playsinline", "");
  68780. _this.video.addEventListener("canplay", _this._createInternalTexture);
  68781. _this.video.addEventListener("paused", _this._updateInternalTexture);
  68782. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  68783. _this.video.addEventListener("emptied", _this.reset);
  68784. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  68785. _this._createInternalTexture();
  68786. }
  68787. if (settings.poster) {
  68788. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  68789. _this._poster = true;
  68790. }
  68791. return _this;
  68792. }
  68793. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  68794. get: function () {
  68795. if (!this._onUserActionRequestedObservable) {
  68796. this._onUserActionRequestedObservable = new BABYLON.Observable();
  68797. }
  68798. return this._onUserActionRequestedObservable;
  68799. },
  68800. enumerable: true,
  68801. configurable: true
  68802. });
  68803. VideoTexture.prototype._getName = function (src) {
  68804. if (src instanceof HTMLVideoElement) {
  68805. return src.currentSrc;
  68806. }
  68807. if (typeof src === "object") {
  68808. return src.toString();
  68809. }
  68810. return src;
  68811. };
  68812. ;
  68813. VideoTexture.prototype._getVideo = function (src) {
  68814. if (src instanceof HTMLVideoElement) {
  68815. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  68816. return src;
  68817. }
  68818. var video = document.createElement("video");
  68819. if (typeof src === "string") {
  68820. BABYLON.Tools.SetCorsBehavior(src, video);
  68821. video.src = src;
  68822. }
  68823. else {
  68824. BABYLON.Tools.SetCorsBehavior(src[0], video);
  68825. src.forEach(function (url) {
  68826. var source = document.createElement("source");
  68827. source.src = url;
  68828. video.appendChild(source);
  68829. });
  68830. }
  68831. return video;
  68832. };
  68833. ;
  68834. /**
  68835. * @hidden Internal method to initiate `update`.
  68836. */
  68837. VideoTexture.prototype._rebuild = function () {
  68838. this.update();
  68839. };
  68840. /**
  68841. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  68842. */
  68843. VideoTexture.prototype.update = function () {
  68844. if (!this.autoUpdateTexture) {
  68845. // Expecting user to call `updateTexture` manually
  68846. return;
  68847. }
  68848. this.updateTexture(true);
  68849. };
  68850. /**
  68851. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  68852. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  68853. */
  68854. VideoTexture.prototype.updateTexture = function (isVisible) {
  68855. if (!isVisible) {
  68856. return;
  68857. }
  68858. if (this.video.paused && this._stillImageCaptured) {
  68859. return;
  68860. }
  68861. this._stillImageCaptured = true;
  68862. this._updateInternalTexture();
  68863. };
  68864. /**
  68865. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  68866. * @param url New url.
  68867. */
  68868. VideoTexture.prototype.updateURL = function (url) {
  68869. this.video.src = url;
  68870. };
  68871. VideoTexture.prototype.dispose = function () {
  68872. _super.prototype.dispose.call(this);
  68873. if (this._onUserActionRequestedObservable) {
  68874. this._onUserActionRequestedObservable.clear();
  68875. this._onUserActionRequestedObservable = null;
  68876. }
  68877. this.video.removeEventListener("canplay", this._createInternalTexture);
  68878. this.video.removeEventListener("paused", this._updateInternalTexture);
  68879. this.video.removeEventListener("seeked", this._updateInternalTexture);
  68880. this.video.removeEventListener("emptied", this.reset);
  68881. this.video.pause();
  68882. };
  68883. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  68884. var video = document.createElement("video");
  68885. video.setAttribute('autoplay', '');
  68886. video.setAttribute('muted', '');
  68887. video.setAttribute('playsinline', '');
  68888. var constraintsDeviceId;
  68889. if (constraints && constraints.deviceId) {
  68890. constraintsDeviceId = {
  68891. exact: constraints.deviceId,
  68892. };
  68893. }
  68894. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  68895. if (navigator.mediaDevices) {
  68896. navigator.mediaDevices.getUserMedia({ video: constraints })
  68897. .then(function (stream) {
  68898. if (video.mozSrcObject !== undefined) {
  68899. // hack for Firefox < 19
  68900. video.mozSrcObject = stream;
  68901. }
  68902. else {
  68903. video.srcObject = stream;
  68904. }
  68905. var onPlaying = function () {
  68906. if (onReady) {
  68907. onReady(new VideoTexture("video", video, scene, true, true));
  68908. }
  68909. video.removeEventListener("playing", onPlaying);
  68910. };
  68911. video.addEventListener("playing", onPlaying);
  68912. video.play();
  68913. })
  68914. .catch(function (err) {
  68915. BABYLON.Tools.Error(err.name);
  68916. });
  68917. }
  68918. else {
  68919. navigator.getUserMedia =
  68920. navigator.getUserMedia ||
  68921. navigator.webkitGetUserMedia ||
  68922. navigator.mozGetUserMedia ||
  68923. navigator.msGetUserMedia;
  68924. if (navigator.getUserMedia) {
  68925. navigator.getUserMedia({
  68926. video: {
  68927. deviceId: constraintsDeviceId,
  68928. width: {
  68929. min: (constraints && constraints.minWidth) || 256,
  68930. max: (constraints && constraints.maxWidth) || 640,
  68931. },
  68932. height: {
  68933. min: (constraints && constraints.minHeight) || 256,
  68934. max: (constraints && constraints.maxHeight) || 480,
  68935. },
  68936. },
  68937. }, function (stream) {
  68938. if (video.mozSrcObject !== undefined) {
  68939. // hack for Firefox < 19
  68940. video.mozSrcObject = stream;
  68941. }
  68942. else {
  68943. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  68944. }
  68945. video.play();
  68946. if (onReady) {
  68947. onReady(new VideoTexture("video", video, scene, true, true));
  68948. }
  68949. }, function (e) {
  68950. BABYLON.Tools.Error(e.name);
  68951. });
  68952. }
  68953. }
  68954. };
  68955. return VideoTexture;
  68956. }(BABYLON.Texture));
  68957. BABYLON.VideoTexture = VideoTexture;
  68958. })(BABYLON || (BABYLON = {}));
  68959. //# sourceMappingURL=babylon.videoTexture.js.map
  68960. var BABYLON;
  68961. (function (BABYLON) {
  68962. var RawTexture = /** @class */ (function (_super) {
  68963. __extends(RawTexture, _super);
  68964. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  68965. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68966. if (invertY === void 0) { invertY = false; }
  68967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68968. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68969. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68970. _this.format = format;
  68971. _this._engine = scene.getEngine();
  68972. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  68973. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68974. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68975. return _this;
  68976. }
  68977. RawTexture.prototype.update = function (data) {
  68978. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68979. };
  68980. // Statics
  68981. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68982. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68983. if (invertY === void 0) { invertY = false; }
  68984. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68985. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68986. };
  68987. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68988. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68989. if (invertY === void 0) { invertY = false; }
  68990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68991. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68992. };
  68993. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68994. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68995. if (invertY === void 0) { invertY = false; }
  68996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68997. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68998. };
  68999. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69000. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69001. if (invertY === void 0) { invertY = false; }
  69002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69003. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69004. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  69005. };
  69006. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69007. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69008. if (invertY === void 0) { invertY = false; }
  69009. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69010. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69011. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  69012. };
  69013. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69014. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69015. if (invertY === void 0) { invertY = false; }
  69016. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69017. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  69018. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  69019. };
  69020. return RawTexture;
  69021. }(BABYLON.Texture));
  69022. BABYLON.RawTexture = RawTexture;
  69023. })(BABYLON || (BABYLON = {}));
  69024. //# sourceMappingURL=babylon.rawTexture.js.map
  69025. var BABYLON;
  69026. (function (BABYLON) {
  69027. /**
  69028. * Class used to store 3D textures containing user data
  69029. */
  69030. var RawTexture3D = /** @class */ (function (_super) {
  69031. __extends(RawTexture3D, _super);
  69032. /**
  69033. * Create a new RawTexture3D
  69034. * @param data defines the data of the texture
  69035. * @param width defines the width of the texture
  69036. * @param height defines the height of the texture
  69037. * @param depth defines the depth of the texture
  69038. * @param format defines the texture format to use
  69039. * @param scene defines the hosting scene
  69040. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  69041. * @param invertY defines if texture must be stored with Y axis inverted
  69042. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  69043. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  69044. */
  69045. function RawTexture3D(data, width, height, depth,
  69046. /** Gets or sets the texture format to use */
  69047. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  69048. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69049. if (invertY === void 0) { invertY = false; }
  69050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69051. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69052. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69053. _this.format = format;
  69054. _this._engine = scene.getEngine();
  69055. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  69056. _this.is3D = true;
  69057. return _this;
  69058. }
  69059. /**
  69060. * Update the texture with new data
  69061. * @param data defines the data to store in the texture
  69062. */
  69063. RawTexture3D.prototype.update = function (data) {
  69064. if (!this._texture) {
  69065. return;
  69066. }
  69067. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69068. };
  69069. return RawTexture3D;
  69070. }(BABYLON.Texture));
  69071. BABYLON.RawTexture3D = RawTexture3D;
  69072. })(BABYLON || (BABYLON = {}));
  69073. //# sourceMappingURL=babylon.rawTexture3D.js.map
  69074. var BABYLON;
  69075. (function (BABYLON) {
  69076. /**
  69077. * PostProcessManager is used to manage one or more post processes or post process pipelines
  69078. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69079. */
  69080. var PostProcessManager = /** @class */ (function () {
  69081. /**
  69082. * Creates a new instance PostProcess
  69083. * @param scene The scene that the post process is associated with.
  69084. */
  69085. function PostProcessManager(scene) {
  69086. this._vertexBuffers = {};
  69087. this._scene = scene;
  69088. }
  69089. PostProcessManager.prototype._prepareBuffers = function () {
  69090. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  69091. return;
  69092. }
  69093. // VBO
  69094. var vertices = [];
  69095. vertices.push(1, 1);
  69096. vertices.push(-1, 1);
  69097. vertices.push(-1, -1);
  69098. vertices.push(1, -1);
  69099. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69100. this._buildIndexBuffer();
  69101. };
  69102. PostProcessManager.prototype._buildIndexBuffer = function () {
  69103. // Indices
  69104. var indices = [];
  69105. indices.push(0);
  69106. indices.push(1);
  69107. indices.push(2);
  69108. indices.push(0);
  69109. indices.push(2);
  69110. indices.push(3);
  69111. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  69112. };
  69113. /**
  69114. * Rebuilds the vertex buffers of the manager.
  69115. * @hidden
  69116. */
  69117. PostProcessManager.prototype._rebuild = function () {
  69118. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69119. if (!vb) {
  69120. return;
  69121. }
  69122. vb._rebuild();
  69123. this._buildIndexBuffer();
  69124. };
  69125. // Methods
  69126. /**
  69127. * Prepares a frame to be run through a post process.
  69128. * @param sourceTexture The input texture to the post procesess. (default: null)
  69129. * @param postProcesses An array of post processes to be run. (default: null)
  69130. * @returns True if the post processes were able to be run.
  69131. * @hidden
  69132. */
  69133. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  69134. if (sourceTexture === void 0) { sourceTexture = null; }
  69135. if (postProcesses === void 0) { postProcesses = null; }
  69136. var camera = this._scene.activeCamera;
  69137. if (!camera) {
  69138. return false;
  69139. }
  69140. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69141. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69142. return false;
  69143. }
  69144. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  69145. return true;
  69146. };
  69147. /**
  69148. * Manually render a set of post processes to a texture.
  69149. * @param postProcesses An array of post processes to be run.
  69150. * @param targetTexture The target texture to render to.
  69151. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  69152. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  69153. * @param lodLevel defines which lod of the texture to render to
  69154. */
  69155. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  69156. if (targetTexture === void 0) { targetTexture = null; }
  69157. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69158. if (faceIndex === void 0) { faceIndex = 0; }
  69159. if (lodLevel === void 0) { lodLevel = 0; }
  69160. var engine = this._scene.getEngine();
  69161. for (var index = 0; index < postProcesses.length; index++) {
  69162. if (index < postProcesses.length - 1) {
  69163. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  69164. }
  69165. else {
  69166. if (targetTexture) {
  69167. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  69168. }
  69169. else {
  69170. engine.restoreDefaultFramebuffer();
  69171. }
  69172. }
  69173. var pp = postProcesses[index];
  69174. var effect = pp.apply();
  69175. if (effect) {
  69176. pp.onBeforeRenderObservable.notifyObservers(effect);
  69177. // VBOs
  69178. this._prepareBuffers();
  69179. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69180. // Draw order
  69181. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69182. pp.onAfterRenderObservable.notifyObservers(effect);
  69183. }
  69184. }
  69185. // Restore depth buffer
  69186. engine.setDepthBuffer(true);
  69187. engine.setDepthWrite(true);
  69188. };
  69189. /**
  69190. * Finalize the result of the output of the postprocesses.
  69191. * @param doNotPresent If true the result will not be displayed to the screen.
  69192. * @param targetTexture The target texture to render to.
  69193. * @param faceIndex The index of the face to bind the target texture to.
  69194. * @param postProcesses The array of post processes to render.
  69195. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  69196. * @hidden
  69197. */
  69198. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  69199. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69200. var camera = this._scene.activeCamera;
  69201. if (!camera) {
  69202. return;
  69203. }
  69204. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69205. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69206. return;
  69207. }
  69208. var engine = this._scene.getEngine();
  69209. for (var index = 0, len = postProcesses.length; index < len; index++) {
  69210. var pp = postProcesses[index];
  69211. if (index < len - 1) {
  69212. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  69213. }
  69214. else {
  69215. if (targetTexture) {
  69216. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  69217. pp._outputTexture = targetTexture;
  69218. }
  69219. else {
  69220. engine.restoreDefaultFramebuffer();
  69221. pp._outputTexture = null;
  69222. }
  69223. }
  69224. if (doNotPresent) {
  69225. break;
  69226. }
  69227. var effect = pp.apply();
  69228. if (effect) {
  69229. pp.onBeforeRenderObservable.notifyObservers(effect);
  69230. // VBOs
  69231. this._prepareBuffers();
  69232. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69233. // Draw order
  69234. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69235. pp.onAfterRenderObservable.notifyObservers(effect);
  69236. }
  69237. }
  69238. // Restore states
  69239. engine.setDepthBuffer(true);
  69240. engine.setDepthWrite(true);
  69241. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69242. };
  69243. /**
  69244. * Disposes of the post process manager.
  69245. */
  69246. PostProcessManager.prototype.dispose = function () {
  69247. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69248. if (buffer) {
  69249. buffer.dispose();
  69250. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69251. }
  69252. if (this._indexBuffer) {
  69253. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69254. this._indexBuffer = null;
  69255. }
  69256. };
  69257. return PostProcessManager;
  69258. }());
  69259. BABYLON.PostProcessManager = PostProcessManager;
  69260. })(BABYLON || (BABYLON = {}));
  69261. //# sourceMappingURL=babylon.postProcessManager.js.map
  69262. var BABYLON;
  69263. (function (BABYLON) {
  69264. /**
  69265. * PostProcess can be used to apply a shader to a texture after it has been rendered
  69266. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69267. */
  69268. var PostProcess = /** @class */ (function () {
  69269. /**
  69270. * Creates a new instance PostProcess
  69271. * @param name The name of the PostProcess.
  69272. * @param fragmentUrl The url of the fragment shader to be used.
  69273. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  69274. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  69275. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69276. * @param camera The camera to apply the render pass to.
  69277. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69278. * @param engine The engine which the post process will be applied. (default: current engine)
  69279. * @param reusable If the post process can be reused on the same frame. (default: false)
  69280. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  69281. * @param textureType Type of textures used when performing the post process. (default: 0)
  69282. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  69283. * @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
  69284. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  69285. */
  69286. function PostProcess(
  69287. /** Name of the PostProcess. */
  69288. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  69289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  69290. if (defines === void 0) { defines = null; }
  69291. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69292. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  69293. if (blockCompilation === void 0) { blockCompilation = false; }
  69294. this.name = name;
  69295. /**
  69296. * Width of the texture to apply the post process on
  69297. */
  69298. this.width = -1;
  69299. /**
  69300. * Height of the texture to apply the post process on
  69301. */
  69302. this.height = -1;
  69303. /**
  69304. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  69305. * @hidden
  69306. */
  69307. this._outputTexture = null;
  69308. /**
  69309. * If the buffer needs to be cleared before applying the post process. (default: true)
  69310. * Should be set to false if shader will overwrite all previous pixels.
  69311. */
  69312. this.autoClear = true;
  69313. /**
  69314. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  69315. */
  69316. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  69317. /**
  69318. * Animations to be used for the post processing
  69319. */
  69320. this.animations = new Array();
  69321. /**
  69322. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  69323. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  69324. */
  69325. this.enablePixelPerfectMode = false;
  69326. /**
  69327. * Force the postprocess to be applied without taking in account viewport
  69328. */
  69329. this.forceFullscreenViewport = true;
  69330. /**
  69331. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  69332. *
  69333. * | Value | Type | Description |
  69334. * | ----- | ----------------------------------- | ----------- |
  69335. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  69336. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  69337. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  69338. *
  69339. */
  69340. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  69341. /**
  69342. * Force textures to be a power of two (default: false)
  69343. */
  69344. this.alwaysForcePOT = false;
  69345. this._samples = 1;
  69346. /**
  69347. * Modify the scale of the post process to be the same as the viewport (default: false)
  69348. */
  69349. this.adaptScaleToCurrentViewport = false;
  69350. this._reusable = false;
  69351. /**
  69352. * Smart array of input and output textures for the post process.
  69353. * @hidden
  69354. */
  69355. this._textures = new BABYLON.SmartArray(2);
  69356. /**
  69357. * The index in _textures that corresponds to the output texture.
  69358. * @hidden
  69359. */
  69360. this._currentRenderTextureInd = 0;
  69361. this._scaleRatio = new BABYLON.Vector2(1, 1);
  69362. this._texelSize = BABYLON.Vector2.Zero();
  69363. // Events
  69364. /**
  69365. * An event triggered when the postprocess is activated.
  69366. */
  69367. this.onActivateObservable = new BABYLON.Observable();
  69368. /**
  69369. * An event triggered when the postprocess changes its size.
  69370. */
  69371. this.onSizeChangedObservable = new BABYLON.Observable();
  69372. /**
  69373. * An event triggered when the postprocess applies its effect.
  69374. */
  69375. this.onApplyObservable = new BABYLON.Observable();
  69376. /**
  69377. * An event triggered before rendering the postprocess
  69378. */
  69379. this.onBeforeRenderObservable = new BABYLON.Observable();
  69380. /**
  69381. * An event triggered after rendering the postprocess
  69382. */
  69383. this.onAfterRenderObservable = new BABYLON.Observable();
  69384. if (camera != null) {
  69385. this._camera = camera;
  69386. this._scene = camera.getScene();
  69387. camera.attachPostProcess(this);
  69388. this._engine = this._scene.getEngine();
  69389. this._scene.postProcesses.push(this);
  69390. }
  69391. else if (engine) {
  69392. this._engine = engine;
  69393. this._engine.postProcesses.push(this);
  69394. }
  69395. this._options = options;
  69396. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  69397. this._reusable = reusable || false;
  69398. this._textureType = textureType;
  69399. this._samplers = samplers || [];
  69400. this._samplers.push("textureSampler");
  69401. this._fragmentUrl = fragmentUrl;
  69402. this._vertexUrl = vertexUrl;
  69403. this._parameters = parameters || [];
  69404. this._parameters.push("scale");
  69405. this._indexParameters = indexParameters;
  69406. if (!blockCompilation) {
  69407. this.updateEffect(defines);
  69408. }
  69409. }
  69410. Object.defineProperty(PostProcess.prototype, "samples", {
  69411. /**
  69412. * Number of sample textures (default: 1)
  69413. */
  69414. get: function () {
  69415. return this._samples;
  69416. },
  69417. set: function (n) {
  69418. var _this = this;
  69419. this._samples = n;
  69420. this._textures.forEach(function (texture) {
  69421. if (texture.samples !== _this._samples) {
  69422. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  69423. }
  69424. });
  69425. },
  69426. enumerable: true,
  69427. configurable: true
  69428. });
  69429. Object.defineProperty(PostProcess.prototype, "onActivate", {
  69430. /**
  69431. * A function that is added to the onActivateObservable
  69432. */
  69433. set: function (callback) {
  69434. if (this._onActivateObserver) {
  69435. this.onActivateObservable.remove(this._onActivateObserver);
  69436. }
  69437. if (callback) {
  69438. this._onActivateObserver = this.onActivateObservable.add(callback);
  69439. }
  69440. },
  69441. enumerable: true,
  69442. configurable: true
  69443. });
  69444. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  69445. /**
  69446. * A function that is added to the onSizeChangedObservable
  69447. */
  69448. set: function (callback) {
  69449. if (this._onSizeChangedObserver) {
  69450. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  69451. }
  69452. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  69453. },
  69454. enumerable: true,
  69455. configurable: true
  69456. });
  69457. Object.defineProperty(PostProcess.prototype, "onApply", {
  69458. /**
  69459. * A function that is added to the onApplyObservable
  69460. */
  69461. set: function (callback) {
  69462. if (this._onApplyObserver) {
  69463. this.onApplyObservable.remove(this._onApplyObserver);
  69464. }
  69465. this._onApplyObserver = this.onApplyObservable.add(callback);
  69466. },
  69467. enumerable: true,
  69468. configurable: true
  69469. });
  69470. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  69471. /**
  69472. * A function that is added to the onBeforeRenderObservable
  69473. */
  69474. set: function (callback) {
  69475. if (this._onBeforeRenderObserver) {
  69476. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69477. }
  69478. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69479. },
  69480. enumerable: true,
  69481. configurable: true
  69482. });
  69483. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  69484. /**
  69485. * A function that is added to the onAfterRenderObservable
  69486. */
  69487. set: function (callback) {
  69488. if (this._onAfterRenderObserver) {
  69489. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69490. }
  69491. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69492. },
  69493. enumerable: true,
  69494. configurable: true
  69495. });
  69496. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  69497. /**
  69498. * 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
  69499. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  69500. */
  69501. get: function () {
  69502. return this._textures.data[this._currentRenderTextureInd];
  69503. },
  69504. set: function (value) {
  69505. this._forcedOutputTexture = value;
  69506. },
  69507. enumerable: true,
  69508. configurable: true
  69509. });
  69510. /**
  69511. * Gets the camera which post process is applied to.
  69512. * @returns The camera the post process is applied to.
  69513. */
  69514. PostProcess.prototype.getCamera = function () {
  69515. return this._camera;
  69516. };
  69517. Object.defineProperty(PostProcess.prototype, "texelSize", {
  69518. /**
  69519. * Gets the texel size of the postprocess.
  69520. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  69521. */
  69522. get: function () {
  69523. if (this._shareOutputWithPostProcess) {
  69524. return this._shareOutputWithPostProcess.texelSize;
  69525. }
  69526. if (this._forcedOutputTexture) {
  69527. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  69528. }
  69529. return this._texelSize;
  69530. },
  69531. enumerable: true,
  69532. configurable: true
  69533. });
  69534. /**
  69535. * Gets the engine which this post process belongs to.
  69536. * @returns The engine the post process was enabled with.
  69537. */
  69538. PostProcess.prototype.getEngine = function () {
  69539. return this._engine;
  69540. };
  69541. /**
  69542. * The effect that is created when initializing the post process.
  69543. * @returns The created effect corrisponding the the postprocess.
  69544. */
  69545. PostProcess.prototype.getEffect = function () {
  69546. return this._effect;
  69547. };
  69548. /**
  69549. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  69550. * @param postProcess The post process to share the output with.
  69551. * @returns This post process.
  69552. */
  69553. PostProcess.prototype.shareOutputWith = function (postProcess) {
  69554. this._disposeTextures();
  69555. this._shareOutputWithPostProcess = postProcess;
  69556. return this;
  69557. };
  69558. /**
  69559. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  69560. * This should be called if the post process that shares output with this post process is disabled/disposed.
  69561. */
  69562. PostProcess.prototype.useOwnOutput = function () {
  69563. if (this._textures.length == 0) {
  69564. this._textures = new BABYLON.SmartArray(2);
  69565. }
  69566. this._shareOutputWithPostProcess = null;
  69567. };
  69568. /**
  69569. * Updates the effect with the current post process compile time values and recompiles the shader.
  69570. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69571. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69572. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69573. * @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
  69574. * @param onCompiled Called when the shader has been compiled.
  69575. * @param onError Called if there is an error when compiling a shader.
  69576. */
  69577. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69578. if (defines === void 0) { defines = null; }
  69579. if (uniforms === void 0) { uniforms = null; }
  69580. if (samplers === void 0) { samplers = null; }
  69581. 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);
  69582. };
  69583. /**
  69584. * The post process is reusable if it can be used multiple times within one frame.
  69585. * @returns If the post process is reusable
  69586. */
  69587. PostProcess.prototype.isReusable = function () {
  69588. return this._reusable;
  69589. };
  69590. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  69591. PostProcess.prototype.markTextureDirty = function () {
  69592. this.width = -1;
  69593. };
  69594. /**
  69595. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  69596. * 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.
  69597. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  69598. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  69599. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  69600. * @returns The target texture that was bound to be written to.
  69601. */
  69602. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  69603. var _this = this;
  69604. if (sourceTexture === void 0) { sourceTexture = null; }
  69605. camera = camera || this._camera;
  69606. var scene = camera.getScene();
  69607. var engine = scene.getEngine();
  69608. var maxSize = engine.getCaps().maxTextureSize;
  69609. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  69610. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  69611. // 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
  69612. var webVRCamera = camera.parent;
  69613. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  69614. requiredWidth /= 2;
  69615. }
  69616. var desiredWidth = (this._options.width || requiredWidth);
  69617. var desiredHeight = this._options.height || requiredHeight;
  69618. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  69619. if (this.adaptScaleToCurrentViewport) {
  69620. var currentViewport = engine.currentViewport;
  69621. if (currentViewport) {
  69622. desiredWidth *= currentViewport.width;
  69623. desiredHeight *= currentViewport.height;
  69624. }
  69625. }
  69626. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  69627. if (!this._options.width) {
  69628. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  69629. }
  69630. if (!this._options.height) {
  69631. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  69632. }
  69633. }
  69634. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  69635. if (this._textures.length > 0) {
  69636. for (var i = 0; i < this._textures.length; i++) {
  69637. this._engine._releaseTexture(this._textures.data[i]);
  69638. }
  69639. this._textures.reset();
  69640. }
  69641. this.width = desiredWidth;
  69642. this.height = desiredHeight;
  69643. var textureSize = { width: this.width, height: this.height };
  69644. var textureOptions = {
  69645. generateMipMaps: false,
  69646. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  69647. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  69648. samplingMode: this.renderTargetSamplingMode,
  69649. type: this._textureType
  69650. };
  69651. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69652. if (this._reusable) {
  69653. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69654. }
  69655. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  69656. this.onSizeChangedObservable.notifyObservers(this);
  69657. }
  69658. this._textures.forEach(function (texture) {
  69659. if (texture.samples !== _this.samples) {
  69660. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  69661. }
  69662. });
  69663. }
  69664. var target;
  69665. if (this._shareOutputWithPostProcess) {
  69666. target = this._shareOutputWithPostProcess.inputTexture;
  69667. }
  69668. else if (this._forcedOutputTexture) {
  69669. target = this._forcedOutputTexture;
  69670. this.width = this._forcedOutputTexture.width;
  69671. this.height = this._forcedOutputTexture.height;
  69672. }
  69673. else {
  69674. target = this.inputTexture;
  69675. }
  69676. // Bind the input of this post process to be used as the output of the previous post process.
  69677. if (this.enablePixelPerfectMode) {
  69678. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  69679. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  69680. }
  69681. else {
  69682. this._scaleRatio.copyFromFloats(1, 1);
  69683. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  69684. }
  69685. this.onActivateObservable.notifyObservers(camera);
  69686. // Clear
  69687. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  69688. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  69689. }
  69690. if (this._reusable) {
  69691. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  69692. }
  69693. return target;
  69694. };
  69695. Object.defineProperty(PostProcess.prototype, "isSupported", {
  69696. /**
  69697. * If the post process is supported.
  69698. */
  69699. get: function () {
  69700. return this._effect.isSupported;
  69701. },
  69702. enumerable: true,
  69703. configurable: true
  69704. });
  69705. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  69706. /**
  69707. * The aspect ratio of the output texture.
  69708. */
  69709. get: function () {
  69710. if (this._shareOutputWithPostProcess) {
  69711. return this._shareOutputWithPostProcess.aspectRatio;
  69712. }
  69713. if (this._forcedOutputTexture) {
  69714. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  69715. }
  69716. return this.width / this.height;
  69717. },
  69718. enumerable: true,
  69719. configurable: true
  69720. });
  69721. /**
  69722. * Get a value indicating if the post-process is ready to be used
  69723. * @returns true if the post-process is ready (shader is compiled)
  69724. */
  69725. PostProcess.prototype.isReady = function () {
  69726. return this._effect && this._effect.isReady();
  69727. };
  69728. /**
  69729. * Binds all textures and uniforms to the shader, this will be run on every pass.
  69730. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  69731. */
  69732. PostProcess.prototype.apply = function () {
  69733. // Check
  69734. if (!this._effect || !this._effect.isReady())
  69735. return null;
  69736. // States
  69737. this._engine.enableEffect(this._effect);
  69738. this._engine.setState(false);
  69739. this._engine.setDepthBuffer(false);
  69740. this._engine.setDepthWrite(false);
  69741. // Alpha
  69742. this._engine.setAlphaMode(this.alphaMode);
  69743. if (this.alphaConstants) {
  69744. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  69745. }
  69746. // Bind the output texture of the preivous post process as the input to this post process.
  69747. var source;
  69748. if (this._shareOutputWithPostProcess) {
  69749. source = this._shareOutputWithPostProcess.inputTexture;
  69750. }
  69751. else if (this._forcedOutputTexture) {
  69752. source = this._forcedOutputTexture;
  69753. }
  69754. else {
  69755. source = this.inputTexture;
  69756. }
  69757. this._effect._bindTexture("textureSampler", source);
  69758. // Parameters
  69759. this._effect.setVector2("scale", this._scaleRatio);
  69760. this.onApplyObservable.notifyObservers(this._effect);
  69761. return this._effect;
  69762. };
  69763. PostProcess.prototype._disposeTextures = function () {
  69764. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  69765. return;
  69766. }
  69767. if (this._textures.length > 0) {
  69768. for (var i = 0; i < this._textures.length; i++) {
  69769. this._engine._releaseTexture(this._textures.data[i]);
  69770. }
  69771. }
  69772. this._textures.dispose();
  69773. };
  69774. /**
  69775. * Disposes the post process.
  69776. * @param camera The camera to dispose the post process on.
  69777. */
  69778. PostProcess.prototype.dispose = function (camera) {
  69779. camera = camera || this._camera;
  69780. this._disposeTextures();
  69781. if (this._scene) {
  69782. var index_1 = this._scene.postProcesses.indexOf(this);
  69783. if (index_1 !== -1) {
  69784. this._scene.postProcesses.splice(index_1, 1);
  69785. }
  69786. }
  69787. else {
  69788. var index_2 = this._engine.postProcesses.indexOf(this);
  69789. if (index_2 !== -1) {
  69790. this._engine.postProcesses.splice(index_2, 1);
  69791. }
  69792. }
  69793. if (!camera) {
  69794. return;
  69795. }
  69796. camera.detachPostProcess(this);
  69797. var index = camera._postProcesses.indexOf(this);
  69798. if (index === 0 && camera._postProcesses.length > 0) {
  69799. var firstPostProcess = this._camera._getFirstPostProcess();
  69800. if (firstPostProcess) {
  69801. firstPostProcess.markTextureDirty();
  69802. }
  69803. }
  69804. this.onActivateObservable.clear();
  69805. this.onAfterRenderObservable.clear();
  69806. this.onApplyObservable.clear();
  69807. this.onBeforeRenderObservable.clear();
  69808. this.onSizeChangedObservable.clear();
  69809. };
  69810. return PostProcess;
  69811. }());
  69812. BABYLON.PostProcess = PostProcess;
  69813. })(BABYLON || (BABYLON = {}));
  69814. //# sourceMappingURL=babylon.postProcess.js.map
  69815. var BABYLON;
  69816. (function (BABYLON) {
  69817. var PassPostProcess = /** @class */ (function (_super) {
  69818. __extends(PassPostProcess, _super);
  69819. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69820. if (camera === void 0) { camera = null; }
  69821. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69822. if (blockCompilation === void 0) { blockCompilation = false; }
  69823. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  69824. }
  69825. return PassPostProcess;
  69826. }(BABYLON.PostProcess));
  69827. BABYLON.PassPostProcess = PassPostProcess;
  69828. })(BABYLON || (BABYLON = {}));
  69829. //# sourceMappingURL=babylon.passPostProcess.js.map
  69830. var __assign = (this && this.__assign) || function () {
  69831. __assign = Object.assign || function(t) {
  69832. for (var s, i = 1, n = arguments.length; i < n; i++) {
  69833. s = arguments[i];
  69834. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  69835. t[p] = s[p];
  69836. }
  69837. return t;
  69838. };
  69839. return __assign.apply(this, arguments);
  69840. };
  69841. var BABYLON;
  69842. (function (BABYLON) {
  69843. /**
  69844. * Default implementation IShadowGenerator.
  69845. * This is the main object responsible of generating shadows in the framework.
  69846. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  69847. */
  69848. var ShadowGenerator = /** @class */ (function () {
  69849. /**
  69850. * Creates a ShadowGenerator object.
  69851. * A ShadowGenerator is the required tool to use the shadows.
  69852. * Each light casting shadows needs to use its own ShadowGenerator.
  69853. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  69854. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  69855. * @param light The light object generating the shadows.
  69856. * @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.
  69857. */
  69858. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  69859. this._bias = 0.00005;
  69860. this._normalBias = 0;
  69861. this._blurBoxOffset = 1;
  69862. this._blurScale = 2;
  69863. this._blurKernel = 1;
  69864. this._useKernelBlur = false;
  69865. this._filter = ShadowGenerator.FILTER_NONE;
  69866. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  69867. this._contactHardeningLightSizeUVRatio = 0.1;
  69868. this._darkness = 0;
  69869. this._transparencyShadow = false;
  69870. /**
  69871. * Controls the extent to which the shadows fade out at the edge of the frustum
  69872. * Used only by directionals and spots
  69873. */
  69874. this.frustumEdgeFalloff = 0;
  69875. /**
  69876. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  69877. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  69878. * It might on the other hand introduce peter panning.
  69879. */
  69880. this.forceBackFacesOnly = false;
  69881. this._lightDirection = BABYLON.Vector3.Zero();
  69882. this._viewMatrix = BABYLON.Matrix.Zero();
  69883. this._projectionMatrix = BABYLON.Matrix.Zero();
  69884. this._transformMatrix = BABYLON.Matrix.Zero();
  69885. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69886. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69887. this._currentFaceIndex = 0;
  69888. this._currentFaceIndexCache = 0;
  69889. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  69890. this._mapSize = mapSize;
  69891. this._light = light;
  69892. this._scene = light.getScene();
  69893. light._shadowGenerator = this;
  69894. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  69895. if (!component) {
  69896. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  69897. this._scene._addComponent(component);
  69898. }
  69899. // Texture type fallback from float to int if not supported.
  69900. var caps = this._scene.getEngine().getCaps();
  69901. if (!useFullFloatFirst) {
  69902. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69903. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69904. }
  69905. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69906. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69907. }
  69908. else {
  69909. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69910. }
  69911. }
  69912. else {
  69913. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69914. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69915. }
  69916. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69917. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69918. }
  69919. else {
  69920. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69921. }
  69922. }
  69923. this._initializeGenerator();
  69924. this._applyFilterValues();
  69925. }
  69926. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  69927. /**
  69928. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  69929. */
  69930. get: function () {
  69931. return this._bias;
  69932. },
  69933. /**
  69934. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  69935. */
  69936. set: function (bias) {
  69937. this._bias = bias;
  69938. },
  69939. enumerable: true,
  69940. configurable: true
  69941. });
  69942. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  69943. /**
  69944. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69945. */
  69946. get: function () {
  69947. return this._normalBias;
  69948. },
  69949. /**
  69950. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69951. */
  69952. set: function (normalBias) {
  69953. this._normalBias = normalBias;
  69954. },
  69955. enumerable: true,
  69956. configurable: true
  69957. });
  69958. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  69959. /**
  69960. * Gets the blur box offset: offset applied during the blur pass.
  69961. * Only usefull if useKernelBlur = false
  69962. */
  69963. get: function () {
  69964. return this._blurBoxOffset;
  69965. },
  69966. /**
  69967. * Sets the blur box offset: offset applied during the blur pass.
  69968. * Only usefull if useKernelBlur = false
  69969. */
  69970. set: function (value) {
  69971. if (this._blurBoxOffset === value) {
  69972. return;
  69973. }
  69974. this._blurBoxOffset = value;
  69975. this._disposeBlurPostProcesses();
  69976. },
  69977. enumerable: true,
  69978. configurable: true
  69979. });
  69980. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  69981. /**
  69982. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  69983. * 2 means half of the size.
  69984. */
  69985. get: function () {
  69986. return this._blurScale;
  69987. },
  69988. /**
  69989. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  69990. * 2 means half of the size.
  69991. */
  69992. set: function (value) {
  69993. if (this._blurScale === value) {
  69994. return;
  69995. }
  69996. this._blurScale = value;
  69997. this._disposeBlurPostProcesses();
  69998. },
  69999. enumerable: true,
  70000. configurable: true
  70001. });
  70002. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  70003. /**
  70004. * Gets the blur kernel: kernel size of the blur pass.
  70005. * Only usefull if useKernelBlur = true
  70006. */
  70007. get: function () {
  70008. return this._blurKernel;
  70009. },
  70010. /**
  70011. * Sets the blur kernel: kernel size of the blur pass.
  70012. * Only usefull if useKernelBlur = true
  70013. */
  70014. set: function (value) {
  70015. if (this._blurKernel === value) {
  70016. return;
  70017. }
  70018. this._blurKernel = value;
  70019. this._disposeBlurPostProcesses();
  70020. },
  70021. enumerable: true,
  70022. configurable: true
  70023. });
  70024. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  70025. /**
  70026. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  70027. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70028. */
  70029. get: function () {
  70030. return this._useKernelBlur;
  70031. },
  70032. /**
  70033. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  70034. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70035. */
  70036. set: function (value) {
  70037. if (this._useKernelBlur === value) {
  70038. return;
  70039. }
  70040. this._useKernelBlur = value;
  70041. this._disposeBlurPostProcesses();
  70042. },
  70043. enumerable: true,
  70044. configurable: true
  70045. });
  70046. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  70047. /**
  70048. * Gets the depth scale used in ESM mode.
  70049. */
  70050. get: function () {
  70051. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  70052. },
  70053. /**
  70054. * Sets the depth scale used in ESM mode.
  70055. * This can override the scale stored on the light.
  70056. */
  70057. set: function (value) {
  70058. this._depthScale = value;
  70059. },
  70060. enumerable: true,
  70061. configurable: true
  70062. });
  70063. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  70064. /**
  70065. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  70066. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70067. */
  70068. get: function () {
  70069. return this._filter;
  70070. },
  70071. /**
  70072. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  70073. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70074. */
  70075. set: function (value) {
  70076. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  70077. if (this._light.needCube()) {
  70078. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70079. this.useExponentialShadowMap = true;
  70080. return;
  70081. }
  70082. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70083. this.useCloseExponentialShadowMap = true;
  70084. return;
  70085. }
  70086. // PCF on cubemap would also be expensive
  70087. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70088. this.usePoissonSampling = true;
  70089. return;
  70090. }
  70091. }
  70092. // Weblg1 fallback for PCF.
  70093. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70094. if (this._scene.getEngine().webGLVersion === 1) {
  70095. this.usePoissonSampling = true;
  70096. return;
  70097. }
  70098. }
  70099. if (this._filter === value) {
  70100. return;
  70101. }
  70102. this._filter = value;
  70103. this._disposeBlurPostProcesses();
  70104. this._applyFilterValues();
  70105. this._light._markMeshesAsLightDirty();
  70106. },
  70107. enumerable: true,
  70108. configurable: true
  70109. });
  70110. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  70111. /**
  70112. * Gets if the current filter is set to Poisson Sampling.
  70113. */
  70114. get: function () {
  70115. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  70116. },
  70117. /**
  70118. * Sets the current filter to Poisson Sampling.
  70119. */
  70120. set: function (value) {
  70121. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  70122. return;
  70123. }
  70124. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  70125. },
  70126. enumerable: true,
  70127. configurable: true
  70128. });
  70129. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  70130. /**
  70131. * Gets if the current filter is set to VSM.
  70132. * DEPRECATED. Should use useExponentialShadowMap instead.
  70133. */
  70134. get: function () {
  70135. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70136. return this.useExponentialShadowMap;
  70137. },
  70138. /**
  70139. * Sets the current filter is to VSM.
  70140. * DEPRECATED. Should use useExponentialShadowMap instead.
  70141. */
  70142. set: function (value) {
  70143. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70144. this.useExponentialShadowMap = value;
  70145. },
  70146. enumerable: true,
  70147. configurable: true
  70148. });
  70149. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  70150. /**
  70151. * Gets if the current filter is set to blurred VSM.
  70152. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70153. */
  70154. get: function () {
  70155. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70156. return this.useBlurExponentialShadowMap;
  70157. },
  70158. /**
  70159. * Sets the current filter is to blurred VSM.
  70160. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70161. */
  70162. set: function (value) {
  70163. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70164. this.useBlurExponentialShadowMap = value;
  70165. },
  70166. enumerable: true,
  70167. configurable: true
  70168. });
  70169. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  70170. /**
  70171. * Gets if the current filter is set to ESM.
  70172. */
  70173. get: function () {
  70174. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  70175. },
  70176. /**
  70177. * Sets the current filter is to ESM.
  70178. */
  70179. set: function (value) {
  70180. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  70181. return;
  70182. }
  70183. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70184. },
  70185. enumerable: true,
  70186. configurable: true
  70187. });
  70188. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  70189. /**
  70190. * Gets if the current filter is set to filtered ESM.
  70191. */
  70192. get: function () {
  70193. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  70194. },
  70195. /**
  70196. * Gets if the current filter is set to filtered ESM.
  70197. */
  70198. set: function (value) {
  70199. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70200. return;
  70201. }
  70202. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70203. },
  70204. enumerable: true,
  70205. configurable: true
  70206. });
  70207. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  70208. /**
  70209. * Gets if the current filter is set to "close ESM" (using the inverse of the
  70210. * exponential to prevent steep falloff artifacts).
  70211. */
  70212. get: function () {
  70213. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  70214. },
  70215. /**
  70216. * Sets the current filter to "close ESM" (using the inverse of the
  70217. * exponential to prevent steep falloff artifacts).
  70218. */
  70219. set: function (value) {
  70220. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  70221. return;
  70222. }
  70223. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70224. },
  70225. enumerable: true,
  70226. configurable: true
  70227. });
  70228. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  70229. /**
  70230. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  70231. * exponential to prevent steep falloff artifacts).
  70232. */
  70233. get: function () {
  70234. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  70235. },
  70236. /**
  70237. * Sets the current filter to filtered "close ESM" (using the inverse of the
  70238. * exponential to prevent steep falloff artifacts).
  70239. */
  70240. set: function (value) {
  70241. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70242. return;
  70243. }
  70244. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70245. },
  70246. enumerable: true,
  70247. configurable: true
  70248. });
  70249. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  70250. /**
  70251. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  70252. */
  70253. get: function () {
  70254. return this.filter === ShadowGenerator.FILTER_PCF;
  70255. },
  70256. /**
  70257. * Sets the current filter to "PCF" (percentage closer filtering).
  70258. */
  70259. set: function (value) {
  70260. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  70261. return;
  70262. }
  70263. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  70264. },
  70265. enumerable: true,
  70266. configurable: true
  70267. });
  70268. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  70269. /**
  70270. * Gets the PCF or PCSS Quality.
  70271. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70272. */
  70273. get: function () {
  70274. return this._filteringQuality;
  70275. },
  70276. /**
  70277. * Sets the PCF or PCSS Quality.
  70278. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70279. */
  70280. set: function (filteringQuality) {
  70281. this._filteringQuality = filteringQuality;
  70282. },
  70283. enumerable: true,
  70284. configurable: true
  70285. });
  70286. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  70287. /**
  70288. * Gets if the current filter is set to "PCSS" (contact hardening).
  70289. */
  70290. get: function () {
  70291. return this.filter === ShadowGenerator.FILTER_PCSS;
  70292. },
  70293. /**
  70294. * Sets the current filter to "PCSS" (contact hardening).
  70295. */
  70296. set: function (value) {
  70297. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  70298. return;
  70299. }
  70300. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  70301. },
  70302. enumerable: true,
  70303. configurable: true
  70304. });
  70305. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  70306. /**
  70307. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70308. * Using a ratio helps keeping shape stability independently of the map size.
  70309. *
  70310. * It does not account for the light projection as it was having too much
  70311. * instability during the light setup or during light position changes.
  70312. *
  70313. * Only valid if useContactHardeningShadow is true.
  70314. */
  70315. get: function () {
  70316. return this._contactHardeningLightSizeUVRatio;
  70317. },
  70318. /**
  70319. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70320. * Using a ratio helps keeping shape stability independently of the map size.
  70321. *
  70322. * It does not account for the light projection as it was having too much
  70323. * instability during the light setup or during light position changes.
  70324. *
  70325. * Only valid if useContactHardeningShadow is true.
  70326. */
  70327. set: function (contactHardeningLightSizeUVRatio) {
  70328. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  70329. },
  70330. enumerable: true,
  70331. configurable: true
  70332. });
  70333. /**
  70334. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  70335. * 0 means strongest and 1 would means no shadow.
  70336. * @returns the darkness.
  70337. */
  70338. ShadowGenerator.prototype.getDarkness = function () {
  70339. return this._darkness;
  70340. };
  70341. /**
  70342. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  70343. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  70344. * @returns the shadow generator allowing fluent coding.
  70345. */
  70346. ShadowGenerator.prototype.setDarkness = function (darkness) {
  70347. if (darkness >= 1.0)
  70348. this._darkness = 1.0;
  70349. else if (darkness <= 0.0)
  70350. this._darkness = 0.0;
  70351. else
  70352. this._darkness = darkness;
  70353. return this;
  70354. };
  70355. /**
  70356. * Sets the ability to have transparent shadow (boolean).
  70357. * @param transparent True if transparent else False
  70358. * @returns the shadow generator allowing fluent coding
  70359. */
  70360. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  70361. this._transparencyShadow = transparent;
  70362. return this;
  70363. };
  70364. /**
  70365. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  70366. * @returns The render target texture if present otherwise, null
  70367. */
  70368. ShadowGenerator.prototype.getShadowMap = function () {
  70369. return this._shadowMap;
  70370. };
  70371. /**
  70372. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  70373. * @returns The render target texture if the shadow map is present otherwise, null
  70374. */
  70375. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  70376. if (this._shadowMap2) {
  70377. return this._shadowMap2;
  70378. }
  70379. return this._shadowMap;
  70380. };
  70381. /**
  70382. * Helper function to add a mesh and its descendants to the list of shadow casters.
  70383. * @param mesh Mesh to add
  70384. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  70385. * @returns the Shadow Generator itself
  70386. */
  70387. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  70388. if (includeDescendants === void 0) { includeDescendants = true; }
  70389. var _a;
  70390. if (!this._shadowMap) {
  70391. return this;
  70392. }
  70393. if (!this._shadowMap.renderList) {
  70394. this._shadowMap.renderList = [];
  70395. }
  70396. this._shadowMap.renderList.push(mesh);
  70397. if (includeDescendants) {
  70398. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  70399. }
  70400. return this;
  70401. };
  70402. /**
  70403. * Helper function to remove a mesh and its descendants from the list of shadow casters
  70404. * @param mesh Mesh to remove
  70405. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  70406. * @returns the Shadow Generator itself
  70407. */
  70408. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  70409. if (includeDescendants === void 0) { includeDescendants = true; }
  70410. if (!this._shadowMap || !this._shadowMap.renderList) {
  70411. return this;
  70412. }
  70413. var index = this._shadowMap.renderList.indexOf(mesh);
  70414. if (index !== -1) {
  70415. this._shadowMap.renderList.splice(index, 1);
  70416. }
  70417. if (includeDescendants) {
  70418. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  70419. var child = _a[_i];
  70420. this.removeShadowCaster(child);
  70421. }
  70422. }
  70423. return this;
  70424. };
  70425. /**
  70426. * Returns the associated light object.
  70427. * @returns the light generating the shadow
  70428. */
  70429. ShadowGenerator.prototype.getLight = function () {
  70430. return this._light;
  70431. };
  70432. ShadowGenerator.prototype._initializeGenerator = function () {
  70433. this._light._markMeshesAsLightDirty();
  70434. this._initializeShadowMap();
  70435. };
  70436. ShadowGenerator.prototype._initializeShadowMap = function () {
  70437. var _this = this;
  70438. // Render target
  70439. var engine = this._scene.getEngine();
  70440. if (engine.webGLVersion > 1) {
  70441. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  70442. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  70443. }
  70444. else {
  70445. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  70446. }
  70447. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70448. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70449. this._shadowMap.anisotropicFilteringLevel = 1;
  70450. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70451. this._shadowMap.renderParticles = false;
  70452. this._shadowMap.ignoreCameraViewport = true;
  70453. // Record Face Index before render.
  70454. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  70455. _this._currentFaceIndex = faceIndex;
  70456. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70457. engine.setColorWrite(false);
  70458. }
  70459. });
  70460. // Custom render function.
  70461. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  70462. // Blur if required afer render.
  70463. this._shadowMap.onAfterUnbindObservable.add(function () {
  70464. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70465. engine.setColorWrite(true);
  70466. }
  70467. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  70468. return;
  70469. }
  70470. var shadowMap = _this.getShadowMapForRendering();
  70471. if (shadowMap) {
  70472. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  70473. }
  70474. });
  70475. // Clear according to the chosen filter.
  70476. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  70477. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  70478. this._shadowMap.onClearObservable.add(function (engine) {
  70479. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70480. engine.clear(clearOne, false, true, false);
  70481. }
  70482. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  70483. engine.clear(clearZero, true, true, false);
  70484. }
  70485. else {
  70486. engine.clear(clearOne, true, true, false);
  70487. }
  70488. });
  70489. };
  70490. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  70491. var _this = this;
  70492. var engine = this._scene.getEngine();
  70493. var targetSize = this._mapSize / this.blurScale;
  70494. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  70495. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  70496. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70497. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70498. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70499. }
  70500. if (this.useKernelBlur) {
  70501. 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);
  70502. this._kernelBlurXPostprocess.width = targetSize;
  70503. this._kernelBlurXPostprocess.height = targetSize;
  70504. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  70505. effect.setTexture("textureSampler", _this._shadowMap);
  70506. });
  70507. 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);
  70508. this._kernelBlurXPostprocess.autoClear = false;
  70509. this._kernelBlurYPostprocess.autoClear = false;
  70510. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70511. this._kernelBlurXPostprocess.packedFloat = true;
  70512. this._kernelBlurYPostprocess.packedFloat = true;
  70513. }
  70514. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  70515. }
  70516. else {
  70517. 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);
  70518. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  70519. effect.setFloat2("screenSize", targetSize, targetSize);
  70520. effect.setTexture("textureSampler", _this._shadowMap);
  70521. });
  70522. this._boxBlurPostprocess.autoClear = false;
  70523. this._blurPostProcesses = [this._boxBlurPostprocess];
  70524. }
  70525. };
  70526. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70527. var index;
  70528. var engine = this._scene.getEngine();
  70529. if (depthOnlySubMeshes.length) {
  70530. engine.setColorWrite(false);
  70531. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70532. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  70533. }
  70534. engine.setColorWrite(true);
  70535. }
  70536. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70537. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  70538. }
  70539. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70540. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  70541. }
  70542. if (this._transparencyShadow) {
  70543. for (index = 0; index < transparentSubMeshes.length; index++) {
  70544. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  70545. }
  70546. }
  70547. };
  70548. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  70549. var _this = this;
  70550. var mesh = subMesh.getRenderingMesh();
  70551. var scene = this._scene;
  70552. var engine = scene.getEngine();
  70553. var material = subMesh.getMaterial();
  70554. if (!material) {
  70555. return;
  70556. }
  70557. // Culling
  70558. engine.setState(material.backFaceCulling);
  70559. // Managing instances
  70560. var batch = mesh._getInstancesRenderList(subMesh._id);
  70561. if (batch.mustReturn) {
  70562. return;
  70563. }
  70564. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70565. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  70566. engine.enableEffect(this._effect);
  70567. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70568. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  70569. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  70570. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70571. this._effect.setVector3("lightData", this._cachedDirection);
  70572. }
  70573. else {
  70574. this._effect.setVector3("lightData", this._cachedPosition);
  70575. }
  70576. if (scene.activeCamera) {
  70577. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  70578. }
  70579. // Alpha test
  70580. if (material && material.needAlphaTesting()) {
  70581. var alphaTexture = material.getAlphaTestTexture();
  70582. if (alphaTexture) {
  70583. this._effect.setTexture("diffuseSampler", alphaTexture);
  70584. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  70585. }
  70586. }
  70587. // Bones
  70588. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70589. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  70590. }
  70591. // Morph targets
  70592. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  70593. if (this.forceBackFacesOnly) {
  70594. engine.setState(true, 0, false, true);
  70595. }
  70596. // Draw
  70597. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70598. if (this.forceBackFacesOnly) {
  70599. engine.setState(true, 0, false, false);
  70600. }
  70601. }
  70602. else {
  70603. // Need to reset refresh rate of the shadowMap
  70604. if (this._shadowMap) {
  70605. this._shadowMap.resetRefreshCounter();
  70606. }
  70607. }
  70608. };
  70609. ShadowGenerator.prototype._applyFilterValues = function () {
  70610. if (!this._shadowMap) {
  70611. return;
  70612. }
  70613. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  70614. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  70615. }
  70616. else {
  70617. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70618. }
  70619. };
  70620. /**
  70621. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70622. * @param onCompiled Callback triggered at the and of the effects compilation
  70623. * @param options Sets of optional options forcing the compilation with different modes
  70624. */
  70625. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  70626. var _this = this;
  70627. var localOptions = __assign({ useInstances: false }, options);
  70628. var shadowMap = this.getShadowMap();
  70629. if (!shadowMap) {
  70630. if (onCompiled) {
  70631. onCompiled(this);
  70632. }
  70633. return;
  70634. }
  70635. var renderList = shadowMap.renderList;
  70636. if (!renderList) {
  70637. if (onCompiled) {
  70638. onCompiled(this);
  70639. }
  70640. return;
  70641. }
  70642. var subMeshes = new Array();
  70643. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  70644. var mesh = renderList_1[_i];
  70645. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  70646. }
  70647. if (subMeshes.length === 0) {
  70648. if (onCompiled) {
  70649. onCompiled(this);
  70650. }
  70651. return;
  70652. }
  70653. var currentIndex = 0;
  70654. var checkReady = function () {
  70655. if (!_this._scene || !_this._scene.getEngine()) {
  70656. return;
  70657. }
  70658. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  70659. currentIndex++;
  70660. if (currentIndex >= subMeshes.length) {
  70661. if (onCompiled) {
  70662. onCompiled(_this);
  70663. }
  70664. return;
  70665. }
  70666. }
  70667. setTimeout(checkReady, 16);
  70668. };
  70669. checkReady();
  70670. };
  70671. /**
  70672. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70673. * @param options Sets of optional options forcing the compilation with different modes
  70674. * @returns A promise that resolves when the compilation completes
  70675. */
  70676. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  70677. var _this = this;
  70678. return new Promise(function (resolve) {
  70679. _this.forceCompilation(function () {
  70680. resolve();
  70681. }, options);
  70682. });
  70683. };
  70684. /**
  70685. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  70686. * @param subMesh The submesh we want to render in the shadow map
  70687. * @param useInstances Defines wether will draw in the map using instances
  70688. * @returns true if ready otherwise, false
  70689. */
  70690. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  70691. var defines = [];
  70692. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70693. defines.push("#define FLOAT");
  70694. }
  70695. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70696. defines.push("#define ESM");
  70697. }
  70698. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  70699. defines.push("#define DEPTHTEXTURE");
  70700. }
  70701. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70702. var mesh = subMesh.getMesh();
  70703. var material = subMesh.getMaterial();
  70704. // Normal bias.
  70705. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70706. attribs.push(BABYLON.VertexBuffer.NormalKind);
  70707. defines.push("#define NORMAL");
  70708. if (mesh.nonUniformScaling) {
  70709. defines.push("#define NONUNIFORMSCALING");
  70710. }
  70711. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70712. defines.push("#define DIRECTIONINLIGHTDATA");
  70713. }
  70714. }
  70715. // Alpha test
  70716. if (material && material.needAlphaTesting()) {
  70717. var alphaTexture = material.getAlphaTestTexture();
  70718. if (alphaTexture) {
  70719. defines.push("#define ALPHATEST");
  70720. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70721. attribs.push(BABYLON.VertexBuffer.UVKind);
  70722. defines.push("#define UV1");
  70723. }
  70724. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70725. if (alphaTexture.coordinatesIndex === 1) {
  70726. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70727. defines.push("#define UV2");
  70728. }
  70729. }
  70730. }
  70731. }
  70732. // Bones
  70733. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70736. if (mesh.numBoneInfluencers > 4) {
  70737. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70738. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70739. }
  70740. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70741. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70742. }
  70743. else {
  70744. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70745. }
  70746. // Morph targets
  70747. var manager = mesh.morphTargetManager;
  70748. var morphInfluencers = 0;
  70749. if (manager) {
  70750. if (manager.numInfluencers > 0) {
  70751. defines.push("#define MORPHTARGETS");
  70752. morphInfluencers = manager.numInfluencers;
  70753. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  70754. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  70755. }
  70756. }
  70757. // Instances
  70758. if (useInstances) {
  70759. defines.push("#define INSTANCES");
  70760. attribs.push("world0");
  70761. attribs.push("world1");
  70762. attribs.push("world2");
  70763. attribs.push("world3");
  70764. }
  70765. // Get correct effect
  70766. var join = defines.join("\n");
  70767. if (this._cachedDefines !== join) {
  70768. this._cachedDefines = join;
  70769. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  70770. }
  70771. if (!this._effect.isReady()) {
  70772. return false;
  70773. }
  70774. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70775. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  70776. this._initializeBlurRTTAndPostProcesses();
  70777. }
  70778. }
  70779. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  70780. return false;
  70781. }
  70782. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  70783. return false;
  70784. }
  70785. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  70786. return false;
  70787. }
  70788. return true;
  70789. };
  70790. /**
  70791. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  70792. * @param defines Defines of the material we want to update
  70793. * @param lightIndex Index of the light in the enabled light list of the material
  70794. */
  70795. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  70796. var scene = this._scene;
  70797. var light = this._light;
  70798. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70799. return;
  70800. }
  70801. defines["SHADOW" + lightIndex] = true;
  70802. if (this.useContactHardeningShadow) {
  70803. defines["SHADOWPCSS" + lightIndex] = true;
  70804. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70805. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70806. }
  70807. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70808. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70809. }
  70810. // else default to high.
  70811. }
  70812. if (this.usePercentageCloserFiltering) {
  70813. defines["SHADOWPCF" + lightIndex] = true;
  70814. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70815. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70816. }
  70817. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70818. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70819. }
  70820. // else default to high.
  70821. }
  70822. else if (this.usePoissonSampling) {
  70823. defines["SHADOWPOISSON" + lightIndex] = true;
  70824. }
  70825. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70826. defines["SHADOWESM" + lightIndex] = true;
  70827. }
  70828. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70829. defines["SHADOWCLOSEESM" + lightIndex] = true;
  70830. }
  70831. if (light.needCube()) {
  70832. defines["SHADOWCUBE" + lightIndex] = true;
  70833. }
  70834. };
  70835. /**
  70836. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  70837. * defined in the generator but impacting the effect).
  70838. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  70839. * @param effect The effect we are binfing the information for
  70840. */
  70841. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  70842. var light = this._light;
  70843. var scene = this._scene;
  70844. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70845. return;
  70846. }
  70847. var camera = scene.activeCamera;
  70848. if (!camera) {
  70849. return;
  70850. }
  70851. var shadowMap = this.getShadowMap();
  70852. if (!shadowMap) {
  70853. return;
  70854. }
  70855. if (!light.needCube()) {
  70856. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  70857. }
  70858. // Only PCF uses depth stencil texture.
  70859. if (this._filter === ShadowGenerator.FILTER_PCF) {
  70860. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70861. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70862. }
  70863. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  70864. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70865. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  70866. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70867. }
  70868. else {
  70869. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70870. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  70871. }
  70872. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  70873. };
  70874. /**
  70875. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  70876. * (eq to shadow prjection matrix * light transform matrix)
  70877. * @returns The transform matrix used to create the shadow map
  70878. */
  70879. ShadowGenerator.prototype.getTransformMatrix = function () {
  70880. var scene = this._scene;
  70881. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  70882. return this._transformMatrix;
  70883. }
  70884. this._currentRenderID = scene.getRenderId();
  70885. this._currentFaceIndexCache = this._currentFaceIndex;
  70886. var lightPosition = this._light.position;
  70887. if (this._light.computeTransformedInformation()) {
  70888. lightPosition = this._light.transformedPosition;
  70889. }
  70890. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  70891. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  70892. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  70893. }
  70894. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  70895. this._cachedPosition.copyFrom(lightPosition);
  70896. this._cachedDirection.copyFrom(this._lightDirection);
  70897. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  70898. var shadowMap = this.getShadowMap();
  70899. if (shadowMap) {
  70900. var renderList = shadowMap.renderList;
  70901. if (renderList) {
  70902. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  70903. }
  70904. }
  70905. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  70906. }
  70907. return this._transformMatrix;
  70908. };
  70909. /**
  70910. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  70911. * Cube and 2D textures for instance.
  70912. */
  70913. ShadowGenerator.prototype.recreateShadowMap = function () {
  70914. var shadowMap = this._shadowMap;
  70915. if (!shadowMap) {
  70916. return;
  70917. }
  70918. // Track render list.
  70919. var renderList = shadowMap.renderList;
  70920. // Clean up existing data.
  70921. this._disposeRTTandPostProcesses();
  70922. // Reinitializes.
  70923. this._initializeGenerator();
  70924. // Reaffect the filter to ensure a correct fallback if necessary.
  70925. this.filter = this.filter;
  70926. // Reaffect the filter.
  70927. this._applyFilterValues();
  70928. // Reaffect Render List.
  70929. this._shadowMap.renderList = renderList;
  70930. };
  70931. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  70932. if (this._shadowMap2) {
  70933. this._shadowMap2.dispose();
  70934. this._shadowMap2 = null;
  70935. }
  70936. if (this._boxBlurPostprocess) {
  70937. this._boxBlurPostprocess.dispose();
  70938. this._boxBlurPostprocess = null;
  70939. }
  70940. if (this._kernelBlurXPostprocess) {
  70941. this._kernelBlurXPostprocess.dispose();
  70942. this._kernelBlurXPostprocess = null;
  70943. }
  70944. if (this._kernelBlurYPostprocess) {
  70945. this._kernelBlurYPostprocess.dispose();
  70946. this._kernelBlurYPostprocess = null;
  70947. }
  70948. this._blurPostProcesses = [];
  70949. };
  70950. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  70951. if (this._shadowMap) {
  70952. this._shadowMap.dispose();
  70953. this._shadowMap = null;
  70954. }
  70955. this._disposeBlurPostProcesses();
  70956. };
  70957. /**
  70958. * Disposes the ShadowGenerator.
  70959. * Returns nothing.
  70960. */
  70961. ShadowGenerator.prototype.dispose = function () {
  70962. this._disposeRTTandPostProcesses();
  70963. if (this._light) {
  70964. this._light._shadowGenerator = null;
  70965. this._light._markMeshesAsLightDirty();
  70966. }
  70967. };
  70968. /**
  70969. * Serializes the shadow generator setup to a json object.
  70970. * @returns The serialized JSON object
  70971. */
  70972. ShadowGenerator.prototype.serialize = function () {
  70973. var serializationObject = {};
  70974. var shadowMap = this.getShadowMap();
  70975. if (!shadowMap) {
  70976. return serializationObject;
  70977. }
  70978. serializationObject.lightId = this._light.id;
  70979. serializationObject.mapSize = shadowMap.getRenderSize();
  70980. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  70981. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  70982. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70983. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70984. serializationObject.usePoissonSampling = this.usePoissonSampling;
  70985. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  70986. serializationObject.depthScale = this.depthScale;
  70987. serializationObject.darkness = this.getDarkness();
  70988. serializationObject.blurBoxOffset = this.blurBoxOffset;
  70989. serializationObject.blurKernel = this.blurKernel;
  70990. serializationObject.blurScale = this.blurScale;
  70991. serializationObject.useKernelBlur = this.useKernelBlur;
  70992. serializationObject.transparencyShadow = this._transparencyShadow;
  70993. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70994. serializationObject.bias = this.bias;
  70995. serializationObject.normalBias = this.normalBias;
  70996. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70997. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70998. serializationObject.filteringQuality = this.filteringQuality;
  70999. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  71000. serializationObject.renderList = [];
  71001. if (shadowMap.renderList) {
  71002. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  71003. var mesh = shadowMap.renderList[meshIndex];
  71004. serializationObject.renderList.push(mesh.id);
  71005. }
  71006. }
  71007. return serializationObject;
  71008. };
  71009. /**
  71010. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  71011. * @param parsedShadowGenerator The JSON object to parse
  71012. * @param scene The scene to create the shadow map for
  71013. * @returns The parsed shadow generator
  71014. */
  71015. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  71016. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  71017. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  71018. var shadowMap = shadowGenerator.getShadowMap();
  71019. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  71020. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  71021. meshes.forEach(function (mesh) {
  71022. if (!shadowMap) {
  71023. return;
  71024. }
  71025. if (!shadowMap.renderList) {
  71026. shadowMap.renderList = [];
  71027. }
  71028. shadowMap.renderList.push(mesh);
  71029. });
  71030. }
  71031. if (parsedShadowGenerator.usePoissonSampling) {
  71032. shadowGenerator.usePoissonSampling = true;
  71033. }
  71034. else if (parsedShadowGenerator.useExponentialShadowMap) {
  71035. shadowGenerator.useExponentialShadowMap = true;
  71036. }
  71037. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  71038. shadowGenerator.useBlurExponentialShadowMap = true;
  71039. }
  71040. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  71041. shadowGenerator.useCloseExponentialShadowMap = true;
  71042. }
  71043. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  71044. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  71045. }
  71046. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  71047. shadowGenerator.usePercentageCloserFiltering = true;
  71048. }
  71049. else if (parsedShadowGenerator.useContactHardeningShadow) {
  71050. shadowGenerator.useContactHardeningShadow = true;
  71051. }
  71052. if (parsedShadowGenerator.filteringQuality) {
  71053. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  71054. }
  71055. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  71056. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  71057. }
  71058. // Backward compat
  71059. else if (parsedShadowGenerator.useVarianceShadowMap) {
  71060. shadowGenerator.useExponentialShadowMap = true;
  71061. }
  71062. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  71063. shadowGenerator.useBlurExponentialShadowMap = true;
  71064. }
  71065. if (parsedShadowGenerator.depthScale) {
  71066. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  71067. }
  71068. if (parsedShadowGenerator.blurScale) {
  71069. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  71070. }
  71071. if (parsedShadowGenerator.blurBoxOffset) {
  71072. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  71073. }
  71074. if (parsedShadowGenerator.useKernelBlur) {
  71075. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  71076. }
  71077. if (parsedShadowGenerator.blurKernel) {
  71078. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  71079. }
  71080. if (parsedShadowGenerator.bias !== undefined) {
  71081. shadowGenerator.bias = parsedShadowGenerator.bias;
  71082. }
  71083. if (parsedShadowGenerator.normalBias !== undefined) {
  71084. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  71085. }
  71086. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  71087. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  71088. }
  71089. if (parsedShadowGenerator.darkness) {
  71090. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  71091. }
  71092. if (parsedShadowGenerator.transparencyShadow) {
  71093. shadowGenerator.setTransparencyShadow(true);
  71094. }
  71095. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  71096. return shadowGenerator;
  71097. };
  71098. /**
  71099. * Shadow generator mode None: no filtering applied.
  71100. */
  71101. ShadowGenerator.FILTER_NONE = 0;
  71102. /**
  71103. * Shadow generator mode ESM: Exponential Shadow Mapping.
  71104. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71105. */
  71106. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  71107. /**
  71108. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  71109. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  71110. */
  71111. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  71112. /**
  71113. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  71114. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71115. */
  71116. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  71117. /**
  71118. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  71119. * edge artifacts on steep falloff.
  71120. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71121. */
  71122. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  71123. /**
  71124. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  71125. * edge artifacts on steep falloff.
  71126. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71127. */
  71128. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  71129. /**
  71130. * Shadow generator mode PCF: Percentage Closer Filtering
  71131. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71132. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  71133. */
  71134. ShadowGenerator.FILTER_PCF = 6;
  71135. /**
  71136. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  71137. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71138. * Contact Hardening
  71139. */
  71140. ShadowGenerator.FILTER_PCSS = 7;
  71141. /**
  71142. * Reserved for PCF and PCSS
  71143. * Highest Quality.
  71144. *
  71145. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  71146. *
  71147. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  71148. */
  71149. ShadowGenerator.QUALITY_HIGH = 0;
  71150. /**
  71151. * Reserved for PCF and PCSS
  71152. * Good tradeoff for quality/perf cross devices
  71153. *
  71154. * Execute PCF on a 3*3 kernel.
  71155. *
  71156. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  71157. */
  71158. ShadowGenerator.QUALITY_MEDIUM = 1;
  71159. /**
  71160. * Reserved for PCF and PCSS
  71161. * The lowest quality but the fastest.
  71162. *
  71163. * Execute PCF on a 1*1 kernel.
  71164. *
  71165. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  71166. */
  71167. ShadowGenerator.QUALITY_LOW = 2;
  71168. return ShadowGenerator;
  71169. }());
  71170. BABYLON.ShadowGenerator = ShadowGenerator;
  71171. })(BABYLON || (BABYLON = {}));
  71172. //# sourceMappingURL=babylon.shadowGenerator.js.map
  71173. var BABYLON;
  71174. (function (BABYLON) {
  71175. // Adds the parser to the scene parsers.
  71176. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  71177. // Shadows
  71178. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71179. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71180. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71181. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71182. // SG would be available on their associated lights
  71183. }
  71184. }
  71185. });
  71186. /**
  71187. * Defines the shadow generator component responsible to manage any shadow generators
  71188. * in a given scene.
  71189. */
  71190. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  71191. /**
  71192. * Creates a new instance of the component for the given scene
  71193. * @param scene Defines the scene to register the component in
  71194. */
  71195. function ShadowGeneratorSceneComponent(scene) {
  71196. /**
  71197. * The component name helpfull to identify the component in the list of scene components.
  71198. */
  71199. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  71200. this.scene = scene;
  71201. }
  71202. /**
  71203. * Registers the component in a given scene
  71204. */
  71205. ShadowGeneratorSceneComponent.prototype.register = function () {
  71206. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  71207. };
  71208. /**
  71209. * Rebuilds the elements related to this component in case of
  71210. * context lost for instance.
  71211. */
  71212. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  71213. // Nothing To Do Here.
  71214. };
  71215. /**
  71216. * Serializes the component data to the specified json object
  71217. * @param serializationObject The object to serialize to
  71218. */
  71219. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  71220. // Shadows
  71221. serializationObject.shadowGenerators = [];
  71222. var lights = this.scene.lights;
  71223. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  71224. var light = lights_1[_i];
  71225. var shadowGenerator = light.getShadowGenerator();
  71226. if (shadowGenerator) {
  71227. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71228. }
  71229. }
  71230. };
  71231. /**
  71232. * Adds all the element from the container to the scene
  71233. * @param container the container holding the elements
  71234. */
  71235. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  71236. // Nothing To Do Here. (directly attached to a light)
  71237. };
  71238. /**
  71239. * Removes all the elements in the container from the scene
  71240. * @param container contains the elements to remove
  71241. */
  71242. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  71243. // Nothing To Do Here. (directly attached to a light)
  71244. };
  71245. /**
  71246. * Rebuilds the elements related to this component in case of
  71247. * context lost for instance.
  71248. */
  71249. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  71250. // Nothing To Do Here.
  71251. };
  71252. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  71253. // Shadows
  71254. var scene = this.scene;
  71255. if (this.scene.shadowsEnabled) {
  71256. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  71257. var light = scene.lights[lightIndex];
  71258. var shadowGenerator = light.getShadowGenerator();
  71259. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  71260. var shadowMap = (shadowGenerator.getShadowMap());
  71261. if (scene.textures.indexOf(shadowMap) !== -1) {
  71262. renderTargets.push(shadowMap);
  71263. }
  71264. }
  71265. }
  71266. }
  71267. };
  71268. return ShadowGeneratorSceneComponent;
  71269. }());
  71270. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  71271. })(BABYLON || (BABYLON = {}));
  71272. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  71273. var BABYLON;
  71274. (function (BABYLON) {
  71275. var DefaultLoadingScreen = /** @class */ (function () {
  71276. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  71277. if (_loadingText === void 0) { _loadingText = ""; }
  71278. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  71279. var _this = this;
  71280. this._renderingCanvas = _renderingCanvas;
  71281. this._loadingText = _loadingText;
  71282. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  71283. // Resize
  71284. this._resizeLoadingUI = function () {
  71285. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  71286. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  71287. if (!_this._loadingDiv) {
  71288. return;
  71289. }
  71290. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  71291. _this._loadingDiv.style.left = canvasRect.left + "px";
  71292. _this._loadingDiv.style.top = canvasRect.top + "px";
  71293. _this._loadingDiv.style.width = canvasRect.width + "px";
  71294. _this._loadingDiv.style.height = canvasRect.height + "px";
  71295. };
  71296. }
  71297. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  71298. if (this._loadingDiv) {
  71299. // Do not add a loading screen if there is already one
  71300. return;
  71301. }
  71302. this._loadingDiv = document.createElement("div");
  71303. this._loadingDiv.id = "babylonjsLoadingDiv";
  71304. this._loadingDiv.style.opacity = "0";
  71305. this._loadingDiv.style.transition = "opacity 1.5s ease";
  71306. this._loadingDiv.style.pointerEvents = "none";
  71307. // Loading text
  71308. this._loadingTextDiv = document.createElement("div");
  71309. this._loadingTextDiv.style.position = "absolute";
  71310. this._loadingTextDiv.style.left = "0";
  71311. this._loadingTextDiv.style.top = "50%";
  71312. this._loadingTextDiv.style.marginTop = "80px";
  71313. this._loadingTextDiv.style.width = "100%";
  71314. this._loadingTextDiv.style.height = "20px";
  71315. this._loadingTextDiv.style.fontFamily = "Arial";
  71316. this._loadingTextDiv.style.fontSize = "14px";
  71317. this._loadingTextDiv.style.color = "white";
  71318. this._loadingTextDiv.style.textAlign = "center";
  71319. this._loadingTextDiv.innerHTML = "Loading";
  71320. this._loadingDiv.appendChild(this._loadingTextDiv);
  71321. //set the predefined text
  71322. this._loadingTextDiv.innerHTML = this._loadingText;
  71323. // Generating keyframes
  71324. var style = document.createElement('style');
  71325. style.type = 'text/css';
  71326. 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 }";
  71327. style.innerHTML = keyFrames;
  71328. document.getElementsByTagName('head')[0].appendChild(style);
  71329. // Loading img
  71330. var imgBack = new Image();
  71331. 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";
  71332. imgBack.style.position = "absolute";
  71333. imgBack.style.left = "50%";
  71334. imgBack.style.top = "50%";
  71335. imgBack.style.marginLeft = "-60px";
  71336. imgBack.style.marginTop = "-60px";
  71337. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  71338. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  71339. imgBack.style.transformOrigin = "50% 50%";
  71340. imgBack.style.webkitTransformOrigin = "50% 50%";
  71341. this._loadingDiv.appendChild(imgBack);
  71342. this._resizeLoadingUI();
  71343. window.addEventListener("resize", this._resizeLoadingUI);
  71344. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71345. document.body.appendChild(this._loadingDiv);
  71346. this._loadingDiv.style.opacity = "1";
  71347. };
  71348. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  71349. var _this = this;
  71350. if (!this._loadingDiv) {
  71351. return;
  71352. }
  71353. var onTransitionEnd = function () {
  71354. if (!_this._loadingDiv) {
  71355. return;
  71356. }
  71357. document.body.removeChild(_this._loadingDiv);
  71358. window.removeEventListener("resize", _this._resizeLoadingUI);
  71359. _this._loadingDiv = null;
  71360. };
  71361. this._loadingDiv.style.opacity = "0";
  71362. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  71363. };
  71364. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  71365. set: function (text) {
  71366. this._loadingText = text;
  71367. if (this._loadingTextDiv) {
  71368. this._loadingTextDiv.innerHTML = this._loadingText;
  71369. }
  71370. },
  71371. enumerable: true,
  71372. configurable: true
  71373. });
  71374. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  71375. get: function () {
  71376. return this._loadingDivBackgroundColor;
  71377. },
  71378. set: function (color) {
  71379. this._loadingDivBackgroundColor = color;
  71380. if (!this._loadingDiv) {
  71381. return;
  71382. }
  71383. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71384. },
  71385. enumerable: true,
  71386. configurable: true
  71387. });
  71388. return DefaultLoadingScreen;
  71389. }());
  71390. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  71391. })(BABYLON || (BABYLON = {}));
  71392. //# sourceMappingURL=babylon.loadingScreen.js.map
  71393. var BABYLON;
  71394. (function (BABYLON) {
  71395. var SceneLoaderProgressEvent = /** @class */ (function () {
  71396. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  71397. this.lengthComputable = lengthComputable;
  71398. this.loaded = loaded;
  71399. this.total = total;
  71400. }
  71401. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  71402. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  71403. };
  71404. return SceneLoaderProgressEvent;
  71405. }());
  71406. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  71407. var SceneLoader = /** @class */ (function () {
  71408. function SceneLoader() {
  71409. }
  71410. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  71411. get: function () {
  71412. return 0;
  71413. },
  71414. enumerable: true,
  71415. configurable: true
  71416. });
  71417. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  71418. get: function () {
  71419. return 1;
  71420. },
  71421. enumerable: true,
  71422. configurable: true
  71423. });
  71424. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  71425. get: function () {
  71426. return 2;
  71427. },
  71428. enumerable: true,
  71429. configurable: true
  71430. });
  71431. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  71432. get: function () {
  71433. return 3;
  71434. },
  71435. enumerable: true,
  71436. configurable: true
  71437. });
  71438. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  71439. get: function () {
  71440. return SceneLoader._ForceFullSceneLoadingForIncremental;
  71441. },
  71442. set: function (value) {
  71443. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  71444. },
  71445. enumerable: true,
  71446. configurable: true
  71447. });
  71448. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  71449. get: function () {
  71450. return SceneLoader._ShowLoadingScreen;
  71451. },
  71452. set: function (value) {
  71453. SceneLoader._ShowLoadingScreen = value;
  71454. },
  71455. enumerable: true,
  71456. configurable: true
  71457. });
  71458. Object.defineProperty(SceneLoader, "loggingLevel", {
  71459. get: function () {
  71460. return SceneLoader._loggingLevel;
  71461. },
  71462. set: function (value) {
  71463. SceneLoader._loggingLevel = value;
  71464. },
  71465. enumerable: true,
  71466. configurable: true
  71467. });
  71468. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  71469. get: function () {
  71470. return SceneLoader._CleanBoneMatrixWeights;
  71471. },
  71472. set: function (value) {
  71473. SceneLoader._CleanBoneMatrixWeights = value;
  71474. },
  71475. enumerable: true,
  71476. configurable: true
  71477. });
  71478. SceneLoader._getDefaultPlugin = function () {
  71479. return SceneLoader._registeredPlugins[".babylon"];
  71480. };
  71481. SceneLoader._getPluginForExtension = function (extension) {
  71482. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  71483. if (registeredPlugin) {
  71484. return registeredPlugin;
  71485. }
  71486. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  71487. return SceneLoader._getDefaultPlugin();
  71488. };
  71489. SceneLoader._getPluginForDirectLoad = function (data) {
  71490. for (var extension in SceneLoader._registeredPlugins) {
  71491. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  71492. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  71493. return SceneLoader._registeredPlugins[extension];
  71494. }
  71495. }
  71496. return SceneLoader._getDefaultPlugin();
  71497. };
  71498. SceneLoader._getPluginForFilename = function (sceneFilename) {
  71499. if (sceneFilename.name) {
  71500. sceneFilename = sceneFilename.name;
  71501. }
  71502. var queryStringPosition = sceneFilename.indexOf("?");
  71503. if (queryStringPosition !== -1) {
  71504. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  71505. }
  71506. var dotPosition = sceneFilename.lastIndexOf(".");
  71507. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  71508. return SceneLoader._getPluginForExtension(extension);
  71509. };
  71510. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  71511. SceneLoader._getDirectLoad = function (sceneFilename) {
  71512. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  71513. return sceneFilename.substr(5);
  71514. }
  71515. return null;
  71516. };
  71517. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  71518. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  71519. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  71520. var plugin;
  71521. if (registeredPlugin.plugin.createPlugin) {
  71522. plugin = registeredPlugin.plugin.createPlugin();
  71523. }
  71524. else {
  71525. plugin = registeredPlugin.plugin;
  71526. }
  71527. var useArrayBuffer = registeredPlugin.isBinary;
  71528. var database;
  71529. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  71530. var dataCallback = function (data, responseURL) {
  71531. if (scene.isDisposed) {
  71532. onError("Scene has been disposed");
  71533. return;
  71534. }
  71535. scene.database = database;
  71536. onSuccess(plugin, data, responseURL);
  71537. };
  71538. var request = null;
  71539. var pluginDisposed = false;
  71540. var onDisposeObservable = plugin.onDisposeObservable;
  71541. if (onDisposeObservable) {
  71542. onDisposeObservable.add(function () {
  71543. pluginDisposed = true;
  71544. if (request) {
  71545. request.abort();
  71546. request = null;
  71547. }
  71548. onDispose();
  71549. });
  71550. }
  71551. var manifestChecked = function () {
  71552. if (pluginDisposed) {
  71553. return;
  71554. }
  71555. var url = rootUrl + sceneFilename;
  71556. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  71557. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  71558. } : undefined, database, useArrayBuffer, function (request, exception) {
  71559. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  71560. });
  71561. };
  71562. if (directLoad) {
  71563. dataCallback(directLoad);
  71564. return plugin;
  71565. }
  71566. if (rootUrl.indexOf("file:") === -1) {
  71567. var engine = scene.getEngine();
  71568. var canUseOfflineSupport = engine.enableOfflineSupport;
  71569. if (canUseOfflineSupport) {
  71570. // Also check for exceptions
  71571. var exceptionFound = false;
  71572. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  71573. var regex = _a[_i];
  71574. if (regex.test(rootUrl + sceneFilename)) {
  71575. exceptionFound = true;
  71576. break;
  71577. }
  71578. }
  71579. canUseOfflineSupport = !exceptionFound;
  71580. }
  71581. if (canUseOfflineSupport) {
  71582. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  71583. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  71584. }
  71585. else {
  71586. manifestChecked();
  71587. }
  71588. }
  71589. // Loading file from disk via input file or drag'n'drop
  71590. else {
  71591. var fileOrString = sceneFilename;
  71592. if (fileOrString.name) { // File
  71593. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  71594. }
  71595. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  71596. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  71597. }
  71598. else {
  71599. onError("Unable to find file named " + sceneFilename);
  71600. }
  71601. }
  71602. return plugin;
  71603. };
  71604. // Public functions
  71605. SceneLoader.GetPluginForExtension = function (extension) {
  71606. return SceneLoader._getPluginForExtension(extension).plugin;
  71607. };
  71608. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  71609. return !!SceneLoader._registeredPlugins[extension];
  71610. };
  71611. SceneLoader.RegisterPlugin = function (plugin) {
  71612. if (typeof plugin.extensions === "string") {
  71613. var extension = plugin.extensions;
  71614. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71615. plugin: plugin,
  71616. isBinary: false
  71617. };
  71618. }
  71619. else {
  71620. var extensions = plugin.extensions;
  71621. Object.keys(extensions).forEach(function (extension) {
  71622. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71623. plugin: plugin,
  71624. isBinary: extensions[extension].isBinary
  71625. };
  71626. });
  71627. }
  71628. };
  71629. /**
  71630. * Import meshes into a scene
  71631. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71632. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71633. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71634. * @param scene the instance of BABYLON.Scene to append to
  71635. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  71636. * @param onProgress a callback with a progress event for each file being loaded
  71637. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71638. * @param pluginExtension the extension used to determine the plugin
  71639. * @returns The loaded plugin
  71640. */
  71641. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71642. if (sceneFilename === void 0) { sceneFilename = ""; }
  71643. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71644. if (onSuccess === void 0) { onSuccess = null; }
  71645. if (onProgress === void 0) { onProgress = null; }
  71646. if (onError === void 0) { onError = null; }
  71647. if (pluginExtension === void 0) { pluginExtension = null; }
  71648. if (!scene) {
  71649. BABYLON.Tools.Error("No scene available to import mesh to");
  71650. return null;
  71651. }
  71652. if (!sceneFilename) {
  71653. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71654. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71655. }
  71656. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71657. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71658. return null;
  71659. }
  71660. var loadingToken = {};
  71661. scene._addPendingData(loadingToken);
  71662. var disposeHandler = function () {
  71663. scene._removePendingData(loadingToken);
  71664. };
  71665. var errorHandler = function (message, exception) {
  71666. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  71667. if (onError) {
  71668. onError(scene, errorMessage, exception);
  71669. }
  71670. else {
  71671. BABYLON.Tools.Error(errorMessage);
  71672. // should the exception be thrown?
  71673. }
  71674. disposeHandler();
  71675. };
  71676. var progressHandler = onProgress ? function (event) {
  71677. try {
  71678. onProgress(event);
  71679. }
  71680. catch (e) {
  71681. errorHandler("Error in onProgress callback", e);
  71682. }
  71683. } : undefined;
  71684. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  71685. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  71686. if (onSuccess) {
  71687. try {
  71688. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  71689. }
  71690. catch (e) {
  71691. errorHandler("Error in onSuccess callback", e);
  71692. }
  71693. }
  71694. scene._removePendingData(loadingToken);
  71695. };
  71696. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71697. if (plugin.rewriteRootURL) {
  71698. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  71699. }
  71700. if (sceneFilename === "") {
  71701. if (sceneFilename === "") {
  71702. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71703. }
  71704. }
  71705. if (plugin.importMesh) {
  71706. var syncedPlugin = plugin;
  71707. var meshes = new Array();
  71708. var particleSystems = new Array();
  71709. var skeletons = new Array();
  71710. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  71711. return;
  71712. }
  71713. scene.loadingPluginName = plugin.name;
  71714. successHandler(meshes, particleSystems, skeletons, []);
  71715. }
  71716. else {
  71717. var asyncedPlugin = plugin;
  71718. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (result) {
  71719. scene.loadingPluginName = plugin.name;
  71720. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  71721. }).catch(function (error) {
  71722. errorHandler(error.message, error);
  71723. });
  71724. }
  71725. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71726. };
  71727. /**
  71728. * Import meshes into a scene
  71729. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71730. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71731. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71732. * @param scene the instance of BABYLON.Scene to append to
  71733. * @param onProgress a callback with a progress event for each file being loaded
  71734. * @param pluginExtension the extension used to determine the plugin
  71735. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  71736. */
  71737. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71738. if (sceneFilename === void 0) { sceneFilename = ""; }
  71739. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71740. if (onProgress === void 0) { onProgress = null; }
  71741. if (pluginExtension === void 0) { pluginExtension = null; }
  71742. return new Promise(function (resolve, reject) {
  71743. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  71744. resolve({
  71745. meshes: meshes,
  71746. particleSystems: particleSystems,
  71747. skeletons: skeletons,
  71748. animationGroups: animationGroups
  71749. });
  71750. }, onProgress, function (scene, message, exception) {
  71751. reject(exception || new Error(message));
  71752. }, pluginExtension);
  71753. });
  71754. };
  71755. /**
  71756. * Load a scene
  71757. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71758. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71759. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71760. * @param onSuccess a callback with the scene when import succeeds
  71761. * @param onProgress a callback with a progress event for each file being loaded
  71762. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71763. * @param pluginExtension the extension used to determine the plugin
  71764. * @returns The loaded plugin
  71765. */
  71766. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  71767. if (onSuccess === void 0) { onSuccess = null; }
  71768. if (onProgress === void 0) { onProgress = null; }
  71769. if (onError === void 0) { onError = null; }
  71770. if (pluginExtension === void 0) { pluginExtension = null; }
  71771. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  71772. };
  71773. /**
  71774. * Load a scene
  71775. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71776. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71777. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71778. * @param onProgress a callback with a progress event for each file being loaded
  71779. * @param pluginExtension the extension used to determine the plugin
  71780. * @returns The loaded scene
  71781. */
  71782. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  71783. if (onProgress === void 0) { onProgress = null; }
  71784. if (pluginExtension === void 0) { pluginExtension = null; }
  71785. return new Promise(function (resolve, reject) {
  71786. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  71787. resolve(scene);
  71788. }, onProgress, function (scene, message, exception) {
  71789. reject(exception || new Error(message));
  71790. }, pluginExtension);
  71791. });
  71792. };
  71793. /**
  71794. * Append a scene
  71795. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71796. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71797. * @param scene is the instance of BABYLON.Scene to append to
  71798. * @param onSuccess a callback with the scene when import succeeds
  71799. * @param onProgress a callback with a progress event for each file being loaded
  71800. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71801. * @param pluginExtension the extension used to determine the plugin
  71802. * @returns The loaded plugin
  71803. */
  71804. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71805. if (sceneFilename === void 0) { sceneFilename = ""; }
  71806. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71807. if (onSuccess === void 0) { onSuccess = null; }
  71808. if (onProgress === void 0) { onProgress = null; }
  71809. if (onError === void 0) { onError = null; }
  71810. if (pluginExtension === void 0) { pluginExtension = null; }
  71811. if (!scene) {
  71812. BABYLON.Tools.Error("No scene available to append to");
  71813. return null;
  71814. }
  71815. if (!sceneFilename) {
  71816. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71817. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71818. }
  71819. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71820. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71821. return null;
  71822. }
  71823. if (SceneLoader.ShowLoadingScreen) {
  71824. scene.getEngine().displayLoadingUI();
  71825. }
  71826. var loadingToken = {};
  71827. scene._addPendingData(loadingToken);
  71828. var disposeHandler = function () {
  71829. scene._removePendingData(loadingToken);
  71830. scene.getEngine().hideLoadingUI();
  71831. };
  71832. var errorHandler = function (message, exception) {
  71833. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71834. if (onError) {
  71835. onError(scene, errorMessage, exception);
  71836. }
  71837. else {
  71838. BABYLON.Tools.Error(errorMessage);
  71839. // should the exception be thrown?
  71840. }
  71841. disposeHandler();
  71842. };
  71843. var progressHandler = onProgress ? function (event) {
  71844. try {
  71845. onProgress(event);
  71846. }
  71847. catch (e) {
  71848. errorHandler("Error in onProgress callback", e);
  71849. }
  71850. } : undefined;
  71851. var successHandler = function () {
  71852. if (onSuccess) {
  71853. try {
  71854. onSuccess(scene);
  71855. }
  71856. catch (e) {
  71857. errorHandler("Error in onSuccess callback", e);
  71858. }
  71859. }
  71860. scene._removePendingData(loadingToken);
  71861. };
  71862. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71863. if (sceneFilename === "") {
  71864. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71865. }
  71866. if (plugin.load) {
  71867. var syncedPlugin = plugin;
  71868. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  71869. return;
  71870. }
  71871. scene.loadingPluginName = plugin.name;
  71872. successHandler();
  71873. }
  71874. else {
  71875. var asyncedPlugin = plugin;
  71876. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function () {
  71877. scene.loadingPluginName = plugin.name;
  71878. successHandler();
  71879. }).catch(function (error) {
  71880. errorHandler(error.message, error);
  71881. });
  71882. }
  71883. if (SceneLoader.ShowLoadingScreen) {
  71884. scene.executeWhenReady(function () {
  71885. scene.getEngine().hideLoadingUI();
  71886. });
  71887. }
  71888. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71889. };
  71890. /**
  71891. * Append a scene
  71892. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71893. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71894. * @param scene is the instance of BABYLON.Scene to append to
  71895. * @param onProgress a callback with a progress event for each file being loaded
  71896. * @param pluginExtension the extension used to determine the plugin
  71897. * @returns The given scene
  71898. */
  71899. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71900. if (sceneFilename === void 0) { sceneFilename = ""; }
  71901. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71902. if (onProgress === void 0) { onProgress = null; }
  71903. if (pluginExtension === void 0) { pluginExtension = null; }
  71904. return new Promise(function (resolve, reject) {
  71905. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  71906. resolve(scene);
  71907. }, onProgress, function (scene, message, exception) {
  71908. reject(exception || new Error(message));
  71909. }, pluginExtension);
  71910. });
  71911. };
  71912. /**
  71913. * Load a scene into an asset container
  71914. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71915. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71916. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  71917. * @param onSuccess a callback with the scene when import succeeds
  71918. * @param onProgress a callback with a progress event for each file being loaded
  71919. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71920. * @param pluginExtension the extension used to determine the plugin
  71921. * @returns The loaded plugin
  71922. */
  71923. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71924. if (sceneFilename === void 0) { sceneFilename = ""; }
  71925. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71926. if (onSuccess === void 0) { onSuccess = null; }
  71927. if (onProgress === void 0) { onProgress = null; }
  71928. if (onError === void 0) { onError = null; }
  71929. if (pluginExtension === void 0) { pluginExtension = null; }
  71930. if (!scene) {
  71931. BABYLON.Tools.Error("No scene available to load asset container to");
  71932. return null;
  71933. }
  71934. if (!sceneFilename) {
  71935. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71936. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71937. }
  71938. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71939. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71940. return null;
  71941. }
  71942. var loadingToken = {};
  71943. scene._addPendingData(loadingToken);
  71944. var disposeHandler = function () {
  71945. scene._removePendingData(loadingToken);
  71946. };
  71947. var errorHandler = function (message, exception) {
  71948. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71949. if (onError) {
  71950. onError(scene, errorMessage, exception);
  71951. }
  71952. else {
  71953. BABYLON.Tools.Error(errorMessage);
  71954. // should the exception be thrown?
  71955. }
  71956. disposeHandler();
  71957. };
  71958. var progressHandler = onProgress ? function (event) {
  71959. try {
  71960. onProgress(event);
  71961. }
  71962. catch (e) {
  71963. errorHandler("Error in onProgress callback", e);
  71964. }
  71965. } : undefined;
  71966. var successHandler = function (assets) {
  71967. if (onSuccess) {
  71968. try {
  71969. onSuccess(assets);
  71970. }
  71971. catch (e) {
  71972. errorHandler("Error in onSuccess callback", e);
  71973. }
  71974. }
  71975. scene._removePendingData(loadingToken);
  71976. };
  71977. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71978. if (plugin.loadAssetContainer) {
  71979. var syncedPlugin = plugin;
  71980. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  71981. if (!assetContainer) {
  71982. return;
  71983. }
  71984. scene.loadingPluginName = plugin.name;
  71985. successHandler(assetContainer);
  71986. }
  71987. else if (plugin.loadAssetContainerAsync) {
  71988. var asyncedPlugin = plugin;
  71989. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (assetContainer) {
  71990. scene.loadingPluginName = plugin.name;
  71991. successHandler(assetContainer);
  71992. }).catch(function (error) {
  71993. errorHandler(error.message, error);
  71994. });
  71995. }
  71996. else {
  71997. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  71998. }
  71999. if (SceneLoader.ShowLoadingScreen) {
  72000. scene.executeWhenReady(function () {
  72001. scene.getEngine().hideLoadingUI();
  72002. });
  72003. }
  72004. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72005. };
  72006. /**
  72007. * Load a scene into an asset container
  72008. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  72009. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  72010. * @param scene is the instance of BABYLON.Scene to append to
  72011. * @param onProgress a callback with a progress event for each file being loaded
  72012. * @param pluginExtension the extension used to determine the plugin
  72013. * @returns The loaded asset container
  72014. */
  72015. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72016. if (sceneFilename === void 0) { sceneFilename = ""; }
  72017. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72018. if (onProgress === void 0) { onProgress = null; }
  72019. if (pluginExtension === void 0) { pluginExtension = null; }
  72020. return new Promise(function (resolve, reject) {
  72021. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  72022. resolve(assetContainer);
  72023. }, onProgress, function (scene, message, exception) {
  72024. reject(exception || new Error(message));
  72025. }, pluginExtension);
  72026. });
  72027. };
  72028. // Flags
  72029. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  72030. SceneLoader._ShowLoadingScreen = true;
  72031. SceneLoader._CleanBoneMatrixWeights = false;
  72032. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  72033. // Members
  72034. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  72035. SceneLoader._registeredPlugins = {};
  72036. return SceneLoader;
  72037. }());
  72038. BABYLON.SceneLoader = SceneLoader;
  72039. ;
  72040. })(BABYLON || (BABYLON = {}));
  72041. //# sourceMappingURL=babylon.sceneLoader.js.map
  72042. var BABYLON;
  72043. (function (BABYLON) {
  72044. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  72045. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72046. var parsedMaterial = parsedData.materials[index];
  72047. if (parsedMaterial.id === id) {
  72048. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72049. }
  72050. }
  72051. return null;
  72052. };
  72053. var isDescendantOf = function (mesh, names, hierarchyIds) {
  72054. for (var i in names) {
  72055. if (mesh.name === names[i]) {
  72056. hierarchyIds.push(mesh.id);
  72057. return true;
  72058. }
  72059. }
  72060. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  72061. hierarchyIds.push(mesh.id);
  72062. return true;
  72063. }
  72064. return false;
  72065. };
  72066. var logOperation = function (operation, producer) {
  72067. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  72068. };
  72069. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  72070. if (addToScene === void 0) { addToScene = false; }
  72071. var container = new BABYLON.AssetContainer(scene);
  72072. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72073. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72074. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72075. // and avoid problems with multiple concurrent .babylon loads.
  72076. var log = "importScene has failed JSON parse";
  72077. try {
  72078. var parsedData = JSON.parse(data);
  72079. log = "";
  72080. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72081. var index;
  72082. var cache;
  72083. // Lights
  72084. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  72085. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  72086. var parsedLight = parsedData.lights[index];
  72087. var light = BABYLON.Light.Parse(parsedLight, scene);
  72088. if (light) {
  72089. container.lights.push(light);
  72090. log += (index === 0 ? "\n\tLights:" : "");
  72091. log += "\n\t\t" + light.toString(fullDetails);
  72092. }
  72093. }
  72094. }
  72095. // Animations
  72096. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  72097. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  72098. var parsedAnimation = parsedData.animations[index];
  72099. var animation = BABYLON.Animation.Parse(parsedAnimation);
  72100. scene.animations.push(animation);
  72101. container.animations.push(animation);
  72102. log += (index === 0 ? "\n\tAnimations:" : "");
  72103. log += "\n\t\t" + animation.toString(fullDetails);
  72104. }
  72105. }
  72106. // Materials
  72107. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  72108. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72109. var parsedMaterial = parsedData.materials[index];
  72110. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72111. container.materials.push(mat);
  72112. log += (index === 0 ? "\n\tMaterials:" : "");
  72113. log += "\n\t\t" + mat.toString(fullDetails);
  72114. }
  72115. }
  72116. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72117. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  72118. var parsedMultiMaterial = parsedData.multiMaterials[index];
  72119. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72120. container.multiMaterials.push(mmat);
  72121. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  72122. log += "\n\t\t" + mmat.toString(fullDetails);
  72123. }
  72124. }
  72125. // Morph targets
  72126. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72127. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72128. var managerData = _a[_i];
  72129. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  72130. }
  72131. }
  72132. // Skeletons
  72133. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72134. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  72135. var parsedSkeleton = parsedData.skeletons[index];
  72136. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72137. container.skeletons.push(skeleton);
  72138. log += (index === 0 ? "\n\tSkeletons:" : "");
  72139. log += "\n\t\t" + skeleton.toString(fullDetails);
  72140. }
  72141. }
  72142. // Geometries
  72143. var geometries = parsedData.geometries;
  72144. if (geometries !== undefined && geometries !== null) {
  72145. var addedGeometry = new Array();
  72146. // Boxes
  72147. var boxes = geometries.boxes;
  72148. if (boxes !== undefined && boxes !== null) {
  72149. for (index = 0, cache = boxes.length; index < cache; index++) {
  72150. var parsedBox = boxes[index];
  72151. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  72152. }
  72153. }
  72154. // Spheres
  72155. var spheres = geometries.spheres;
  72156. if (spheres !== undefined && spheres !== null) {
  72157. for (index = 0, cache = spheres.length; index < cache; index++) {
  72158. var parsedSphere = spheres[index];
  72159. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  72160. }
  72161. }
  72162. // Cylinders
  72163. var cylinders = geometries.cylinders;
  72164. if (cylinders !== undefined && cylinders !== null) {
  72165. for (index = 0, cache = cylinders.length; index < cache; index++) {
  72166. var parsedCylinder = cylinders[index];
  72167. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  72168. }
  72169. }
  72170. // Toruses
  72171. var toruses = geometries.toruses;
  72172. if (toruses !== undefined && toruses !== null) {
  72173. for (index = 0, cache = toruses.length; index < cache; index++) {
  72174. var parsedTorus = toruses[index];
  72175. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  72176. }
  72177. }
  72178. // Grounds
  72179. var grounds = geometries.grounds;
  72180. if (grounds !== undefined && grounds !== null) {
  72181. for (index = 0, cache = grounds.length; index < cache; index++) {
  72182. var parsedGround = grounds[index];
  72183. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  72184. }
  72185. }
  72186. // Planes
  72187. var planes = geometries.planes;
  72188. if (planes !== undefined && planes !== null) {
  72189. for (index = 0, cache = planes.length; index < cache; index++) {
  72190. var parsedPlane = planes[index];
  72191. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  72192. }
  72193. }
  72194. // TorusKnots
  72195. var torusKnots = geometries.torusKnots;
  72196. if (torusKnots !== undefined && torusKnots !== null) {
  72197. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  72198. var parsedTorusKnot = torusKnots[index];
  72199. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  72200. }
  72201. }
  72202. // VertexData
  72203. var vertexData = geometries.vertexData;
  72204. if (vertexData !== undefined && vertexData !== null) {
  72205. for (index = 0, cache = vertexData.length; index < cache; index++) {
  72206. var parsedVertexData = vertexData[index];
  72207. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  72208. }
  72209. }
  72210. addedGeometry.forEach(function (g) {
  72211. if (g) {
  72212. container.geometries.push(g);
  72213. }
  72214. });
  72215. }
  72216. // Transform nodes
  72217. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  72218. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  72219. var parsedTransformNode = parsedData.transformNodes[index];
  72220. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  72221. container.transformNodes.push(node);
  72222. }
  72223. }
  72224. // Meshes
  72225. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72226. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72227. var parsedMesh = parsedData.meshes[index];
  72228. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72229. container.meshes.push(mesh);
  72230. log += (index === 0 ? "\n\tMeshes:" : "");
  72231. log += "\n\t\t" + mesh.toString(fullDetails);
  72232. }
  72233. }
  72234. // Cameras
  72235. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  72236. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  72237. var parsedCamera = parsedData.cameras[index];
  72238. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  72239. container.cameras.push(camera);
  72240. log += (index === 0 ? "\n\tCameras:" : "");
  72241. log += "\n\t\t" + camera.toString(fullDetails);
  72242. }
  72243. }
  72244. // Animation Groups
  72245. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  72246. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  72247. var parsedAnimationGroup = parsedData.animationGroups[index];
  72248. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  72249. container.animationGroups.push(animationGroup);
  72250. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  72251. log += "\n\t\t" + animationGroup.toString(fullDetails);
  72252. }
  72253. }
  72254. // Browsing all the graph to connect the dots
  72255. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  72256. var camera = scene.cameras[index];
  72257. if (camera._waitingParentId) {
  72258. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  72259. camera._waitingParentId = null;
  72260. }
  72261. }
  72262. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72263. var light_1 = scene.lights[index];
  72264. if (light_1 && light_1._waitingParentId) {
  72265. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  72266. light_1._waitingParentId = null;
  72267. }
  72268. }
  72269. // Sounds
  72270. // TODO: add sound
  72271. var loadedSounds = [];
  72272. var loadedSound;
  72273. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72274. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72275. var parsedSound = parsedData.sounds[index];
  72276. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72277. if (!parsedSound.url)
  72278. parsedSound.url = parsedSound.name;
  72279. if (!loadedSounds[parsedSound.url]) {
  72280. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72281. loadedSounds[parsedSound.url] = loadedSound;
  72282. container.sounds.push(loadedSound);
  72283. }
  72284. else {
  72285. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72286. }
  72287. }
  72288. else {
  72289. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72290. }
  72291. }
  72292. }
  72293. loadedSounds = [];
  72294. // Connect parents & children and parse actions
  72295. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  72296. var transformNode = scene.transformNodes[index];
  72297. if (transformNode._waitingParentId) {
  72298. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  72299. transformNode._waitingParentId = null;
  72300. }
  72301. }
  72302. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72303. var mesh = scene.meshes[index];
  72304. if (mesh._waitingParentId) {
  72305. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  72306. mesh._waitingParentId = null;
  72307. }
  72308. if (mesh._waitingActions) {
  72309. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  72310. mesh._waitingActions = null;
  72311. }
  72312. }
  72313. // freeze world matrix application
  72314. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72315. var currentMesh = scene.meshes[index];
  72316. if (currentMesh._waitingFreezeWorldMatrix) {
  72317. currentMesh.freezeWorldMatrix();
  72318. currentMesh._waitingFreezeWorldMatrix = null;
  72319. }
  72320. else {
  72321. currentMesh.computeWorldMatrix(true);
  72322. }
  72323. }
  72324. // Lights exclusions / inclusions
  72325. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72326. var light_2 = scene.lights[index];
  72327. // Excluded check
  72328. if (light_2._excludedMeshesIds.length > 0) {
  72329. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  72330. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  72331. if (excludedMesh) {
  72332. light_2.excludedMeshes.push(excludedMesh);
  72333. }
  72334. }
  72335. light_2._excludedMeshesIds = [];
  72336. }
  72337. // Included check
  72338. if (light_2._includedOnlyMeshesIds.length > 0) {
  72339. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  72340. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  72341. if (includedOnlyMesh) {
  72342. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  72343. }
  72344. }
  72345. light_2._includedOnlyMeshesIds = [];
  72346. }
  72347. }
  72348. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  72349. // Actions (scene)
  72350. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  72351. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  72352. }
  72353. if (!addToScene) {
  72354. container.removeAllFromScene();
  72355. }
  72356. }
  72357. catch (err) {
  72358. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  72359. if (onError) {
  72360. onError(msg, err);
  72361. }
  72362. else {
  72363. BABYLON.Tools.Log(msg);
  72364. throw err;
  72365. }
  72366. }
  72367. finally {
  72368. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72369. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72370. }
  72371. }
  72372. return container;
  72373. };
  72374. BABYLON.SceneLoader.RegisterPlugin({
  72375. name: "babylon.js",
  72376. extensions: ".babylon",
  72377. canDirectLoad: function (data) {
  72378. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  72379. return true;
  72380. }
  72381. return false;
  72382. },
  72383. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  72384. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72385. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72386. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72387. // and avoid problems with multiple concurrent .babylon loads.
  72388. var log = "importMesh has failed JSON parse";
  72389. try {
  72390. var parsedData = JSON.parse(data);
  72391. log = "";
  72392. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72393. if (!meshesNames) {
  72394. meshesNames = null;
  72395. }
  72396. else if (!Array.isArray(meshesNames)) {
  72397. meshesNames = [meshesNames];
  72398. }
  72399. var hierarchyIds = new Array();
  72400. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72401. var loadedSkeletonsIds = [];
  72402. var loadedMaterialsIds = [];
  72403. var index;
  72404. var cache;
  72405. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72406. var parsedMesh = parsedData.meshes[index];
  72407. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  72408. if (meshesNames !== null) {
  72409. // Remove found mesh name from list.
  72410. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  72411. }
  72412. //Geometry?
  72413. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  72414. //does the file contain geometries?
  72415. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  72416. //find the correct geometry and add it to the scene
  72417. var found = false;
  72418. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  72419. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  72420. return;
  72421. }
  72422. else {
  72423. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  72424. if (parsedGeometryData.id === parsedMesh.geometryId) {
  72425. switch (geometryType) {
  72426. case "boxes":
  72427. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  72428. break;
  72429. case "spheres":
  72430. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  72431. break;
  72432. case "cylinders":
  72433. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  72434. break;
  72435. case "toruses":
  72436. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  72437. break;
  72438. case "grounds":
  72439. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  72440. break;
  72441. case "planes":
  72442. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  72443. break;
  72444. case "torusKnots":
  72445. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  72446. break;
  72447. case "vertexData":
  72448. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  72449. break;
  72450. }
  72451. found = true;
  72452. }
  72453. });
  72454. }
  72455. });
  72456. if (found === false) {
  72457. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  72458. }
  72459. }
  72460. }
  72461. // Material ?
  72462. if (parsedMesh.materialId) {
  72463. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  72464. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72465. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  72466. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  72467. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  72468. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  72469. var subMatId = parsedMultiMaterial.materials[matIndex];
  72470. loadedMaterialsIds.push(subMatId);
  72471. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  72472. if (mat) {
  72473. log += "\n\tMaterial " + mat.toString(fullDetails);
  72474. }
  72475. }
  72476. loadedMaterialsIds.push(parsedMultiMaterial.id);
  72477. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72478. if (mmat) {
  72479. materialFound = true;
  72480. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  72481. }
  72482. break;
  72483. }
  72484. }
  72485. }
  72486. if (materialFound === false) {
  72487. loadedMaterialsIds.push(parsedMesh.materialId);
  72488. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  72489. if (!mat) {
  72490. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  72491. }
  72492. else {
  72493. log += "\n\tMaterial " + mat.toString(fullDetails);
  72494. }
  72495. }
  72496. }
  72497. // Skeleton ?
  72498. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72499. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  72500. if (skeletonAlreadyLoaded === false) {
  72501. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  72502. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  72503. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  72504. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72505. skeletons.push(skeleton);
  72506. loadedSkeletonsIds.push(parsedSkeleton.id);
  72507. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  72508. }
  72509. }
  72510. }
  72511. }
  72512. // Morph targets ?
  72513. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72514. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72515. var managerData = _a[_i];
  72516. BABYLON.MorphTargetManager.Parse(managerData, scene);
  72517. }
  72518. }
  72519. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72520. meshes.push(mesh);
  72521. log += "\n\tMesh " + mesh.toString(fullDetails);
  72522. }
  72523. }
  72524. // Connecting parents
  72525. var currentMesh;
  72526. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72527. currentMesh = scene.meshes[index];
  72528. if (currentMesh._waitingParentId) {
  72529. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  72530. currentMesh._waitingParentId = null;
  72531. }
  72532. }
  72533. // freeze and compute world matrix application
  72534. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72535. currentMesh = scene.meshes[index];
  72536. if (currentMesh._waitingFreezeWorldMatrix) {
  72537. currentMesh.freezeWorldMatrix();
  72538. currentMesh._waitingFreezeWorldMatrix = null;
  72539. }
  72540. else {
  72541. currentMesh.computeWorldMatrix(true);
  72542. }
  72543. }
  72544. }
  72545. // Particles
  72546. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  72547. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  72548. if (parser) {
  72549. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  72550. var parsedParticleSystem = parsedData.particleSystems[index];
  72551. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  72552. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  72553. }
  72554. }
  72555. }
  72556. }
  72557. return true;
  72558. }
  72559. catch (err) {
  72560. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  72561. if (onError) {
  72562. onError(msg, err);
  72563. }
  72564. else {
  72565. BABYLON.Tools.Log(msg);
  72566. throw err;
  72567. }
  72568. }
  72569. finally {
  72570. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72571. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72572. }
  72573. }
  72574. return false;
  72575. },
  72576. load: function (scene, data, rootUrl, onError) {
  72577. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72578. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72579. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72580. // and avoid problems with multiple concurrent .babylon loads.
  72581. var log = "importScene has failed JSON parse";
  72582. try {
  72583. var parsedData = JSON.parse(data);
  72584. log = "";
  72585. // Scene
  72586. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  72587. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  72588. }
  72589. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  72590. scene.autoClear = parsedData.autoClear;
  72591. }
  72592. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  72593. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  72594. }
  72595. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  72596. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  72597. }
  72598. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  72599. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  72600. }
  72601. // Fog
  72602. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  72603. scene.fogMode = parsedData.fogMode;
  72604. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  72605. scene.fogStart = parsedData.fogStart;
  72606. scene.fogEnd = parsedData.fogEnd;
  72607. scene.fogDensity = parsedData.fogDensity;
  72608. log += "\tFog mode for scene: ";
  72609. switch (scene.fogMode) {
  72610. // getters not compiling, so using hardcoded
  72611. case 1:
  72612. log += "exp\n";
  72613. break;
  72614. case 2:
  72615. log += "exp2\n";
  72616. break;
  72617. case 3:
  72618. log += "linear\n";
  72619. break;
  72620. }
  72621. }
  72622. //Physics
  72623. if (parsedData.physicsEnabled) {
  72624. var physicsPlugin;
  72625. if (parsedData.physicsEngine === "cannon") {
  72626. physicsPlugin = new BABYLON.CannonJSPlugin();
  72627. }
  72628. else if (parsedData.physicsEngine === "oimo") {
  72629. physicsPlugin = new BABYLON.OimoJSPlugin();
  72630. }
  72631. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  72632. //else - default engine, which is currently oimo
  72633. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  72634. scene.enablePhysics(physicsGravity, physicsPlugin);
  72635. }
  72636. // Metadata
  72637. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  72638. scene.metadata = parsedData.metadata;
  72639. }
  72640. //collisions, if defined. otherwise, default is true
  72641. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  72642. scene.collisionsEnabled = parsedData.collisionsEnabled;
  72643. }
  72644. scene.workerCollisions = !!parsedData.workerCollisions;
  72645. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  72646. if (!container) {
  72647. return false;
  72648. }
  72649. if (parsedData.autoAnimate) {
  72650. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  72651. }
  72652. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  72653. scene.setActiveCameraByID(parsedData.activeCameraID);
  72654. }
  72655. // Environment texture
  72656. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  72657. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  72658. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  72659. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  72660. if (parsedData.environmentTextureRotationY) {
  72661. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  72662. }
  72663. scene.environmentTexture = hdrTexture;
  72664. }
  72665. else {
  72666. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  72667. if (parsedData.environmentTextureRotationY) {
  72668. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  72669. }
  72670. scene.environmentTexture = cubeTexture;
  72671. }
  72672. if (parsedData.createDefaultSkybox === true) {
  72673. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  72674. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  72675. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  72676. }
  72677. }
  72678. // Finish
  72679. return true;
  72680. }
  72681. catch (err) {
  72682. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  72683. if (onError) {
  72684. onError(msg, err);
  72685. }
  72686. else {
  72687. BABYLON.Tools.Log(msg);
  72688. throw err;
  72689. }
  72690. }
  72691. finally {
  72692. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72693. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72694. }
  72695. }
  72696. return false;
  72697. },
  72698. loadAssetContainer: function (scene, data, rootUrl, onError) {
  72699. var container = loadAssetContainer(scene, data, rootUrl, onError);
  72700. return container;
  72701. }
  72702. });
  72703. })(BABYLON || (BABYLON = {}));
  72704. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  72705. var BABYLON;
  72706. (function (BABYLON) {
  72707. var FilesInput = /** @class */ (function () {
  72708. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  72709. this.onProcessFileCallback = function () { return true; };
  72710. this._engine = engine;
  72711. this._currentScene = scene;
  72712. this._sceneLoadedCallback = sceneLoadedCallback;
  72713. this._progressCallback = progressCallback;
  72714. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  72715. this._textureLoadingCallback = textureLoadingCallback;
  72716. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  72717. this._onReloadCallback = onReloadCallback;
  72718. this._errorCallback = errorCallback;
  72719. }
  72720. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  72721. var _this = this;
  72722. if (elementToMonitor) {
  72723. this._elementToMonitor = elementToMonitor;
  72724. this._dragEnterHandler = function (e) { _this.drag(e); };
  72725. this._dragOverHandler = function (e) { _this.drag(e); };
  72726. this._dropHandler = function (e) { _this.drop(e); };
  72727. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  72728. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  72729. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72730. }
  72731. };
  72732. FilesInput.prototype.dispose = function () {
  72733. if (!this._elementToMonitor) {
  72734. return;
  72735. }
  72736. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  72737. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  72738. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  72739. };
  72740. FilesInput.prototype.renderFunction = function () {
  72741. if (this._additionalRenderLoopLogicCallback) {
  72742. this._additionalRenderLoopLogicCallback();
  72743. }
  72744. if (this._currentScene) {
  72745. if (this._textureLoadingCallback) {
  72746. var remaining = this._currentScene.getWaitingItemsCount();
  72747. if (remaining > 0) {
  72748. this._textureLoadingCallback(remaining);
  72749. }
  72750. }
  72751. this._currentScene.render();
  72752. }
  72753. };
  72754. FilesInput.prototype.drag = function (e) {
  72755. e.stopPropagation();
  72756. e.preventDefault();
  72757. };
  72758. FilesInput.prototype.drop = function (eventDrop) {
  72759. eventDrop.stopPropagation();
  72760. eventDrop.preventDefault();
  72761. this.loadFiles(eventDrop);
  72762. };
  72763. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  72764. var _this = this;
  72765. var reader = folder.createReader();
  72766. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  72767. reader.readEntries(function (entries) {
  72768. remaining.count += entries.length;
  72769. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  72770. var entry = entries_1[_i];
  72771. if (entry.isFile) {
  72772. entry.file(function (file) {
  72773. file.correctName = relativePath + file.name;
  72774. files.push(file);
  72775. if (--remaining.count === 0) {
  72776. callback();
  72777. }
  72778. });
  72779. }
  72780. else if (entry.isDirectory) {
  72781. _this._traverseFolder(entry, files, remaining, callback);
  72782. }
  72783. }
  72784. if (--remaining.count) {
  72785. callback();
  72786. }
  72787. });
  72788. };
  72789. FilesInput.prototype._processFiles = function (files) {
  72790. for (var i = 0; i < files.length; i++) {
  72791. var name = files[i].correctName.toLowerCase();
  72792. var extension = name.split('.').pop();
  72793. if (!this.onProcessFileCallback(files[i], name, extension)) {
  72794. continue;
  72795. }
  72796. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  72797. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  72798. this._sceneFileToLoad = files[i];
  72799. }
  72800. else {
  72801. FilesInput.FilesToLoad[name] = files[i];
  72802. }
  72803. }
  72804. };
  72805. FilesInput.prototype.loadFiles = function (event) {
  72806. var _this = this;
  72807. // Handling data transfer via drag'n'drop
  72808. if (event && event.dataTransfer && event.dataTransfer.files) {
  72809. this._filesToLoad = event.dataTransfer.files;
  72810. }
  72811. // Handling files from input files
  72812. if (event && event.target && event.target.files) {
  72813. this._filesToLoad = event.target.files;
  72814. }
  72815. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  72816. return;
  72817. }
  72818. if (this._startingProcessingFilesCallback) {
  72819. this._startingProcessingFilesCallback(this._filesToLoad);
  72820. }
  72821. if (this._filesToLoad && this._filesToLoad.length > 0) {
  72822. var files_1 = new Array();
  72823. var folders = [];
  72824. var items = event.dataTransfer ? event.dataTransfer.items : null;
  72825. for (var i = 0; i < this._filesToLoad.length; i++) {
  72826. var fileToLoad = this._filesToLoad[i];
  72827. var name_1 = fileToLoad.name.toLowerCase();
  72828. var entry = void 0;
  72829. fileToLoad.correctName = name_1;
  72830. if (items) {
  72831. var item = items[i];
  72832. if (item.getAsEntry) {
  72833. entry = item.getAsEntry();
  72834. }
  72835. else if (item.webkitGetAsEntry) {
  72836. entry = item.webkitGetAsEntry();
  72837. }
  72838. }
  72839. if (!entry) {
  72840. files_1.push(fileToLoad);
  72841. }
  72842. else {
  72843. if (entry.isDirectory) {
  72844. folders.push(entry);
  72845. }
  72846. else {
  72847. files_1.push(fileToLoad);
  72848. }
  72849. }
  72850. }
  72851. if (folders.length === 0) {
  72852. this._processFiles(files_1);
  72853. this._processReload();
  72854. }
  72855. else {
  72856. var remaining = { count: folders.length };
  72857. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  72858. var folder = folders_1[_i];
  72859. this._traverseFolder(folder, files_1, remaining, function () {
  72860. _this._processFiles(files_1);
  72861. if (remaining.count === 0) {
  72862. _this._processReload();
  72863. }
  72864. });
  72865. }
  72866. }
  72867. }
  72868. };
  72869. FilesInput.prototype._processReload = function () {
  72870. if (this._onReloadCallback) {
  72871. this._onReloadCallback(this._sceneFileToLoad);
  72872. }
  72873. else {
  72874. this.reload();
  72875. }
  72876. };
  72877. FilesInput.prototype.reload = function () {
  72878. var _this = this;
  72879. // If a scene file has been provided
  72880. if (this._sceneFileToLoad) {
  72881. if (this._currentScene) {
  72882. if (BABYLON.Tools.errorsCount > 0) {
  72883. BABYLON.Tools.ClearLogCache();
  72884. }
  72885. this._engine.stopRenderLoop();
  72886. }
  72887. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  72888. if (_this._progressCallback) {
  72889. _this._progressCallback(progress);
  72890. }
  72891. }).then(function (scene) {
  72892. if (_this._currentScene) {
  72893. _this._currentScene.dispose();
  72894. }
  72895. _this._currentScene = scene;
  72896. if (_this._sceneLoadedCallback) {
  72897. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  72898. }
  72899. // Wait for textures and shaders to be ready
  72900. _this._currentScene.executeWhenReady(function () {
  72901. _this._engine.runRenderLoop(function () {
  72902. _this.renderFunction();
  72903. });
  72904. });
  72905. }).catch(function (error) {
  72906. if (_this._errorCallback) {
  72907. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  72908. }
  72909. });
  72910. }
  72911. else {
  72912. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  72913. }
  72914. };
  72915. FilesInput.FilesToLoad = {};
  72916. return FilesInput;
  72917. }());
  72918. BABYLON.FilesInput = FilesInput;
  72919. })(BABYLON || (BABYLON = {}));
  72920. //# sourceMappingURL=babylon.filesInput.js.map
  72921. var BABYLON;
  72922. (function (BABYLON) {
  72923. var Tags = /** @class */ (function () {
  72924. function Tags() {
  72925. }
  72926. Tags.EnableFor = function (obj) {
  72927. obj._tags = obj._tags || {};
  72928. obj.hasTags = function () {
  72929. return Tags.HasTags(obj);
  72930. };
  72931. obj.addTags = function (tagsString) {
  72932. return Tags.AddTagsTo(obj, tagsString);
  72933. };
  72934. obj.removeTags = function (tagsString) {
  72935. return Tags.RemoveTagsFrom(obj, tagsString);
  72936. };
  72937. obj.matchesTagsQuery = function (tagsQuery) {
  72938. return Tags.MatchesQuery(obj, tagsQuery);
  72939. };
  72940. };
  72941. Tags.DisableFor = function (obj) {
  72942. delete obj._tags;
  72943. delete obj.hasTags;
  72944. delete obj.addTags;
  72945. delete obj.removeTags;
  72946. delete obj.matchesTagsQuery;
  72947. };
  72948. Tags.HasTags = function (obj) {
  72949. if (!obj._tags) {
  72950. return false;
  72951. }
  72952. return !BABYLON.Tools.IsEmpty(obj._tags);
  72953. };
  72954. Tags.GetTags = function (obj, asString) {
  72955. if (asString === void 0) { asString = true; }
  72956. if (!obj._tags) {
  72957. return null;
  72958. }
  72959. if (asString) {
  72960. var tagsArray = [];
  72961. for (var tag in obj._tags) {
  72962. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  72963. tagsArray.push(tag);
  72964. }
  72965. }
  72966. return tagsArray.join(" ");
  72967. }
  72968. else {
  72969. return obj._tags;
  72970. }
  72971. };
  72972. // the tags 'true' and 'false' are reserved and cannot be used as tags
  72973. // a tag cannot start with '||', '&&', and '!'
  72974. // it cannot contain whitespaces
  72975. Tags.AddTagsTo = function (obj, tagsString) {
  72976. if (!tagsString) {
  72977. return;
  72978. }
  72979. if (typeof tagsString !== "string") {
  72980. return;
  72981. }
  72982. var tags = tagsString.split(" ");
  72983. tags.forEach(function (tag, index, array) {
  72984. Tags._AddTagTo(obj, tag);
  72985. });
  72986. };
  72987. Tags._AddTagTo = function (obj, tag) {
  72988. tag = tag.trim();
  72989. if (tag === "" || tag === "true" || tag === "false") {
  72990. return;
  72991. }
  72992. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  72993. return;
  72994. }
  72995. Tags.EnableFor(obj);
  72996. obj._tags[tag] = true;
  72997. };
  72998. Tags.RemoveTagsFrom = function (obj, tagsString) {
  72999. if (!Tags.HasTags(obj)) {
  73000. return;
  73001. }
  73002. var tags = tagsString.split(" ");
  73003. for (var t in tags) {
  73004. Tags._RemoveTagFrom(obj, tags[t]);
  73005. }
  73006. };
  73007. Tags._RemoveTagFrom = function (obj, tag) {
  73008. delete obj._tags[tag];
  73009. };
  73010. Tags.MatchesQuery = function (obj, tagsQuery) {
  73011. if (tagsQuery === undefined) {
  73012. return true;
  73013. }
  73014. if (tagsQuery === "") {
  73015. return Tags.HasTags(obj);
  73016. }
  73017. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  73018. };
  73019. return Tags;
  73020. }());
  73021. BABYLON.Tags = Tags;
  73022. })(BABYLON || (BABYLON = {}));
  73023. //# sourceMappingURL=babylon.tags.js.map
  73024. var BABYLON;
  73025. (function (BABYLON) {
  73026. /**
  73027. * Class used to evalaute queries containing `and` and `or` operators
  73028. */
  73029. var AndOrNotEvaluator = /** @class */ (function () {
  73030. function AndOrNotEvaluator() {
  73031. }
  73032. /**
  73033. * Evaluate a query
  73034. * @param query defines the query to evaluate
  73035. * @param evaluateCallback defines the callback used to filter result
  73036. * @returns true if the query matches
  73037. */
  73038. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  73039. if (!query.match(/\([^\(\)]*\)/g)) {
  73040. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  73041. }
  73042. else {
  73043. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  73044. // remove parenthesis
  73045. r = r.slice(1, r.length - 1);
  73046. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  73047. });
  73048. }
  73049. if (query === "true") {
  73050. return true;
  73051. }
  73052. if (query === "false") {
  73053. return false;
  73054. }
  73055. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  73056. };
  73057. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  73058. evaluateCallback = evaluateCallback || (function (r) {
  73059. return r === "true" ? true : false;
  73060. });
  73061. var result;
  73062. var or = parenthesisContent.split("||");
  73063. for (var i in or) {
  73064. if (or.hasOwnProperty(i)) {
  73065. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  73066. var and = ori.split("&&");
  73067. if (and.length > 1) {
  73068. for (var j = 0; j < and.length; ++j) {
  73069. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  73070. if (andj !== "true" && andj !== "false") {
  73071. if (andj[0] === "!") {
  73072. result = !evaluateCallback(andj.substring(1));
  73073. }
  73074. else {
  73075. result = evaluateCallback(andj);
  73076. }
  73077. }
  73078. else {
  73079. result = andj === "true" ? true : false;
  73080. }
  73081. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  73082. ori = "false";
  73083. break;
  73084. }
  73085. }
  73086. }
  73087. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  73088. result = true;
  73089. break;
  73090. }
  73091. // result equals false (or undefined)
  73092. if (ori !== "true" && ori !== "false") {
  73093. if (ori[0] === "!") {
  73094. result = !evaluateCallback(ori.substring(1));
  73095. }
  73096. else {
  73097. result = evaluateCallback(ori);
  73098. }
  73099. }
  73100. else {
  73101. result = ori === "true" ? true : false;
  73102. }
  73103. }
  73104. }
  73105. // the whole parenthesis scope is replaced by 'true' or 'false'
  73106. return result ? "true" : "false";
  73107. };
  73108. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  73109. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  73110. // remove whitespaces
  73111. r = r.replace(/[\s]/g, function () { return ""; });
  73112. return r.length % 2 ? "!" : "";
  73113. });
  73114. booleanString = booleanString.trim();
  73115. if (booleanString === "!true") {
  73116. booleanString = "false";
  73117. }
  73118. else if (booleanString === "!false") {
  73119. booleanString = "true";
  73120. }
  73121. return booleanString;
  73122. };
  73123. return AndOrNotEvaluator;
  73124. }());
  73125. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  73126. })(BABYLON || (BABYLON = {}));
  73127. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  73128. var BABYLON;
  73129. (function (BABYLON) {
  73130. /**
  73131. * Class used to enable access to IndexedDB
  73132. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  73133. */
  73134. var Database = /** @class */ (function () {
  73135. /**
  73136. * Creates a new Database
  73137. * @param urlToScene defines the url to load the scene
  73138. * @param callbackManifestChecked defines the callback to use when manifest is checked
  73139. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  73140. */
  73141. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  73142. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  73143. var _this = this;
  73144. // Handling various flavors of prefixed version of IndexedDB
  73145. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  73146. this.callbackManifestChecked = callbackManifestChecked;
  73147. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  73148. this.db = null;
  73149. this._enableSceneOffline = false;
  73150. this._enableTexturesOffline = false;
  73151. this.manifestVersionFound = 0;
  73152. this.mustUpdateRessources = false;
  73153. this.hasReachedQuota = false;
  73154. if (!Database.IDBStorageEnabled) {
  73155. this.callbackManifestChecked(true);
  73156. }
  73157. else {
  73158. if (disableManifestCheck) {
  73159. this._enableSceneOffline = true;
  73160. this._enableTexturesOffline = true;
  73161. this.manifestVersionFound = 1;
  73162. BABYLON.Tools.SetImmediate(function () {
  73163. _this.callbackManifestChecked(true);
  73164. });
  73165. }
  73166. else {
  73167. this._checkManifestFile();
  73168. }
  73169. }
  73170. }
  73171. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  73172. /**
  73173. * Gets a boolean indicating if scene must be saved in the database
  73174. */
  73175. get: function () {
  73176. return this._enableSceneOffline;
  73177. },
  73178. enumerable: true,
  73179. configurable: true
  73180. });
  73181. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  73182. /**
  73183. * Gets a boolean indicating if textures must be saved in the database
  73184. */
  73185. get: function () {
  73186. return this._enableTexturesOffline;
  73187. },
  73188. enumerable: true,
  73189. configurable: true
  73190. });
  73191. Database.prototype._checkManifestFile = function () {
  73192. var _this = this;
  73193. var noManifestFile = function () {
  73194. _this._enableSceneOffline = false;
  73195. _this._enableTexturesOffline = false;
  73196. _this.callbackManifestChecked(false);
  73197. };
  73198. var timeStampUsed = false;
  73199. var manifestURL = this.currentSceneUrl + ".manifest";
  73200. var xhr = new XMLHttpRequest();
  73201. if (navigator.onLine) {
  73202. // Adding a timestamp to by-pass browsers' cache
  73203. timeStampUsed = true;
  73204. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  73205. }
  73206. xhr.open("GET", manifestURL, true);
  73207. xhr.addEventListener("load", function () {
  73208. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73209. try {
  73210. var manifestFile = JSON.parse(xhr.response);
  73211. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  73212. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  73213. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  73214. _this.manifestVersionFound = manifestFile.version;
  73215. }
  73216. if (_this.callbackManifestChecked) {
  73217. _this.callbackManifestChecked(true);
  73218. }
  73219. }
  73220. catch (ex) {
  73221. noManifestFile();
  73222. }
  73223. }
  73224. else {
  73225. noManifestFile();
  73226. }
  73227. }, false);
  73228. xhr.addEventListener("error", function (event) {
  73229. if (timeStampUsed) {
  73230. timeStampUsed = false;
  73231. // Let's retry without the timeStamp
  73232. // It could fail when coupled with HTML5 Offline API
  73233. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  73234. xhr.open("GET", retryManifestURL, true);
  73235. xhr.send();
  73236. }
  73237. else {
  73238. noManifestFile();
  73239. }
  73240. }, false);
  73241. try {
  73242. xhr.send();
  73243. }
  73244. catch (ex) {
  73245. BABYLON.Tools.Error("Error on XHR send request.");
  73246. this.callbackManifestChecked(false);
  73247. }
  73248. };
  73249. /**
  73250. * Open the database and make it available
  73251. * @param successCallback defines the callback to call on success
  73252. * @param errorCallback defines the callback to call on error
  73253. */
  73254. Database.prototype.openAsync = function (successCallback, errorCallback) {
  73255. var _this = this;
  73256. var handleError = function () {
  73257. _this.isSupported = false;
  73258. if (errorCallback)
  73259. errorCallback();
  73260. };
  73261. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  73262. // Your browser doesn't support IndexedDB
  73263. this.isSupported = false;
  73264. if (errorCallback)
  73265. errorCallback();
  73266. }
  73267. else {
  73268. // If the DB hasn't been opened or created yet
  73269. if (!this.db) {
  73270. this.hasReachedQuota = false;
  73271. this.isSupported = true;
  73272. var request = this.idbFactory.open("babylonjs", 1);
  73273. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  73274. request.onerror = function (event) {
  73275. handleError();
  73276. };
  73277. // executes when a version change transaction cannot complete due to other active transactions
  73278. request.onblocked = function (event) {
  73279. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  73280. handleError();
  73281. };
  73282. // DB has been opened successfully
  73283. request.onsuccess = function (event) {
  73284. _this.db = request.result;
  73285. successCallback();
  73286. };
  73287. // Initialization of the DB. Creating Scenes & Textures stores
  73288. request.onupgradeneeded = function (event) {
  73289. _this.db = (event.target).result;
  73290. if (_this.db) {
  73291. try {
  73292. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  73293. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  73294. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  73295. }
  73296. catch (ex) {
  73297. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  73298. handleError();
  73299. }
  73300. }
  73301. };
  73302. }
  73303. // DB has already been created and opened
  73304. else {
  73305. if (successCallback)
  73306. successCallback();
  73307. }
  73308. }
  73309. };
  73310. /**
  73311. * Loads an image from the database
  73312. * @param url defines the url to load from
  73313. * @param image defines the target DOM image
  73314. */
  73315. Database.prototype.loadImageFromDB = function (url, image) {
  73316. var _this = this;
  73317. var completeURL = Database._ReturnFullUrlLocation(url);
  73318. var saveAndLoadImage = function () {
  73319. if (!_this.hasReachedQuota && _this.db !== null) {
  73320. // the texture is not yet in the DB, let's try to save it
  73321. _this._saveImageIntoDBAsync(completeURL, image);
  73322. }
  73323. // If the texture is not in the DB and we've reached the DB quota limit
  73324. // let's load it directly from the web
  73325. else {
  73326. image.src = url;
  73327. }
  73328. };
  73329. if (!this.mustUpdateRessources) {
  73330. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  73331. }
  73332. // First time we're download the images or update requested in the manifest file by a version change
  73333. else {
  73334. saveAndLoadImage();
  73335. }
  73336. };
  73337. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  73338. if (this.isSupported && this.db !== null) {
  73339. var texture;
  73340. var transaction = this.db.transaction(["textures"]);
  73341. transaction.onabort = function (event) {
  73342. image.src = url;
  73343. };
  73344. transaction.oncomplete = function (event) {
  73345. var blobTextureURL;
  73346. if (texture) {
  73347. var URL = window.URL || window.webkitURL;
  73348. blobTextureURL = URL.createObjectURL(texture.data);
  73349. image.onerror = function () {
  73350. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  73351. image.src = url;
  73352. };
  73353. image.src = blobTextureURL;
  73354. }
  73355. else {
  73356. notInDBCallback();
  73357. }
  73358. };
  73359. var getRequest = transaction.objectStore("textures").get(url);
  73360. getRequest.onsuccess = function (event) {
  73361. texture = (event.target).result;
  73362. };
  73363. getRequest.onerror = function (event) {
  73364. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  73365. image.src = url;
  73366. };
  73367. }
  73368. else {
  73369. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73370. image.src = url;
  73371. }
  73372. };
  73373. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  73374. var _this = this;
  73375. if (this.isSupported) {
  73376. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  73377. var generateBlobUrl = function () {
  73378. var blobTextureURL;
  73379. if (blob) {
  73380. var URL = window.URL || window.webkitURL;
  73381. try {
  73382. blobTextureURL = URL.createObjectURL(blob);
  73383. }
  73384. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  73385. catch (ex) {
  73386. blobTextureURL = URL.createObjectURL(blob);
  73387. }
  73388. }
  73389. if (blobTextureURL) {
  73390. image.src = blobTextureURL;
  73391. }
  73392. };
  73393. if (Database.IsUASupportingBlobStorage) { // Create XHR
  73394. var xhr = new XMLHttpRequest(), blob;
  73395. xhr.open("GET", url, true);
  73396. xhr.responseType = "blob";
  73397. xhr.addEventListener("load", function () {
  73398. if (xhr.status === 200 && _this.db) {
  73399. // Blob as response (XHR2)
  73400. blob = xhr.response;
  73401. var transaction = _this.db.transaction(["textures"], "readwrite");
  73402. // the transaction could abort because of a QuotaExceededError error
  73403. transaction.onabort = function (event) {
  73404. try {
  73405. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73406. var srcElement = (event.srcElement || event.target);
  73407. var error = srcElement.error;
  73408. if (error && error.name === "QuotaExceededError") {
  73409. _this.hasReachedQuota = true;
  73410. }
  73411. }
  73412. catch (ex) { }
  73413. generateBlobUrl();
  73414. };
  73415. transaction.oncomplete = function (event) {
  73416. generateBlobUrl();
  73417. };
  73418. var newTexture = { textureUrl: url, data: blob };
  73419. try {
  73420. // Put the blob into the dabase
  73421. var addRequest = transaction.objectStore("textures").put(newTexture);
  73422. addRequest.onsuccess = function (event) {
  73423. };
  73424. addRequest.onerror = function (event) {
  73425. generateBlobUrl();
  73426. };
  73427. }
  73428. catch (ex) {
  73429. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  73430. if (ex.code === 25) {
  73431. Database.IsUASupportingBlobStorage = false;
  73432. }
  73433. image.src = url;
  73434. }
  73435. }
  73436. else {
  73437. image.src = url;
  73438. }
  73439. }, false);
  73440. xhr.addEventListener("error", function (event) {
  73441. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  73442. image.src = url;
  73443. }, false);
  73444. xhr.send();
  73445. }
  73446. else {
  73447. image.src = url;
  73448. }
  73449. }
  73450. else {
  73451. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73452. image.src = url;
  73453. }
  73454. };
  73455. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  73456. var _this = this;
  73457. var updateVersion = function () {
  73458. // the version is not yet in the DB or we need to update it
  73459. _this._saveVersionIntoDBAsync(url, versionLoaded);
  73460. };
  73461. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  73462. };
  73463. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  73464. var _this = this;
  73465. if (this.isSupported && this.db) {
  73466. var version;
  73467. try {
  73468. var transaction = this.db.transaction(["versions"]);
  73469. transaction.oncomplete = function (event) {
  73470. if (version) {
  73471. // If the version in the JSON file is different from the version in DB
  73472. if (_this.manifestVersionFound !== version.data) {
  73473. _this.mustUpdateRessources = true;
  73474. updateInDBCallback();
  73475. }
  73476. else {
  73477. callback(version.data);
  73478. }
  73479. }
  73480. // version was not found in DB
  73481. else {
  73482. _this.mustUpdateRessources = true;
  73483. updateInDBCallback();
  73484. }
  73485. };
  73486. transaction.onabort = function (event) {
  73487. callback(-1);
  73488. };
  73489. var getRequest = transaction.objectStore("versions").get(url);
  73490. getRequest.onsuccess = function (event) {
  73491. version = (event.target).result;
  73492. };
  73493. getRequest.onerror = function (event) {
  73494. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  73495. callback(-1);
  73496. };
  73497. }
  73498. catch (ex) {
  73499. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  73500. callback(-1);
  73501. }
  73502. }
  73503. else {
  73504. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73505. callback(-1);
  73506. }
  73507. };
  73508. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  73509. var _this = this;
  73510. if (this.isSupported && !this.hasReachedQuota && this.db) {
  73511. try {
  73512. // Open a transaction to the database
  73513. var transaction = this.db.transaction(["versions"], "readwrite");
  73514. // the transaction could abort because of a QuotaExceededError error
  73515. transaction.onabort = function (event) {
  73516. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73517. var error = event.srcElement['error'];
  73518. if (error && error.name === "QuotaExceededError") {
  73519. _this.hasReachedQuota = true;
  73520. }
  73521. }
  73522. catch (ex) { }
  73523. callback(-1);
  73524. };
  73525. transaction.oncomplete = function (event) {
  73526. callback(_this.manifestVersionFound);
  73527. };
  73528. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  73529. // Put the scene into the database
  73530. var addRequest = transaction.objectStore("versions").put(newVersion);
  73531. addRequest.onsuccess = function (event) {
  73532. };
  73533. addRequest.onerror = function (event) {
  73534. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  73535. };
  73536. }
  73537. catch (ex) {
  73538. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  73539. callback(-1);
  73540. }
  73541. }
  73542. else {
  73543. callback(-1);
  73544. }
  73545. };
  73546. /**
  73547. * Loads a file from database
  73548. * @param url defines the URL to load from
  73549. * @param sceneLoaded defines a callback to call on success
  73550. * @param progressCallBack defines a callback to call when progress changed
  73551. * @param errorCallback defines a callback to call on error
  73552. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  73553. */
  73554. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  73555. var _this = this;
  73556. var completeUrl = Database._ReturnFullUrlLocation(url);
  73557. var saveAndLoadFile = function () {
  73558. // the scene is not yet in the DB, let's try to save it
  73559. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73560. };
  73561. this._checkVersionFromDB(completeUrl, function (version) {
  73562. if (version !== -1) {
  73563. if (!_this.mustUpdateRessources) {
  73564. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  73565. }
  73566. else {
  73567. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73568. }
  73569. }
  73570. else {
  73571. if (errorCallback) {
  73572. errorCallback();
  73573. }
  73574. }
  73575. });
  73576. };
  73577. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  73578. if (this.isSupported && this.db) {
  73579. var targetStore;
  73580. if (url.indexOf(".babylon") !== -1) {
  73581. targetStore = "scenes";
  73582. }
  73583. else {
  73584. targetStore = "textures";
  73585. }
  73586. var file;
  73587. var transaction = this.db.transaction([targetStore]);
  73588. transaction.oncomplete = function (event) {
  73589. if (file) {
  73590. callback(file.data);
  73591. }
  73592. // file was not found in DB
  73593. else {
  73594. notInDBCallback();
  73595. }
  73596. };
  73597. transaction.onabort = function (event) {
  73598. notInDBCallback();
  73599. };
  73600. var getRequest = transaction.objectStore(targetStore).get(url);
  73601. getRequest.onsuccess = function (event) {
  73602. file = (event.target).result;
  73603. };
  73604. getRequest.onerror = function (event) {
  73605. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  73606. notInDBCallback();
  73607. };
  73608. }
  73609. else {
  73610. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73611. callback();
  73612. }
  73613. };
  73614. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  73615. var _this = this;
  73616. if (this.isSupported) {
  73617. var targetStore;
  73618. if (url.indexOf(".babylon") !== -1) {
  73619. targetStore = "scenes";
  73620. }
  73621. else {
  73622. targetStore = "textures";
  73623. }
  73624. // Create XHR
  73625. var xhr = new XMLHttpRequest();
  73626. var fileData;
  73627. xhr.open("GET", url + "?" + Date.now(), true);
  73628. if (useArrayBuffer) {
  73629. xhr.responseType = "arraybuffer";
  73630. }
  73631. if (progressCallback) {
  73632. xhr.onprogress = progressCallback;
  73633. }
  73634. xhr.addEventListener("load", function () {
  73635. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  73636. // Blob as response (XHR2)
  73637. //fileData = xhr.responseText;
  73638. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  73639. if (!_this.hasReachedQuota && _this.db) {
  73640. // Open a transaction to the database
  73641. var transaction = _this.db.transaction([targetStore], "readwrite");
  73642. // the transaction could abort because of a QuotaExceededError error
  73643. transaction.onabort = function (event) {
  73644. try {
  73645. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73646. var error = event.srcElement['error'];
  73647. if (error && error.name === "QuotaExceededError") {
  73648. _this.hasReachedQuota = true;
  73649. }
  73650. }
  73651. catch (ex) { }
  73652. callback(fileData);
  73653. };
  73654. transaction.oncomplete = function (event) {
  73655. callback(fileData);
  73656. };
  73657. var newFile;
  73658. if (targetStore === "scenes") {
  73659. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  73660. }
  73661. else {
  73662. newFile = { textureUrl: url, data: fileData };
  73663. }
  73664. try {
  73665. // Put the scene into the database
  73666. var addRequest = transaction.objectStore(targetStore).put(newFile);
  73667. addRequest.onsuccess = function (event) {
  73668. };
  73669. addRequest.onerror = function (event) {
  73670. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  73671. };
  73672. }
  73673. catch (ex) {
  73674. callback(fileData);
  73675. }
  73676. }
  73677. else {
  73678. callback(fileData);
  73679. }
  73680. }
  73681. else {
  73682. if (xhr.status >= 400 && errorCallback) {
  73683. errorCallback(xhr);
  73684. }
  73685. else {
  73686. callback();
  73687. }
  73688. }
  73689. }, false);
  73690. xhr.addEventListener("error", function (event) {
  73691. BABYLON.Tools.Error("error on XHR request.");
  73692. callback();
  73693. }, false);
  73694. xhr.send();
  73695. }
  73696. else {
  73697. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73698. callback();
  73699. }
  73700. };
  73701. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  73702. Database.IsUASupportingBlobStorage = true;
  73703. /** Gets a boolean indicating if Database storate is enabled */
  73704. Database.IDBStorageEnabled = true;
  73705. Database._ParseURL = function (url) {
  73706. var a = document.createElement('a');
  73707. a.href = url;
  73708. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  73709. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  73710. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  73711. return absLocation;
  73712. };
  73713. Database._ReturnFullUrlLocation = function (url) {
  73714. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  73715. return (Database._ParseURL(window.location.href) + url);
  73716. }
  73717. else {
  73718. return url;
  73719. }
  73720. };
  73721. return Database;
  73722. }());
  73723. BABYLON.Database = Database;
  73724. })(BABYLON || (BABYLON = {}));
  73725. //# sourceMappingURL=babylon.database.js.map
  73726. var BABYLON;
  73727. (function (BABYLON) {
  73728. var FresnelParameters = /** @class */ (function () {
  73729. function FresnelParameters() {
  73730. this._isEnabled = true;
  73731. this.leftColor = BABYLON.Color3.White();
  73732. this.rightColor = BABYLON.Color3.Black();
  73733. this.bias = 0;
  73734. this.power = 1;
  73735. }
  73736. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  73737. get: function () {
  73738. return this._isEnabled;
  73739. },
  73740. set: function (value) {
  73741. if (this._isEnabled === value) {
  73742. return;
  73743. }
  73744. this._isEnabled = value;
  73745. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  73746. },
  73747. enumerable: true,
  73748. configurable: true
  73749. });
  73750. FresnelParameters.prototype.clone = function () {
  73751. var newFresnelParameters = new FresnelParameters();
  73752. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  73753. return newFresnelParameters;
  73754. };
  73755. FresnelParameters.prototype.serialize = function () {
  73756. var serializationObject = {};
  73757. serializationObject.isEnabled = this.isEnabled;
  73758. serializationObject.leftColor = this.leftColor.asArray();
  73759. serializationObject.rightColor = this.rightColor.asArray();
  73760. serializationObject.bias = this.bias;
  73761. serializationObject.power = this.power;
  73762. return serializationObject;
  73763. };
  73764. FresnelParameters.Parse = function (parsedFresnelParameters) {
  73765. var fresnelParameters = new FresnelParameters();
  73766. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  73767. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  73768. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  73769. fresnelParameters.bias = parsedFresnelParameters.bias;
  73770. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  73771. return fresnelParameters;
  73772. };
  73773. return FresnelParameters;
  73774. }());
  73775. BABYLON.FresnelParameters = FresnelParameters;
  73776. })(BABYLON || (BABYLON = {}));
  73777. //# sourceMappingURL=babylon.fresnelParameters.js.map
  73778. var BABYLON;
  73779. (function (BABYLON) {
  73780. var MultiMaterial = /** @class */ (function (_super) {
  73781. __extends(MultiMaterial, _super);
  73782. function MultiMaterial(name, scene) {
  73783. var _this = _super.call(this, name, scene, true) || this;
  73784. scene.multiMaterials.push(_this);
  73785. _this.subMaterials = new Array();
  73786. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  73787. return _this;
  73788. }
  73789. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  73790. get: function () {
  73791. return this._subMaterials;
  73792. },
  73793. set: function (value) {
  73794. this._subMaterials = value;
  73795. this._hookArray(value);
  73796. },
  73797. enumerable: true,
  73798. configurable: true
  73799. });
  73800. MultiMaterial.prototype._hookArray = function (array) {
  73801. var _this = this;
  73802. var oldPush = array.push;
  73803. array.push = function () {
  73804. var items = [];
  73805. for (var _i = 0; _i < arguments.length; _i++) {
  73806. items[_i] = arguments[_i];
  73807. }
  73808. var result = oldPush.apply(array, items);
  73809. _this._markAllSubMeshesAsTexturesDirty();
  73810. return result;
  73811. };
  73812. var oldSplice = array.splice;
  73813. array.splice = function (index, deleteCount) {
  73814. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73815. _this._markAllSubMeshesAsTexturesDirty();
  73816. return deleted;
  73817. };
  73818. };
  73819. // Properties
  73820. MultiMaterial.prototype.getSubMaterial = function (index) {
  73821. if (index < 0 || index >= this.subMaterials.length) {
  73822. return this.getScene().defaultMaterial;
  73823. }
  73824. return this.subMaterials[index];
  73825. };
  73826. MultiMaterial.prototype.getActiveTextures = function () {
  73827. var _a;
  73828. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  73829. if (subMaterial) {
  73830. return subMaterial.getActiveTextures();
  73831. }
  73832. else {
  73833. return [];
  73834. }
  73835. }));
  73836. };
  73837. // Methods
  73838. MultiMaterial.prototype.getClassName = function () {
  73839. return "MultiMaterial";
  73840. };
  73841. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  73842. for (var index = 0; index < this.subMaterials.length; index++) {
  73843. var subMaterial = this.subMaterials[index];
  73844. if (subMaterial) {
  73845. if (subMaterial.storeEffectOnSubMeshes) {
  73846. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  73847. return false;
  73848. }
  73849. continue;
  73850. }
  73851. if (!subMaterial.isReady(mesh)) {
  73852. return false;
  73853. }
  73854. }
  73855. }
  73856. return true;
  73857. };
  73858. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  73859. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  73860. for (var index = 0; index < this.subMaterials.length; index++) {
  73861. var subMaterial = null;
  73862. var current = this.subMaterials[index];
  73863. if (cloneChildren && current) {
  73864. subMaterial = current.clone(name + "-" + current.name);
  73865. }
  73866. else {
  73867. subMaterial = this.subMaterials[index];
  73868. }
  73869. newMultiMaterial.subMaterials.push(subMaterial);
  73870. }
  73871. return newMultiMaterial;
  73872. };
  73873. MultiMaterial.prototype.serialize = function () {
  73874. var serializationObject = {};
  73875. serializationObject.name = this.name;
  73876. serializationObject.id = this.id;
  73877. if (BABYLON.Tags) {
  73878. serializationObject.tags = BABYLON.Tags.GetTags(this);
  73879. }
  73880. serializationObject.materials = [];
  73881. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  73882. var subMat = this.subMaterials[matIndex];
  73883. if (subMat) {
  73884. serializationObject.materials.push(subMat.id);
  73885. }
  73886. else {
  73887. serializationObject.materials.push(null);
  73888. }
  73889. }
  73890. return serializationObject;
  73891. };
  73892. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  73893. var scene = this.getScene();
  73894. if (!scene) {
  73895. return;
  73896. }
  73897. var index = scene.multiMaterials.indexOf(this);
  73898. if (index >= 0) {
  73899. scene.multiMaterials.splice(index, 1);
  73900. }
  73901. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  73902. };
  73903. return MultiMaterial;
  73904. }(BABYLON.Material));
  73905. BABYLON.MultiMaterial = MultiMaterial;
  73906. })(BABYLON || (BABYLON = {}));
  73907. //# sourceMappingURL=babylon.multiMaterial.js.map
  73908. var BABYLON;
  73909. (function (BABYLON) {
  73910. var FreeCameraTouchInput = /** @class */ (function () {
  73911. function FreeCameraTouchInput() {
  73912. this._offsetX = null;
  73913. this._offsetY = null;
  73914. this._pointerPressed = new Array();
  73915. this.touchAngularSensibility = 200000.0;
  73916. this.touchMoveSensibility = 250.0;
  73917. }
  73918. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  73919. var _this = this;
  73920. var previousPosition = null;
  73921. if (this._pointerInput === undefined) {
  73922. this._onLostFocus = function (evt) {
  73923. _this._offsetX = null;
  73924. _this._offsetY = null;
  73925. };
  73926. this._pointerInput = function (p, s) {
  73927. var evt = p.event;
  73928. if (evt.pointerType === "mouse") {
  73929. return;
  73930. }
  73931. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73932. if (!noPreventDefault) {
  73933. evt.preventDefault();
  73934. }
  73935. _this._pointerPressed.push(evt.pointerId);
  73936. if (_this._pointerPressed.length !== 1) {
  73937. return;
  73938. }
  73939. previousPosition = {
  73940. x: evt.clientX,
  73941. y: evt.clientY
  73942. };
  73943. }
  73944. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  73945. if (!noPreventDefault) {
  73946. evt.preventDefault();
  73947. }
  73948. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73949. if (index === -1) {
  73950. return;
  73951. }
  73952. _this._pointerPressed.splice(index, 1);
  73953. if (index != 0) {
  73954. return;
  73955. }
  73956. previousPosition = null;
  73957. _this._offsetX = null;
  73958. _this._offsetY = null;
  73959. }
  73960. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  73961. if (!noPreventDefault) {
  73962. evt.preventDefault();
  73963. }
  73964. if (!previousPosition) {
  73965. return;
  73966. }
  73967. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73968. if (index != 0) {
  73969. return;
  73970. }
  73971. _this._offsetX = evt.clientX - previousPosition.x;
  73972. _this._offsetY = -(evt.clientY - previousPosition.y);
  73973. }
  73974. };
  73975. }
  73976. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  73977. if (this._onLostFocus) {
  73978. element.addEventListener("blur", this._onLostFocus);
  73979. }
  73980. };
  73981. FreeCameraTouchInput.prototype.detachControl = function (element) {
  73982. if (this._pointerInput && element) {
  73983. if (this._observer) {
  73984. this.camera.getScene().onPointerObservable.remove(this._observer);
  73985. this._observer = null;
  73986. }
  73987. if (this._onLostFocus) {
  73988. element.removeEventListener("blur", this._onLostFocus);
  73989. this._onLostFocus = null;
  73990. }
  73991. this._pointerPressed = [];
  73992. this._offsetX = null;
  73993. this._offsetY = null;
  73994. }
  73995. };
  73996. FreeCameraTouchInput.prototype.checkInputs = function () {
  73997. if (this._offsetX && this._offsetY) {
  73998. var camera = this.camera;
  73999. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  74000. if (this._pointerPressed.length > 1) {
  74001. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  74002. }
  74003. else {
  74004. var speed = camera._computeLocalCameraSpeed();
  74005. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  74006. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  74007. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  74008. }
  74009. }
  74010. };
  74011. FreeCameraTouchInput.prototype.getClassName = function () {
  74012. return "FreeCameraTouchInput";
  74013. };
  74014. FreeCameraTouchInput.prototype.getSimpleName = function () {
  74015. return "touch";
  74016. };
  74017. __decorate([
  74018. BABYLON.serialize()
  74019. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  74020. __decorate([
  74021. BABYLON.serialize()
  74022. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  74023. return FreeCameraTouchInput;
  74024. }());
  74025. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  74026. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  74027. })(BABYLON || (BABYLON = {}));
  74028. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  74029. var BABYLON;
  74030. (function (BABYLON) {
  74031. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  74032. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  74033. });
  74034. // We're mainly based on the logic defined into the FreeCamera code
  74035. var TouchCamera = /** @class */ (function (_super) {
  74036. __extends(TouchCamera, _super);
  74037. //-- end properties for backward compatibility for inputs
  74038. function TouchCamera(name, position, scene) {
  74039. var _this = _super.call(this, name, position, scene) || this;
  74040. _this.inputs.addTouch();
  74041. _this._setupInputs();
  74042. return _this;
  74043. }
  74044. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  74045. //-- Begin properties for backward compatibility for inputs
  74046. get: function () {
  74047. var touch = this.inputs.attached["touch"];
  74048. if (touch)
  74049. return touch.touchAngularSensibility;
  74050. return 0;
  74051. },
  74052. set: function (value) {
  74053. var touch = this.inputs.attached["touch"];
  74054. if (touch)
  74055. touch.touchAngularSensibility = value;
  74056. },
  74057. enumerable: true,
  74058. configurable: true
  74059. });
  74060. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  74061. get: function () {
  74062. var touch = this.inputs.attached["touch"];
  74063. if (touch)
  74064. return touch.touchMoveSensibility;
  74065. return 0;
  74066. },
  74067. set: function (value) {
  74068. var touch = this.inputs.attached["touch"];
  74069. if (touch)
  74070. touch.touchMoveSensibility = value;
  74071. },
  74072. enumerable: true,
  74073. configurable: true
  74074. });
  74075. TouchCamera.prototype.getClassName = function () {
  74076. return "TouchCamera";
  74077. };
  74078. /** @hidden */
  74079. TouchCamera.prototype._setupInputs = function () {
  74080. var mouse = this.inputs.attached["mouse"];
  74081. if (mouse) {
  74082. mouse.touchEnabled = false;
  74083. }
  74084. };
  74085. return TouchCamera;
  74086. }(BABYLON.FreeCamera));
  74087. BABYLON.TouchCamera = TouchCamera;
  74088. })(BABYLON || (BABYLON = {}));
  74089. //# sourceMappingURL=babylon.touchCamera.js.map
  74090. var BABYLON;
  74091. (function (BABYLON) {
  74092. var ProceduralTexture = /** @class */ (function (_super) {
  74093. __extends(ProceduralTexture, _super);
  74094. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  74095. if (fallbackTexture === void 0) { fallbackTexture = null; }
  74096. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74097. if (isCube === void 0) { isCube = false; }
  74098. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  74099. _this.isCube = isCube;
  74100. _this.isEnabled = true;
  74101. _this._currentRefreshId = -1;
  74102. _this._refreshRate = 1;
  74103. _this._vertexBuffers = {};
  74104. _this._uniforms = new Array();
  74105. _this._samplers = new Array();
  74106. /** @hidden */
  74107. _this._textures = {};
  74108. _this._floats = {};
  74109. _this._ints = {};
  74110. _this._floatsArrays = {};
  74111. _this._colors3 = {};
  74112. _this._colors4 = {};
  74113. _this._vectors2 = {};
  74114. _this._vectors3 = {};
  74115. _this._matrices = {};
  74116. _this._fallbackTextureUsed = false;
  74117. _this._cachedDefines = "";
  74118. scene = _this.getScene();
  74119. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  74120. if (!component) {
  74121. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  74122. scene._addComponent(component);
  74123. }
  74124. scene.proceduralTextures.push(_this);
  74125. _this._engine = scene.getEngine();
  74126. _this.name = name;
  74127. _this.isRenderTarget = true;
  74128. _this._size = size;
  74129. _this._generateMipMaps = generateMipMaps;
  74130. _this.setFragment(fragment);
  74131. _this._fallbackTexture = fallbackTexture;
  74132. if (isCube) {
  74133. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  74134. _this.setFloat("face", 0);
  74135. }
  74136. else {
  74137. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  74138. }
  74139. // VBO
  74140. var vertices = [];
  74141. vertices.push(1, 1);
  74142. vertices.push(-1, 1);
  74143. vertices.push(-1, -1);
  74144. vertices.push(1, -1);
  74145. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74146. _this._createIndexBuffer();
  74147. return _this;
  74148. }
  74149. ProceduralTexture.prototype._createIndexBuffer = function () {
  74150. var engine = this._engine;
  74151. // Indices
  74152. var indices = [];
  74153. indices.push(0);
  74154. indices.push(1);
  74155. indices.push(2);
  74156. indices.push(0);
  74157. indices.push(2);
  74158. indices.push(3);
  74159. this._indexBuffer = engine.createIndexBuffer(indices);
  74160. };
  74161. /** @hidden */
  74162. ProceduralTexture.prototype._rebuild = function () {
  74163. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74164. if (vb) {
  74165. vb._rebuild();
  74166. }
  74167. this._createIndexBuffer();
  74168. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74169. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74170. }
  74171. };
  74172. ProceduralTexture.prototype.reset = function () {
  74173. if (this._effect === undefined) {
  74174. return;
  74175. }
  74176. var engine = this._engine;
  74177. engine._releaseEffect(this._effect);
  74178. };
  74179. ProceduralTexture.prototype._getDefines = function () {
  74180. return "";
  74181. };
  74182. ProceduralTexture.prototype.isReady = function () {
  74183. var _this = this;
  74184. var engine = this._engine;
  74185. var shaders;
  74186. if (!this._fragment) {
  74187. return false;
  74188. }
  74189. if (this._fallbackTextureUsed) {
  74190. return true;
  74191. }
  74192. var defines = this._getDefines();
  74193. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  74194. return true;
  74195. }
  74196. if (this._fragment.fragmentElement !== undefined) {
  74197. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  74198. }
  74199. else {
  74200. shaders = { vertex: "procedural", fragment: this._fragment };
  74201. }
  74202. this._cachedDefines = defines;
  74203. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  74204. _this.releaseInternalTexture();
  74205. if (_this._fallbackTexture) {
  74206. _this._texture = _this._fallbackTexture._texture;
  74207. if (_this._texture) {
  74208. _this._texture.incrementReferences();
  74209. }
  74210. }
  74211. _this._fallbackTextureUsed = true;
  74212. });
  74213. return this._effect.isReady();
  74214. };
  74215. ProceduralTexture.prototype.resetRefreshCounter = function () {
  74216. this._currentRefreshId = -1;
  74217. };
  74218. ProceduralTexture.prototype.setFragment = function (fragment) {
  74219. this._fragment = fragment;
  74220. };
  74221. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  74222. get: function () {
  74223. return this._refreshRate;
  74224. },
  74225. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74226. set: function (value) {
  74227. this._refreshRate = value;
  74228. this.resetRefreshCounter();
  74229. },
  74230. enumerable: true,
  74231. configurable: true
  74232. });
  74233. /** @hidden */
  74234. ProceduralTexture.prototype._shouldRender = function () {
  74235. if (!this.isEnabled || !this.isReady() || !this._texture) {
  74236. if (this._texture) {
  74237. this._texture.isReady = false;
  74238. }
  74239. return false;
  74240. }
  74241. if (this._fallbackTextureUsed) {
  74242. return false;
  74243. }
  74244. if (this._currentRefreshId === -1) { // At least render once
  74245. this._currentRefreshId = 1;
  74246. return true;
  74247. }
  74248. if (this.refreshRate === this._currentRefreshId) {
  74249. this._currentRefreshId = 1;
  74250. return true;
  74251. }
  74252. this._currentRefreshId++;
  74253. return false;
  74254. };
  74255. ProceduralTexture.prototype.getRenderSize = function () {
  74256. return this._size;
  74257. };
  74258. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  74259. if (this._fallbackTextureUsed) {
  74260. return;
  74261. }
  74262. this.releaseInternalTexture();
  74263. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  74264. // Update properties
  74265. this._size = size;
  74266. this._generateMipMaps = generateMipMaps;
  74267. };
  74268. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  74269. if (this._uniforms.indexOf(uniformName) === -1) {
  74270. this._uniforms.push(uniformName);
  74271. }
  74272. };
  74273. ProceduralTexture.prototype.setTexture = function (name, texture) {
  74274. if (this._samplers.indexOf(name) === -1) {
  74275. this._samplers.push(name);
  74276. }
  74277. this._textures[name] = texture;
  74278. return this;
  74279. };
  74280. ProceduralTexture.prototype.setFloat = function (name, value) {
  74281. this._checkUniform(name);
  74282. this._floats[name] = value;
  74283. return this;
  74284. };
  74285. /**
  74286. * Set the value of an uniform to an integer value
  74287. * @param name defines the name of the uniform
  74288. * @param value defines the value to set
  74289. * @returns the current procedural texture
  74290. */
  74291. ProceduralTexture.prototype.setInt = function (name, value) {
  74292. this._checkUniform(name);
  74293. this._ints[name] = value;
  74294. return this;
  74295. };
  74296. ProceduralTexture.prototype.setFloats = function (name, value) {
  74297. this._checkUniform(name);
  74298. this._floatsArrays[name] = value;
  74299. return this;
  74300. };
  74301. ProceduralTexture.prototype.setColor3 = function (name, value) {
  74302. this._checkUniform(name);
  74303. this._colors3[name] = value;
  74304. return this;
  74305. };
  74306. ProceduralTexture.prototype.setColor4 = function (name, value) {
  74307. this._checkUniform(name);
  74308. this._colors4[name] = value;
  74309. return this;
  74310. };
  74311. ProceduralTexture.prototype.setVector2 = function (name, value) {
  74312. this._checkUniform(name);
  74313. this._vectors2[name] = value;
  74314. return this;
  74315. };
  74316. ProceduralTexture.prototype.setVector3 = function (name, value) {
  74317. this._checkUniform(name);
  74318. this._vectors3[name] = value;
  74319. return this;
  74320. };
  74321. ProceduralTexture.prototype.setMatrix = function (name, value) {
  74322. this._checkUniform(name);
  74323. this._matrices[name] = value;
  74324. return this;
  74325. };
  74326. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74327. var scene = this.getScene();
  74328. if (!scene) {
  74329. return;
  74330. }
  74331. var engine = this._engine;
  74332. // Render
  74333. engine.enableEffect(this._effect);
  74334. engine.setState(false);
  74335. // Texture
  74336. for (var name in this._textures) {
  74337. this._effect.setTexture(name, this._textures[name]);
  74338. }
  74339. // Float
  74340. for (name in this._ints) {
  74341. this._effect.setInt(name, this._ints[name]);
  74342. }
  74343. // Float
  74344. for (name in this._floats) {
  74345. this._effect.setFloat(name, this._floats[name]);
  74346. }
  74347. // Floats
  74348. for (name in this._floatsArrays) {
  74349. this._effect.setArray(name, this._floatsArrays[name]);
  74350. }
  74351. // Color3
  74352. for (name in this._colors3) {
  74353. this._effect.setColor3(name, this._colors3[name]);
  74354. }
  74355. // Color4
  74356. for (name in this._colors4) {
  74357. var color = this._colors4[name];
  74358. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  74359. }
  74360. // Vector2
  74361. for (name in this._vectors2) {
  74362. this._effect.setVector2(name, this._vectors2[name]);
  74363. }
  74364. // Vector3
  74365. for (name in this._vectors3) {
  74366. this._effect.setVector3(name, this._vectors3[name]);
  74367. }
  74368. // Matrix
  74369. for (name in this._matrices) {
  74370. this._effect.setMatrix(name, this._matrices[name]);
  74371. }
  74372. if (!this._texture) {
  74373. return;
  74374. }
  74375. if (this.isCube) {
  74376. for (var face = 0; face < 6; face++) {
  74377. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  74378. // VBOs
  74379. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74380. this._effect.setFloat("face", face);
  74381. // Clear
  74382. engine.clear(scene.clearColor, true, true, true);
  74383. // Draw order
  74384. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74385. // Mipmaps
  74386. if (face === 5) {
  74387. engine.generateMipMapsForCubemap(this._texture);
  74388. }
  74389. }
  74390. }
  74391. else {
  74392. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  74393. // VBOs
  74394. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74395. // Clear
  74396. engine.clear(scene.clearColor, true, true, true);
  74397. // Draw order
  74398. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74399. }
  74400. // Unbind
  74401. engine.unBindFramebuffer(this._texture, this.isCube);
  74402. if (this.onGenerated) {
  74403. this.onGenerated();
  74404. }
  74405. };
  74406. ProceduralTexture.prototype.clone = function () {
  74407. var textureSize = this.getSize();
  74408. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  74409. // Base texture
  74410. newTexture.hasAlpha = this.hasAlpha;
  74411. newTexture.level = this.level;
  74412. // RenderTarget Texture
  74413. newTexture.coordinatesMode = this.coordinatesMode;
  74414. return newTexture;
  74415. };
  74416. ProceduralTexture.prototype.dispose = function () {
  74417. var scene = this.getScene();
  74418. if (!scene) {
  74419. return;
  74420. }
  74421. var index = scene.proceduralTextures.indexOf(this);
  74422. if (index >= 0) {
  74423. scene.proceduralTextures.splice(index, 1);
  74424. }
  74425. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74426. if (vertexBuffer) {
  74427. vertexBuffer.dispose();
  74428. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74429. }
  74430. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  74431. this._indexBuffer = null;
  74432. }
  74433. _super.prototype.dispose.call(this);
  74434. };
  74435. __decorate([
  74436. BABYLON.serialize()
  74437. ], ProceduralTexture.prototype, "_size", void 0);
  74438. __decorate([
  74439. BABYLON.serialize()
  74440. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  74441. __decorate([
  74442. BABYLON.serialize()
  74443. ], ProceduralTexture.prototype, "isEnabled", void 0);
  74444. __decorate([
  74445. BABYLON.serialize()
  74446. ], ProceduralTexture.prototype, "refreshRate", null);
  74447. return ProceduralTexture;
  74448. }(BABYLON.Texture));
  74449. BABYLON.ProceduralTexture = ProceduralTexture;
  74450. })(BABYLON || (BABYLON = {}));
  74451. //# sourceMappingURL=babylon.proceduralTexture.js.map
  74452. var BABYLON;
  74453. (function (BABYLON) {
  74454. /**
  74455. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  74456. * in a given scene.
  74457. */
  74458. var ProceduralTextureSceneComponent = /** @class */ (function () {
  74459. /**
  74460. * Creates a new instance of the component for the given scene
  74461. * @param scene Defines the scene to register the component in
  74462. */
  74463. function ProceduralTextureSceneComponent(scene) {
  74464. /**
  74465. * The component name helpfull to identify the component in the list of scene components.
  74466. */
  74467. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  74468. this.scene = scene;
  74469. this.scene.proceduralTextures = new Array();
  74470. scene.layers = new Array();
  74471. }
  74472. /**
  74473. * Registers the component in a given scene
  74474. */
  74475. ProceduralTextureSceneComponent.prototype.register = function () {
  74476. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  74477. };
  74478. /**
  74479. * Rebuilds the elements related to this component in case of
  74480. * context lost for instance.
  74481. */
  74482. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  74483. // Nothing to do here.
  74484. };
  74485. /**
  74486. * Disposes the component and the associated ressources.
  74487. */
  74488. ProceduralTextureSceneComponent.prototype.dispose = function () {
  74489. // Nothing to do here.
  74490. };
  74491. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  74492. if (this.scene.proceduralTexturesEnabled) {
  74493. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74494. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  74495. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  74496. if (proceduralTexture._shouldRender()) {
  74497. proceduralTexture.render();
  74498. }
  74499. }
  74500. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74501. }
  74502. };
  74503. return ProceduralTextureSceneComponent;
  74504. }());
  74505. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  74506. })(BABYLON || (BABYLON = {}));
  74507. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  74508. var BABYLON;
  74509. (function (BABYLON) {
  74510. var CustomProceduralTexture = /** @class */ (function (_super) {
  74511. __extends(CustomProceduralTexture, _super);
  74512. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  74513. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  74514. _this._animate = true;
  74515. _this._time = 0;
  74516. _this._texturePath = texturePath;
  74517. //Try to load json
  74518. _this.loadJson(texturePath);
  74519. _this.refreshRate = 1;
  74520. return _this;
  74521. }
  74522. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  74523. var _this = this;
  74524. var noConfigFile = function () {
  74525. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  74526. try {
  74527. _this.setFragment(_this._texturePath);
  74528. }
  74529. catch (ex) {
  74530. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  74531. }
  74532. };
  74533. var configFileUrl = jsonUrl + "/config.json";
  74534. var xhr = new XMLHttpRequest();
  74535. xhr.open("GET", configFileUrl, true);
  74536. xhr.addEventListener("load", function () {
  74537. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  74538. try {
  74539. _this._config = JSON.parse(xhr.response);
  74540. _this.updateShaderUniforms();
  74541. _this.updateTextures();
  74542. _this.setFragment(_this._texturePath + "/custom");
  74543. _this._animate = _this._config.animate;
  74544. _this.refreshRate = _this._config.refreshrate;
  74545. }
  74546. catch (ex) {
  74547. noConfigFile();
  74548. }
  74549. }
  74550. else {
  74551. noConfigFile();
  74552. }
  74553. }, false);
  74554. xhr.addEventListener("error", function () {
  74555. noConfigFile();
  74556. }, false);
  74557. try {
  74558. xhr.send();
  74559. }
  74560. catch (ex) {
  74561. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  74562. }
  74563. };
  74564. CustomProceduralTexture.prototype.isReady = function () {
  74565. if (!_super.prototype.isReady.call(this)) {
  74566. return false;
  74567. }
  74568. for (var name in this._textures) {
  74569. var texture = this._textures[name];
  74570. if (!texture.isReady()) {
  74571. return false;
  74572. }
  74573. }
  74574. return true;
  74575. };
  74576. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74577. var scene = this.getScene();
  74578. if (this._animate && scene) {
  74579. this._time += scene.getAnimationRatio() * 0.03;
  74580. this.updateShaderUniforms();
  74581. }
  74582. _super.prototype.render.call(this, useCameraPostProcess);
  74583. };
  74584. CustomProceduralTexture.prototype.updateTextures = function () {
  74585. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  74586. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  74587. }
  74588. };
  74589. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  74590. if (this._config) {
  74591. for (var j = 0; j < this._config.uniforms.length; j++) {
  74592. var uniform = this._config.uniforms[j];
  74593. switch (uniform.type) {
  74594. case "float":
  74595. this.setFloat(uniform.name, uniform.value);
  74596. break;
  74597. case "color3":
  74598. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  74599. break;
  74600. case "color4":
  74601. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  74602. break;
  74603. case "vector2":
  74604. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  74605. break;
  74606. case "vector3":
  74607. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  74608. break;
  74609. }
  74610. }
  74611. }
  74612. this.setFloat("time", this._time);
  74613. };
  74614. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  74615. get: function () {
  74616. return this._animate;
  74617. },
  74618. set: function (value) {
  74619. this._animate = value;
  74620. },
  74621. enumerable: true,
  74622. configurable: true
  74623. });
  74624. return CustomProceduralTexture;
  74625. }(BABYLON.ProceduralTexture));
  74626. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  74627. })(BABYLON || (BABYLON = {}));
  74628. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  74629. var BABYLON;
  74630. (function (BABYLON) {
  74631. var FreeCameraGamepadInput = /** @class */ (function () {
  74632. function FreeCameraGamepadInput() {
  74633. this.gamepadAngularSensibility = 200;
  74634. this.gamepadMoveSensibility = 40;
  74635. // private members
  74636. this._cameraTransform = BABYLON.Matrix.Identity();
  74637. this._deltaTransform = BABYLON.Vector3.Zero();
  74638. this._vector3 = BABYLON.Vector3.Zero();
  74639. this._vector2 = BABYLON.Vector2.Zero();
  74640. }
  74641. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74642. var _this = this;
  74643. var manager = this.camera.getScene().gamepadManager;
  74644. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74645. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74646. // prioritize XBOX gamepads.
  74647. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74648. _this.gamepad = gamepad;
  74649. }
  74650. }
  74651. });
  74652. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74653. if (_this.gamepad === gamepad) {
  74654. _this.gamepad = null;
  74655. }
  74656. });
  74657. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74658. };
  74659. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  74660. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74661. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74662. this.gamepad = null;
  74663. };
  74664. FreeCameraGamepadInput.prototype.checkInputs = function () {
  74665. if (this.gamepad && this.gamepad.leftStick) {
  74666. var camera = this.camera;
  74667. var LSValues = this.gamepad.leftStick;
  74668. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  74669. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74670. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  74671. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  74672. var RSValues = this.gamepad.rightStick;
  74673. if (RSValues) {
  74674. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  74675. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  74676. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  74677. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  74678. }
  74679. else {
  74680. RSValues = { x: 0, y: 0 };
  74681. }
  74682. if (!camera.rotationQuaternion) {
  74683. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  74684. }
  74685. else {
  74686. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  74687. }
  74688. var speed = camera._computeLocalCameraSpeed() * 50.0;
  74689. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  74690. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  74691. camera.cameraDirection.addInPlace(this._deltaTransform);
  74692. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  74693. camera.cameraRotation.addInPlace(this._vector2);
  74694. }
  74695. };
  74696. FreeCameraGamepadInput.prototype.getClassName = function () {
  74697. return "FreeCameraGamepadInput";
  74698. };
  74699. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  74700. return "gamepad";
  74701. };
  74702. __decorate([
  74703. BABYLON.serialize()
  74704. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  74705. __decorate([
  74706. BABYLON.serialize()
  74707. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74708. return FreeCameraGamepadInput;
  74709. }());
  74710. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  74711. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  74712. })(BABYLON || (BABYLON = {}));
  74713. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  74714. var BABYLON;
  74715. (function (BABYLON) {
  74716. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  74717. function ArcRotateCameraGamepadInput() {
  74718. this.gamepadRotationSensibility = 80;
  74719. this.gamepadMoveSensibility = 40;
  74720. }
  74721. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74722. var _this = this;
  74723. var manager = this.camera.getScene().gamepadManager;
  74724. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74725. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74726. // prioritize XBOX gamepads.
  74727. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74728. _this.gamepad = gamepad;
  74729. }
  74730. }
  74731. });
  74732. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74733. if (_this.gamepad === gamepad) {
  74734. _this.gamepad = null;
  74735. }
  74736. });
  74737. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74738. };
  74739. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  74740. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74741. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74742. this.gamepad = null;
  74743. };
  74744. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  74745. if (this.gamepad) {
  74746. var camera = this.camera;
  74747. var RSValues = this.gamepad.rightStick;
  74748. if (RSValues) {
  74749. if (RSValues.x != 0) {
  74750. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  74751. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  74752. camera.inertialAlphaOffset += normalizedRX;
  74753. }
  74754. }
  74755. if (RSValues.y != 0) {
  74756. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  74757. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  74758. camera.inertialBetaOffset += normalizedRY;
  74759. }
  74760. }
  74761. }
  74762. var LSValues = this.gamepad.leftStick;
  74763. if (LSValues && LSValues.y != 0) {
  74764. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74765. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  74766. this.camera.inertialRadiusOffset -= normalizedLY;
  74767. }
  74768. }
  74769. }
  74770. };
  74771. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  74772. return "ArcRotateCameraGamepadInput";
  74773. };
  74774. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  74775. return "gamepad";
  74776. };
  74777. __decorate([
  74778. BABYLON.serialize()
  74779. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  74780. __decorate([
  74781. BABYLON.serialize()
  74782. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74783. return ArcRotateCameraGamepadInput;
  74784. }());
  74785. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  74786. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  74787. })(BABYLON || (BABYLON = {}));
  74788. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  74789. var BABYLON;
  74790. (function (BABYLON) {
  74791. var GamepadManager = /** @class */ (function () {
  74792. function GamepadManager(_scene) {
  74793. var _this = this;
  74794. this._scene = _scene;
  74795. this._babylonGamepads = [];
  74796. this._oneGamepadConnected = false;
  74797. /** @hidden */
  74798. this._isMonitoring = false;
  74799. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  74800. if (!BABYLON.Tools.IsWindowObjectExist()) {
  74801. this._gamepadEventSupported = false;
  74802. }
  74803. else {
  74804. this._gamepadEventSupported = 'GamepadEvent' in window;
  74805. this._gamepadSupport = (navigator.getGamepads ||
  74806. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  74807. }
  74808. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  74809. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  74810. for (var i in _this._babylonGamepads) {
  74811. var gamepad = _this._babylonGamepads[i];
  74812. if (gamepad && gamepad._isConnected) {
  74813. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  74814. }
  74815. }
  74816. });
  74817. this._onGamepadConnectedEvent = function (evt) {
  74818. var gamepad = evt.gamepad;
  74819. if (gamepad.index in _this._babylonGamepads) {
  74820. if (_this._babylonGamepads[gamepad.index].isConnected) {
  74821. return;
  74822. }
  74823. }
  74824. var newGamepad;
  74825. if (_this._babylonGamepads[gamepad.index]) {
  74826. newGamepad = _this._babylonGamepads[gamepad.index];
  74827. newGamepad.browserGamepad = gamepad;
  74828. newGamepad._isConnected = true;
  74829. }
  74830. else {
  74831. newGamepad = _this._addNewGamepad(gamepad);
  74832. }
  74833. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74834. _this._startMonitoringGamepads();
  74835. };
  74836. this._onGamepadDisconnectedEvent = function (evt) {
  74837. var gamepad = evt.gamepad;
  74838. // Remove the gamepad from the list of gamepads to monitor.
  74839. for (var i in _this._babylonGamepads) {
  74840. if (_this._babylonGamepads[i].index === gamepad.index) {
  74841. var disconnectedGamepad = _this._babylonGamepads[i];
  74842. disconnectedGamepad._isConnected = false;
  74843. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  74844. break;
  74845. }
  74846. }
  74847. };
  74848. if (this._gamepadSupport) {
  74849. //first add already-connected gamepads
  74850. this._updateGamepadObjects();
  74851. if (this._babylonGamepads.length) {
  74852. this._startMonitoringGamepads();
  74853. }
  74854. // Checking if the gamepad connected event is supported (like in Firefox)
  74855. if (this._gamepadEventSupported) {
  74856. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  74857. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  74858. }
  74859. else {
  74860. this._startMonitoringGamepads();
  74861. }
  74862. }
  74863. }
  74864. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  74865. get: function () {
  74866. return this._babylonGamepads;
  74867. },
  74868. enumerable: true,
  74869. configurable: true
  74870. });
  74871. GamepadManager.prototype.getGamepadByType = function (type) {
  74872. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  74873. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  74874. var gamepad = _a[_i];
  74875. if (gamepad && gamepad.type === type) {
  74876. return gamepad;
  74877. }
  74878. }
  74879. return null;
  74880. };
  74881. GamepadManager.prototype.dispose = function () {
  74882. if (this._gamepadEventSupported) {
  74883. if (this._onGamepadConnectedEvent) {
  74884. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  74885. }
  74886. if (this._onGamepadDisconnectedEvent) {
  74887. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  74888. }
  74889. this._onGamepadConnectedEvent = null;
  74890. this._onGamepadDisconnectedEvent = null;
  74891. }
  74892. this._babylonGamepads.forEach(function (gamepad) {
  74893. gamepad.dispose();
  74894. });
  74895. this.onGamepadConnectedObservable.clear();
  74896. this.onGamepadDisconnectedObservable.clear();
  74897. this._oneGamepadConnected = false;
  74898. this._stopMonitoringGamepads();
  74899. this._babylonGamepads = [];
  74900. };
  74901. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  74902. if (!this._oneGamepadConnected) {
  74903. this._oneGamepadConnected = true;
  74904. }
  74905. var newGamepad;
  74906. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  74907. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  74908. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  74909. }
  74910. // if pose is supported, use the (WebVR) pose enabled controller
  74911. else if (gamepad.pose) {
  74912. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  74913. }
  74914. else {
  74915. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  74916. }
  74917. this._babylonGamepads[newGamepad.index] = newGamepad;
  74918. return newGamepad;
  74919. };
  74920. GamepadManager.prototype._startMonitoringGamepads = function () {
  74921. if (!this._isMonitoring) {
  74922. this._isMonitoring = true;
  74923. //back-comp
  74924. if (!this._scene) {
  74925. this._checkGamepadsStatus();
  74926. }
  74927. }
  74928. };
  74929. GamepadManager.prototype._stopMonitoringGamepads = function () {
  74930. this._isMonitoring = false;
  74931. };
  74932. /** @hidden */
  74933. GamepadManager.prototype._checkGamepadsStatus = function () {
  74934. var _this = this;
  74935. // Hack to be compatible Chrome
  74936. this._updateGamepadObjects();
  74937. for (var i in this._babylonGamepads) {
  74938. var gamepad = this._babylonGamepads[i];
  74939. if (!gamepad || !gamepad.isConnected) {
  74940. continue;
  74941. }
  74942. gamepad.update();
  74943. }
  74944. if (this._isMonitoring && !this._scene) {
  74945. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  74946. }
  74947. };
  74948. // This function is called only on Chrome, which does not properly support
  74949. // connection/disconnection events and forces you to recopy again the gamepad object
  74950. GamepadManager.prototype._updateGamepadObjects = function () {
  74951. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  74952. for (var i = 0; i < gamepads.length; i++) {
  74953. var gamepad = gamepads[i];
  74954. if (gamepad) {
  74955. if (!this._babylonGamepads[gamepad.index]) {
  74956. var newGamepad = this._addNewGamepad(gamepad);
  74957. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74958. }
  74959. else {
  74960. // Forced to copy again this object for Chrome for unknown reason
  74961. this._babylonGamepads[i].browserGamepad = gamepad;
  74962. if (!this._babylonGamepads[i].isConnected) {
  74963. this._babylonGamepads[i]._isConnected = true;
  74964. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  74965. }
  74966. }
  74967. }
  74968. }
  74969. };
  74970. return GamepadManager;
  74971. }());
  74972. BABYLON.GamepadManager = GamepadManager;
  74973. })(BABYLON || (BABYLON = {}));
  74974. //# sourceMappingURL=babylon.gamepadManager.js.map
  74975. var BABYLON;
  74976. (function (BABYLON) {
  74977. var StickValues = /** @class */ (function () {
  74978. function StickValues(x, y) {
  74979. this.x = x;
  74980. this.y = y;
  74981. }
  74982. return StickValues;
  74983. }());
  74984. BABYLON.StickValues = StickValues;
  74985. var Gamepad = /** @class */ (function () {
  74986. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  74987. if (leftStickX === void 0) { leftStickX = 0; }
  74988. if (leftStickY === void 0) { leftStickY = 1; }
  74989. if (rightStickX === void 0) { rightStickX = 2; }
  74990. if (rightStickY === void 0) { rightStickY = 3; }
  74991. this.id = id;
  74992. this.index = index;
  74993. this.browserGamepad = browserGamepad;
  74994. this._leftStick = { x: 0, y: 0 };
  74995. this._rightStick = { x: 0, y: 0 };
  74996. /** @hidden */
  74997. this._isConnected = true;
  74998. this._invertLeftStickY = false;
  74999. this.type = Gamepad.GAMEPAD;
  75000. this._leftStickAxisX = leftStickX;
  75001. this._leftStickAxisY = leftStickY;
  75002. this._rightStickAxisX = rightStickX;
  75003. this._rightStickAxisY = rightStickY;
  75004. if (this.browserGamepad.axes.length >= 2) {
  75005. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75006. }
  75007. if (this.browserGamepad.axes.length >= 4) {
  75008. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75009. }
  75010. }
  75011. Object.defineProperty(Gamepad.prototype, "isConnected", {
  75012. get: function () {
  75013. return this._isConnected;
  75014. },
  75015. enumerable: true,
  75016. configurable: true
  75017. });
  75018. Gamepad.prototype.onleftstickchanged = function (callback) {
  75019. this._onleftstickchanged = callback;
  75020. };
  75021. Gamepad.prototype.onrightstickchanged = function (callback) {
  75022. this._onrightstickchanged = callback;
  75023. };
  75024. Object.defineProperty(Gamepad.prototype, "leftStick", {
  75025. get: function () {
  75026. return this._leftStick;
  75027. },
  75028. set: function (newValues) {
  75029. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  75030. this._onleftstickchanged(newValues);
  75031. }
  75032. this._leftStick = newValues;
  75033. },
  75034. enumerable: true,
  75035. configurable: true
  75036. });
  75037. Object.defineProperty(Gamepad.prototype, "rightStick", {
  75038. get: function () {
  75039. return this._rightStick;
  75040. },
  75041. set: function (newValues) {
  75042. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  75043. this._onrightstickchanged(newValues);
  75044. }
  75045. this._rightStick = newValues;
  75046. },
  75047. enumerable: true,
  75048. configurable: true
  75049. });
  75050. Gamepad.prototype.update = function () {
  75051. if (this._leftStick) {
  75052. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75053. if (this._invertLeftStickY) {
  75054. this.leftStick.y *= -1;
  75055. }
  75056. }
  75057. if (this._rightStick) {
  75058. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75059. }
  75060. };
  75061. Gamepad.prototype.dispose = function () {
  75062. };
  75063. Gamepad.GAMEPAD = 0;
  75064. Gamepad.GENERIC = 1;
  75065. Gamepad.XBOX = 2;
  75066. Gamepad.POSE_ENABLED = 3;
  75067. return Gamepad;
  75068. }());
  75069. BABYLON.Gamepad = Gamepad;
  75070. var GenericPad = /** @class */ (function (_super) {
  75071. __extends(GenericPad, _super);
  75072. function GenericPad(id, index, browserGamepad) {
  75073. var _this = _super.call(this, id, index, browserGamepad) || this;
  75074. _this.onButtonDownObservable = new BABYLON.Observable();
  75075. _this.onButtonUpObservable = new BABYLON.Observable();
  75076. _this.type = Gamepad.GENERIC;
  75077. _this._buttons = new Array(browserGamepad.buttons.length);
  75078. return _this;
  75079. }
  75080. GenericPad.prototype.onbuttondown = function (callback) {
  75081. this._onbuttondown = callback;
  75082. };
  75083. GenericPad.prototype.onbuttonup = function (callback) {
  75084. this._onbuttonup = callback;
  75085. };
  75086. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  75087. if (newValue !== currentValue) {
  75088. if (newValue === 1) {
  75089. if (this._onbuttondown) {
  75090. this._onbuttondown(buttonIndex);
  75091. }
  75092. this.onButtonDownObservable.notifyObservers(buttonIndex);
  75093. }
  75094. if (newValue === 0) {
  75095. if (this._onbuttonup) {
  75096. this._onbuttonup(buttonIndex);
  75097. }
  75098. this.onButtonUpObservable.notifyObservers(buttonIndex);
  75099. }
  75100. }
  75101. return newValue;
  75102. };
  75103. GenericPad.prototype.update = function () {
  75104. _super.prototype.update.call(this);
  75105. for (var index = 0; index < this._buttons.length; index++) {
  75106. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  75107. }
  75108. };
  75109. GenericPad.prototype.dispose = function () {
  75110. _super.prototype.dispose.call(this);
  75111. this.onButtonDownObservable.clear();
  75112. this.onButtonUpObservable.clear();
  75113. };
  75114. return GenericPad;
  75115. }(Gamepad));
  75116. BABYLON.GenericPad = GenericPad;
  75117. })(BABYLON || (BABYLON = {}));
  75118. //# sourceMappingURL=babylon.gamepad.js.map
  75119. var BABYLON;
  75120. (function (BABYLON) {
  75121. /**
  75122. * Defines supported buttons for XBox360 compatible gamepads
  75123. */
  75124. var Xbox360Button;
  75125. (function (Xbox360Button) {
  75126. /** A */
  75127. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  75128. /** B */
  75129. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  75130. /** X */
  75131. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  75132. /** Y */
  75133. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  75134. /** Start */
  75135. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  75136. /** Back */
  75137. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  75138. /** Left button */
  75139. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  75140. /** Right button */
  75141. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  75142. /** Left stick */
  75143. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  75144. /** Right stick */
  75145. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  75146. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  75147. /** Defines values for XBox360 DPad */
  75148. var Xbox360Dpad;
  75149. (function (Xbox360Dpad) {
  75150. /** Up */
  75151. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  75152. /** Down */
  75153. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  75154. /** Left */
  75155. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  75156. /** Right */
  75157. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  75158. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  75159. /**
  75160. * Defines a XBox360 gamepad
  75161. */
  75162. var Xbox360Pad = /** @class */ (function (_super) {
  75163. __extends(Xbox360Pad, _super);
  75164. /**
  75165. * Creates a new XBox360 gamepad object
  75166. * @param id defines the id of this gamepad
  75167. * @param index defines its index
  75168. * @param gamepad defines the internal HTML gamepad object
  75169. * @param xboxOne defines if it is a XBox One gamepad
  75170. */
  75171. function Xbox360Pad(id, index, gamepad, xboxOne) {
  75172. if (xboxOne === void 0) { xboxOne = false; }
  75173. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  75174. _this._leftTrigger = 0;
  75175. _this._rightTrigger = 0;
  75176. /** Observable raised when a button is pressed */
  75177. _this.onButtonDownObservable = new BABYLON.Observable();
  75178. /** Observable raised when a button is released */
  75179. _this.onButtonUpObservable = new BABYLON.Observable();
  75180. /** Observable raised when a pad is pressed */
  75181. _this.onPadDownObservable = new BABYLON.Observable();
  75182. /** Observable raised when a pad is released */
  75183. _this.onPadUpObservable = new BABYLON.Observable();
  75184. _this._buttonA = 0;
  75185. _this._buttonB = 0;
  75186. _this._buttonX = 0;
  75187. _this._buttonY = 0;
  75188. _this._buttonBack = 0;
  75189. _this._buttonStart = 0;
  75190. _this._buttonLB = 0;
  75191. _this._buttonRB = 0;
  75192. _this._buttonLeftStick = 0;
  75193. _this._buttonRightStick = 0;
  75194. _this._dPadUp = 0;
  75195. _this._dPadDown = 0;
  75196. _this._dPadLeft = 0;
  75197. _this._dPadRight = 0;
  75198. _this._isXboxOnePad = false;
  75199. _this.type = BABYLON.Gamepad.XBOX;
  75200. _this._isXboxOnePad = xboxOne;
  75201. return _this;
  75202. }
  75203. /**
  75204. * Defines the callback to call when left trigger is pressed
  75205. * @param callback defines the callback to use
  75206. */
  75207. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  75208. this._onlefttriggerchanged = callback;
  75209. };
  75210. /**
  75211. * Defines the callback to call when right trigger is pressed
  75212. * @param callback defines the callback to use
  75213. */
  75214. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  75215. this._onrighttriggerchanged = callback;
  75216. };
  75217. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  75218. /**
  75219. * Gets or sets left trigger value
  75220. */
  75221. get: function () {
  75222. return this._leftTrigger;
  75223. },
  75224. set: function (newValue) {
  75225. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  75226. this._onlefttriggerchanged(newValue);
  75227. }
  75228. this._leftTrigger = newValue;
  75229. },
  75230. enumerable: true,
  75231. configurable: true
  75232. });
  75233. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  75234. /**
  75235. * Gets or sets right trigger value
  75236. */
  75237. get: function () {
  75238. return this._rightTrigger;
  75239. },
  75240. set: function (newValue) {
  75241. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  75242. this._onrighttriggerchanged(newValue);
  75243. }
  75244. this._rightTrigger = newValue;
  75245. },
  75246. enumerable: true,
  75247. configurable: true
  75248. });
  75249. /**
  75250. * Defines the callback to call when a button is pressed
  75251. * @param callback defines the callback to use
  75252. */
  75253. Xbox360Pad.prototype.onbuttondown = function (callback) {
  75254. this._onbuttondown = callback;
  75255. };
  75256. /**
  75257. * Defines the callback to call when a button is released
  75258. * @param callback defines the callback to use
  75259. */
  75260. Xbox360Pad.prototype.onbuttonup = function (callback) {
  75261. this._onbuttonup = callback;
  75262. };
  75263. /**
  75264. * Defines the callback to call when a pad is pressed
  75265. * @param callback defines the callback to use
  75266. */
  75267. Xbox360Pad.prototype.ondpaddown = function (callback) {
  75268. this._ondpaddown = callback;
  75269. };
  75270. /**
  75271. * Defines the callback to call when a pad is released
  75272. * @param callback defines the callback to use
  75273. */
  75274. Xbox360Pad.prototype.ondpadup = function (callback) {
  75275. this._ondpadup = callback;
  75276. };
  75277. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  75278. if (newValue !== currentValue) {
  75279. if (newValue === 1) {
  75280. if (this._onbuttondown) {
  75281. this._onbuttondown(buttonType);
  75282. }
  75283. this.onButtonDownObservable.notifyObservers(buttonType);
  75284. }
  75285. if (newValue === 0) {
  75286. if (this._onbuttonup) {
  75287. this._onbuttonup(buttonType);
  75288. }
  75289. this.onButtonUpObservable.notifyObservers(buttonType);
  75290. }
  75291. }
  75292. return newValue;
  75293. };
  75294. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  75295. if (newValue !== currentValue) {
  75296. if (newValue === 1) {
  75297. if (this._ondpaddown) {
  75298. this._ondpaddown(buttonType);
  75299. }
  75300. this.onPadDownObservable.notifyObservers(buttonType);
  75301. }
  75302. if (newValue === 0) {
  75303. if (this._ondpadup) {
  75304. this._ondpadup(buttonType);
  75305. }
  75306. this.onPadUpObservable.notifyObservers(buttonType);
  75307. }
  75308. }
  75309. return newValue;
  75310. };
  75311. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  75312. /** Gets or sets value of A button */
  75313. get: function () {
  75314. return this._buttonA;
  75315. },
  75316. set: function (value) {
  75317. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  75318. },
  75319. enumerable: true,
  75320. configurable: true
  75321. });
  75322. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  75323. /** Gets or sets value of B button */
  75324. get: function () {
  75325. return this._buttonB;
  75326. },
  75327. set: function (value) {
  75328. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  75329. },
  75330. enumerable: true,
  75331. configurable: true
  75332. });
  75333. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  75334. /** Gets or sets value of X button */
  75335. get: function () {
  75336. return this._buttonX;
  75337. },
  75338. set: function (value) {
  75339. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  75340. },
  75341. enumerable: true,
  75342. configurable: true
  75343. });
  75344. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  75345. /** Gets or sets value of Y button */
  75346. get: function () {
  75347. return this._buttonY;
  75348. },
  75349. set: function (value) {
  75350. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  75351. },
  75352. enumerable: true,
  75353. configurable: true
  75354. });
  75355. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  75356. /** Gets or sets value of Start button */
  75357. get: function () {
  75358. return this._buttonStart;
  75359. },
  75360. set: function (value) {
  75361. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  75362. },
  75363. enumerable: true,
  75364. configurable: true
  75365. });
  75366. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  75367. /** Gets or sets value of Back button */
  75368. get: function () {
  75369. return this._buttonBack;
  75370. },
  75371. set: function (value) {
  75372. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  75373. },
  75374. enumerable: true,
  75375. configurable: true
  75376. });
  75377. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  75378. /** Gets or sets value of Left button */
  75379. get: function () {
  75380. return this._buttonLB;
  75381. },
  75382. set: function (value) {
  75383. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  75384. },
  75385. enumerable: true,
  75386. configurable: true
  75387. });
  75388. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  75389. /** Gets or sets value of Right button */
  75390. get: function () {
  75391. return this._buttonRB;
  75392. },
  75393. set: function (value) {
  75394. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  75395. },
  75396. enumerable: true,
  75397. configurable: true
  75398. });
  75399. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  75400. /** Gets or sets value of left stick */
  75401. get: function () {
  75402. return this._buttonLeftStick;
  75403. },
  75404. set: function (value) {
  75405. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  75406. },
  75407. enumerable: true,
  75408. configurable: true
  75409. });
  75410. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  75411. /** Gets or sets value of right stick */
  75412. get: function () {
  75413. return this._buttonRightStick;
  75414. },
  75415. set: function (value) {
  75416. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  75417. },
  75418. enumerable: true,
  75419. configurable: true
  75420. });
  75421. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  75422. /** Gets or sets value of DPad up */
  75423. get: function () {
  75424. return this._dPadUp;
  75425. },
  75426. set: function (value) {
  75427. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  75428. },
  75429. enumerable: true,
  75430. configurable: true
  75431. });
  75432. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  75433. /** Gets or sets value of DPad down */
  75434. get: function () {
  75435. return this._dPadDown;
  75436. },
  75437. set: function (value) {
  75438. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  75439. },
  75440. enumerable: true,
  75441. configurable: true
  75442. });
  75443. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  75444. /** Gets or sets value of DPad left */
  75445. get: function () {
  75446. return this._dPadLeft;
  75447. },
  75448. set: function (value) {
  75449. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  75450. },
  75451. enumerable: true,
  75452. configurable: true
  75453. });
  75454. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  75455. /** Gets or sets value of DPad right */
  75456. get: function () {
  75457. return this._dPadRight;
  75458. },
  75459. set: function (value) {
  75460. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  75461. },
  75462. enumerable: true,
  75463. configurable: true
  75464. });
  75465. /**
  75466. * Force the gamepad to synchronize with device values
  75467. */
  75468. Xbox360Pad.prototype.update = function () {
  75469. _super.prototype.update.call(this);
  75470. if (this._isXboxOnePad) {
  75471. this.buttonA = this.browserGamepad.buttons[0].value;
  75472. this.buttonB = this.browserGamepad.buttons[1].value;
  75473. this.buttonX = this.browserGamepad.buttons[2].value;
  75474. this.buttonY = this.browserGamepad.buttons[3].value;
  75475. this.buttonLB = this.browserGamepad.buttons[4].value;
  75476. this.buttonRB = this.browserGamepad.buttons[5].value;
  75477. this.leftTrigger = this.browserGamepad.axes[2];
  75478. this.rightTrigger = this.browserGamepad.axes[5];
  75479. this.buttonBack = this.browserGamepad.buttons[9].value;
  75480. this.buttonStart = this.browserGamepad.buttons[8].value;
  75481. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  75482. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  75483. this.dPadUp = this.browserGamepad.buttons[11].value;
  75484. this.dPadDown = this.browserGamepad.buttons[12].value;
  75485. this.dPadLeft = this.browserGamepad.buttons[13].value;
  75486. this.dPadRight = this.browserGamepad.buttons[14].value;
  75487. }
  75488. else {
  75489. this.buttonA = this.browserGamepad.buttons[0].value;
  75490. this.buttonB = this.browserGamepad.buttons[1].value;
  75491. this.buttonX = this.browserGamepad.buttons[2].value;
  75492. this.buttonY = this.browserGamepad.buttons[3].value;
  75493. this.buttonLB = this.browserGamepad.buttons[4].value;
  75494. this.buttonRB = this.browserGamepad.buttons[5].value;
  75495. this.leftTrigger = this.browserGamepad.buttons[6].value;
  75496. this.rightTrigger = this.browserGamepad.buttons[7].value;
  75497. this.buttonBack = this.browserGamepad.buttons[8].value;
  75498. this.buttonStart = this.browserGamepad.buttons[9].value;
  75499. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  75500. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  75501. this.dPadUp = this.browserGamepad.buttons[12].value;
  75502. this.dPadDown = this.browserGamepad.buttons[13].value;
  75503. this.dPadLeft = this.browserGamepad.buttons[14].value;
  75504. this.dPadRight = this.browserGamepad.buttons[15].value;
  75505. }
  75506. };
  75507. Xbox360Pad.prototype.dispose = function () {
  75508. _super.prototype.dispose.call(this);
  75509. this.onButtonDownObservable.clear();
  75510. this.onButtonUpObservable.clear();
  75511. this.onPadDownObservable.clear();
  75512. this.onPadUpObservable.clear();
  75513. };
  75514. return Xbox360Pad;
  75515. }(BABYLON.Gamepad));
  75516. BABYLON.Xbox360Pad = Xbox360Pad;
  75517. })(BABYLON || (BABYLON = {}));
  75518. //# sourceMappingURL=babylon.xboxGamepad.js.map
  75519. var BABYLON;
  75520. (function (BABYLON) {
  75521. /**
  75522. * Defines the types of pose enabled controllers that are supported
  75523. */
  75524. var PoseEnabledControllerType;
  75525. (function (PoseEnabledControllerType) {
  75526. /**
  75527. * HTC Vive
  75528. */
  75529. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  75530. /**
  75531. * Oculus Rift
  75532. */
  75533. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  75534. /**
  75535. * Windows mixed reality
  75536. */
  75537. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  75538. /**
  75539. * Samsung gear VR
  75540. */
  75541. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  75542. /**
  75543. * Google Daydream
  75544. */
  75545. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  75546. /**
  75547. * Generic
  75548. */
  75549. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  75550. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  75551. /**
  75552. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75553. */
  75554. var PoseEnabledControllerHelper = /** @class */ (function () {
  75555. function PoseEnabledControllerHelper() {
  75556. }
  75557. /**
  75558. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75559. * @param vrGamepad the gamepad to initialized
  75560. * @returns a vr controller of the type the gamepad identified as
  75561. */
  75562. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  75563. // Oculus Touch
  75564. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  75565. return new BABYLON.OculusTouchController(vrGamepad);
  75566. }
  75567. // Windows Mixed Reality controllers
  75568. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  75569. return new BABYLON.WindowsMotionController(vrGamepad);
  75570. }
  75571. // HTC Vive
  75572. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  75573. return new BABYLON.ViveController(vrGamepad);
  75574. }
  75575. // Samsung/Oculus Gear VR or Oculus Go
  75576. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  75577. return new BABYLON.GearVRController(vrGamepad);
  75578. }
  75579. // Google Daydream
  75580. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  75581. return new BABYLON.DaydreamController(vrGamepad);
  75582. }
  75583. // Generic
  75584. else {
  75585. return new BABYLON.GenericController(vrGamepad);
  75586. }
  75587. };
  75588. return PoseEnabledControllerHelper;
  75589. }());
  75590. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  75591. /**
  75592. * Defines the PoseEnabledController object that contains state of a vr capable controller
  75593. */
  75594. var PoseEnabledController = /** @class */ (function (_super) {
  75595. __extends(PoseEnabledController, _super);
  75596. /**
  75597. * Creates a new PoseEnabledController from a gamepad
  75598. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  75599. */
  75600. function PoseEnabledController(browserGamepad) {
  75601. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  75602. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75603. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75604. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  75605. /**
  75606. * The device position in babylon space
  75607. */
  75608. _this.devicePosition = BABYLON.Vector3.Zero();
  75609. /**
  75610. * The device rotation in babylon space
  75611. */
  75612. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  75613. /**
  75614. * The scale factor of the device in babylon space
  75615. */
  75616. _this.deviceScaleFactor = 1;
  75617. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  75618. /**
  75619. * Internal, matrix used to convert room space to babylon space
  75620. * @hidden
  75621. */
  75622. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75623. /**
  75624. * Node to be used when casting a ray from the controller
  75625. * @hidden
  75626. */
  75627. _this._pointingPoseNode = null;
  75628. _this._workingMatrix = BABYLON.Matrix.Identity();
  75629. /**
  75630. * @hidden
  75631. */
  75632. _this._meshAttachedObservable = new BABYLON.Observable();
  75633. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  75634. _this.controllerType = PoseEnabledControllerType.GENERIC;
  75635. _this.position = BABYLON.Vector3.Zero();
  75636. _this.rotationQuaternion = new BABYLON.Quaternion();
  75637. _this._calculatedPosition = BABYLON.Vector3.Zero();
  75638. _this._calculatedRotation = new BABYLON.Quaternion();
  75639. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  75640. return _this;
  75641. }
  75642. /**
  75643. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  75644. */
  75645. PoseEnabledController.prototype.update = function () {
  75646. _super.prototype.update.call(this);
  75647. this._updatePoseAndMesh();
  75648. };
  75649. /**
  75650. * Updates only the pose device and mesh without doing any button event checking
  75651. */
  75652. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  75653. var pose = this.browserGamepad.pose;
  75654. this.updateFromDevice(pose);
  75655. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  75656. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  75657. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75658. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  75659. if (this._mesh) {
  75660. this._mesh.position.copyFrom(this.devicePosition);
  75661. if (this._mesh.rotationQuaternion) {
  75662. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  75663. }
  75664. }
  75665. };
  75666. /**
  75667. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75668. * @param poseData raw pose fromthe device
  75669. */
  75670. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  75671. if (poseData) {
  75672. this.rawPose = poseData;
  75673. if (poseData.position) {
  75674. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  75675. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  75676. this._deviceRoomPosition.z *= -1;
  75677. }
  75678. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  75679. this._calculatedPosition.addInPlace(this.position);
  75680. }
  75681. var pose = this.rawPose;
  75682. if (poseData.orientation && pose.orientation) {
  75683. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  75684. if (this._mesh) {
  75685. if (this._mesh.getScene().useRightHandedSystem) {
  75686. this._deviceRoomRotationQuaternion.z *= -1;
  75687. this._deviceRoomRotationQuaternion.w *= -1;
  75688. }
  75689. else {
  75690. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  75691. }
  75692. }
  75693. // if the camera is set, rotate to the camera's rotation
  75694. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  75695. }
  75696. }
  75697. };
  75698. /**
  75699. * Attaches a mesh to the controller
  75700. * @param mesh the mesh to be attached
  75701. */
  75702. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  75703. if (this._mesh) {
  75704. this._mesh.parent = null;
  75705. }
  75706. this._mesh = mesh;
  75707. if (this._poseControlledCamera) {
  75708. this._mesh.parent = this._poseControlledCamera;
  75709. }
  75710. if (!this._mesh.rotationQuaternion) {
  75711. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  75712. }
  75713. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  75714. this._updatePoseAndMesh();
  75715. if (this._pointingPoseNode) {
  75716. var parents = [];
  75717. var obj = this._pointingPoseNode;
  75718. while (obj.parent) {
  75719. parents.push(obj.parent);
  75720. obj = obj.parent;
  75721. }
  75722. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  75723. }
  75724. this._meshAttachedObservable.notifyObservers(mesh);
  75725. };
  75726. /**
  75727. * Attaches the controllers mesh to a camera
  75728. * @param camera the camera the mesh should be attached to
  75729. */
  75730. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  75731. this._poseControlledCamera = camera;
  75732. if (this._mesh) {
  75733. this._mesh.parent = this._poseControlledCamera;
  75734. }
  75735. };
  75736. /**
  75737. * Disposes of the controller
  75738. */
  75739. PoseEnabledController.prototype.dispose = function () {
  75740. if (this._mesh) {
  75741. this._mesh.dispose();
  75742. }
  75743. this._mesh = null;
  75744. _super.prototype.dispose.call(this);
  75745. };
  75746. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  75747. /**
  75748. * The mesh that is attached to the controller
  75749. */
  75750. get: function () {
  75751. return this._mesh;
  75752. },
  75753. enumerable: true,
  75754. configurable: true
  75755. });
  75756. /**
  75757. * Gets the ray of the controller in the direction the controller is pointing
  75758. * @param length the length the resulting ray should be
  75759. * @returns a ray in the direction the controller is pointing
  75760. */
  75761. PoseEnabledController.prototype.getForwardRay = function (length) {
  75762. if (length === void 0) { length = 100; }
  75763. if (!this.mesh) {
  75764. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  75765. }
  75766. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  75767. var origin = m.getTranslation();
  75768. var forward = new BABYLON.Vector3(0, 0, -1);
  75769. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75770. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75771. return new BABYLON.Ray(origin, direction, length);
  75772. };
  75773. /**
  75774. * Name of the child mesh that can be used to cast a ray from the controller
  75775. */
  75776. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  75777. return PoseEnabledController;
  75778. }(BABYLON.Gamepad));
  75779. BABYLON.PoseEnabledController = PoseEnabledController;
  75780. })(BABYLON || (BABYLON = {}));
  75781. //# sourceMappingURL=babylon.poseEnabledController.js.map
  75782. var BABYLON;
  75783. (function (BABYLON) {
  75784. /**
  75785. * Defines the WebVRController object that represents controllers tracked in 3D space
  75786. */
  75787. var WebVRController = /** @class */ (function (_super) {
  75788. __extends(WebVRController, _super);
  75789. /**
  75790. * Creates a new WebVRController from a gamepad
  75791. * @param vrGamepad the gamepad that the WebVRController should be created from
  75792. */
  75793. function WebVRController(vrGamepad) {
  75794. var _this = _super.call(this, vrGamepad) || this;
  75795. // Observables
  75796. /**
  75797. * Fired when the trigger state has changed
  75798. */
  75799. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  75800. /**
  75801. * Fired when the main button state has changed
  75802. */
  75803. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  75804. /**
  75805. * Fired when the secondary button state has changed
  75806. */
  75807. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  75808. /**
  75809. * Fired when the pad state has changed
  75810. */
  75811. _this.onPadStateChangedObservable = new BABYLON.Observable();
  75812. /**
  75813. * Fired when controllers stick values have changed
  75814. */
  75815. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  75816. /**
  75817. * X and Y axis corrisponding to the controllers joystick
  75818. */
  75819. _this.pad = { x: 0, y: 0 };
  75820. // avoid GC, store state in a tmp object
  75821. _this._changes = {
  75822. pressChanged: false,
  75823. touchChanged: false,
  75824. valueChanged: false,
  75825. changed: false
  75826. };
  75827. _this._buttons = new Array(vrGamepad.buttons.length);
  75828. _this.hand = vrGamepad.hand;
  75829. return _this;
  75830. }
  75831. /**
  75832. * Fired when a controller button's state has changed
  75833. * @param callback the callback containing the button that was modified
  75834. */
  75835. WebVRController.prototype.onButtonStateChange = function (callback) {
  75836. this._onButtonStateChange = callback;
  75837. };
  75838. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  75839. /**
  75840. * The default controller model for the controller
  75841. */
  75842. get: function () {
  75843. return this._defaultModel;
  75844. },
  75845. enumerable: true,
  75846. configurable: true
  75847. });
  75848. /**
  75849. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  75850. */
  75851. WebVRController.prototype.update = function () {
  75852. _super.prototype.update.call(this);
  75853. for (var index = 0; index < this._buttons.length; index++) {
  75854. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  75855. }
  75856. ;
  75857. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  75858. this.pad.x = this.leftStick.x;
  75859. this.pad.y = this.leftStick.y;
  75860. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  75861. }
  75862. };
  75863. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  75864. if (!newState) {
  75865. newState = {
  75866. pressed: false,
  75867. touched: false,
  75868. value: 0
  75869. };
  75870. }
  75871. if (!currentState) {
  75872. this._buttons[buttonIndex] = {
  75873. pressed: newState.pressed,
  75874. touched: newState.touched,
  75875. value: newState.value
  75876. };
  75877. return;
  75878. }
  75879. this._checkChanges(newState, currentState);
  75880. if (this._changes.changed) {
  75881. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  75882. this._handleButtonChange(buttonIndex, newState, this._changes);
  75883. }
  75884. this._buttons[buttonIndex].pressed = newState.pressed;
  75885. this._buttons[buttonIndex].touched = newState.touched;
  75886. // oculus triggers are never 0, thou not touched.
  75887. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  75888. };
  75889. WebVRController.prototype._checkChanges = function (newState, currentState) {
  75890. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  75891. this._changes.touchChanged = newState.touched !== currentState.touched;
  75892. this._changes.valueChanged = newState.value !== currentState.value;
  75893. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  75894. return this._changes;
  75895. };
  75896. /**
  75897. * Disposes of th webVRCOntroller
  75898. */
  75899. WebVRController.prototype.dispose = function () {
  75900. _super.prototype.dispose.call(this);
  75901. this.onTriggerStateChangedObservable.clear();
  75902. this.onMainButtonStateChangedObservable.clear();
  75903. this.onSecondaryButtonStateChangedObservable.clear();
  75904. this.onPadStateChangedObservable.clear();
  75905. this.onPadValuesChangedObservable.clear();
  75906. };
  75907. return WebVRController;
  75908. }(BABYLON.PoseEnabledController));
  75909. BABYLON.WebVRController = WebVRController;
  75910. })(BABYLON || (BABYLON = {}));
  75911. //# sourceMappingURL=babylon.webVRController.js.map
  75912. var BABYLON;
  75913. (function (BABYLON) {
  75914. /**
  75915. * Oculus Touch Controller
  75916. */
  75917. var OculusTouchController = /** @class */ (function (_super) {
  75918. __extends(OculusTouchController, _super);
  75919. /**
  75920. * Creates a new OculusTouchController from a gamepad
  75921. * @param vrGamepad the gamepad that the controller should be created from
  75922. */
  75923. function OculusTouchController(vrGamepad) {
  75924. var _this = _super.call(this, vrGamepad) || this;
  75925. /**
  75926. * Fired when the secondary trigger on this controller is modified
  75927. */
  75928. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  75929. /**
  75930. * Fired when the thumb rest on this controller is modified
  75931. */
  75932. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  75933. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  75934. return _this;
  75935. }
  75936. /**
  75937. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75938. * @param scene scene in which to add meshes
  75939. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75940. */
  75941. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75942. var _this = this;
  75943. var meshName;
  75944. // Hand
  75945. if (this.hand === 'left') {
  75946. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  75947. }
  75948. else { // Right is the default if no hand is specified
  75949. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  75950. }
  75951. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  75952. /*
  75953. Parent Mesh name: oculus_touch_left
  75954. - body
  75955. - trigger
  75956. - thumbstick
  75957. - grip
  75958. - button_y
  75959. - button_x
  75960. - button_enter
  75961. */
  75962. _this._defaultModel = newMeshes[1];
  75963. _this.attachToMesh(_this._defaultModel);
  75964. if (meshLoaded) {
  75965. meshLoaded(_this._defaultModel);
  75966. }
  75967. });
  75968. };
  75969. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  75970. /**
  75971. * Fired when the A button on this controller is modified
  75972. */
  75973. get: function () {
  75974. if (this.hand === 'right') {
  75975. return this.onMainButtonStateChangedObservable;
  75976. }
  75977. else {
  75978. throw new Error('No A button on left hand');
  75979. }
  75980. },
  75981. enumerable: true,
  75982. configurable: true
  75983. });
  75984. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  75985. /**
  75986. * Fired when the B button on this controller is modified
  75987. */
  75988. get: function () {
  75989. if (this.hand === 'right') {
  75990. return this.onSecondaryButtonStateChangedObservable;
  75991. }
  75992. else {
  75993. throw new Error('No B button on left hand');
  75994. }
  75995. },
  75996. enumerable: true,
  75997. configurable: true
  75998. });
  75999. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  76000. /**
  76001. * Fired when the X button on this controller is modified
  76002. */
  76003. get: function () {
  76004. if (this.hand === 'left') {
  76005. return this.onMainButtonStateChangedObservable;
  76006. }
  76007. else {
  76008. throw new Error('No X button on right hand');
  76009. }
  76010. },
  76011. enumerable: true,
  76012. configurable: true
  76013. });
  76014. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  76015. /**
  76016. * Fired when the Y button on this controller is modified
  76017. */
  76018. get: function () {
  76019. if (this.hand === 'left') {
  76020. return this.onSecondaryButtonStateChangedObservable;
  76021. }
  76022. else {
  76023. throw new Error('No Y button on right hand');
  76024. }
  76025. },
  76026. enumerable: true,
  76027. configurable: true
  76028. });
  76029. /**
  76030. * Called once for each button that changed state since the last frame
  76031. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  76032. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  76033. * 2) secondary trigger (same)
  76034. * 3) A (right) X (left), touch, pressed = value
  76035. * 4) B / Y
  76036. * 5) thumb rest
  76037. * @param buttonIdx Which button index changed
  76038. * @param state New state of the button
  76039. * @param changes Which properties on the state changed since last frame
  76040. */
  76041. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76042. var notifyObject = state; //{ state: state, changes: changes };
  76043. var triggerDirection = this.hand === 'right' ? -1 : 1;
  76044. switch (buttonIdx) {
  76045. case 0:
  76046. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76047. return;
  76048. case 1: // index trigger
  76049. if (this._defaultModel) {
  76050. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  76051. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  76052. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  76053. }
  76054. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76055. return;
  76056. case 2: // secondary trigger
  76057. if (this._defaultModel) {
  76058. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  76059. }
  76060. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  76061. return;
  76062. case 3:
  76063. if (this._defaultModel) {
  76064. if (notifyObject.pressed) {
  76065. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  76066. }
  76067. else {
  76068. (this._defaultModel.getChildren()[1]).position.y = 0;
  76069. }
  76070. }
  76071. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76072. return;
  76073. case 4:
  76074. if (this._defaultModel) {
  76075. if (notifyObject.pressed) {
  76076. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76077. }
  76078. else {
  76079. (this._defaultModel.getChildren()[2]).position.y = 0;
  76080. }
  76081. }
  76082. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76083. return;
  76084. case 5:
  76085. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  76086. return;
  76087. }
  76088. };
  76089. /**
  76090. * Base Url for the controller model.
  76091. */
  76092. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  76093. /**
  76094. * File name for the left controller model.
  76095. */
  76096. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  76097. /**
  76098. * File name for the right controller model.
  76099. */
  76100. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  76101. return OculusTouchController;
  76102. }(BABYLON.WebVRController));
  76103. BABYLON.OculusTouchController = OculusTouchController;
  76104. })(BABYLON || (BABYLON = {}));
  76105. //# sourceMappingURL=babylon.oculusTouchController.js.map
  76106. var BABYLON;
  76107. (function (BABYLON) {
  76108. /**
  76109. * Vive Controller
  76110. */
  76111. var ViveController = /** @class */ (function (_super) {
  76112. __extends(ViveController, _super);
  76113. /**
  76114. * Creates a new ViveController from a gamepad
  76115. * @param vrGamepad the gamepad that the controller should be created from
  76116. */
  76117. function ViveController(vrGamepad) {
  76118. var _this = _super.call(this, vrGamepad) || this;
  76119. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  76120. _this._invertLeftStickY = true;
  76121. return _this;
  76122. }
  76123. /**
  76124. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76125. * @param scene scene in which to add meshes
  76126. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76127. */
  76128. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76129. var _this = this;
  76130. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  76131. /*
  76132. Parent Mesh name: ViveWand
  76133. - body
  76134. - r_gripper
  76135. - l_gripper
  76136. - menu_button
  76137. - system_button
  76138. - trackpad
  76139. - trigger
  76140. - LED
  76141. */
  76142. _this._defaultModel = newMeshes[1];
  76143. _this.attachToMesh(_this._defaultModel);
  76144. if (meshLoaded) {
  76145. meshLoaded(_this._defaultModel);
  76146. }
  76147. });
  76148. };
  76149. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  76150. /**
  76151. * Fired when the left button on this controller is modified
  76152. */
  76153. get: function () {
  76154. return this.onMainButtonStateChangedObservable;
  76155. },
  76156. enumerable: true,
  76157. configurable: true
  76158. });
  76159. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  76160. /**
  76161. * Fired when the right button on this controller is modified
  76162. */
  76163. get: function () {
  76164. return this.onMainButtonStateChangedObservable;
  76165. },
  76166. enumerable: true,
  76167. configurable: true
  76168. });
  76169. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  76170. /**
  76171. * Fired when the menu button on this controller is modified
  76172. */
  76173. get: function () {
  76174. return this.onSecondaryButtonStateChangedObservable;
  76175. },
  76176. enumerable: true,
  76177. configurable: true
  76178. });
  76179. /**
  76180. * Called once for each button that changed state since the last frame
  76181. * Vive mapping:
  76182. * 0: touchpad
  76183. * 1: trigger
  76184. * 2: left AND right buttons
  76185. * 3: menu button
  76186. * @param buttonIdx Which button index changed
  76187. * @param state New state of the button
  76188. * @param changes Which properties on the state changed since last frame
  76189. */
  76190. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76191. var notifyObject = state; //{ state: state, changes: changes };
  76192. switch (buttonIdx) {
  76193. case 0:
  76194. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76195. return;
  76196. case 1: // index trigger
  76197. if (this._defaultModel) {
  76198. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  76199. }
  76200. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76201. return;
  76202. case 2: // left AND right button
  76203. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76204. return;
  76205. case 3:
  76206. if (this._defaultModel) {
  76207. if (notifyObject.pressed) {
  76208. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76209. }
  76210. else {
  76211. (this._defaultModel.getChildren()[2]).position.y = 0;
  76212. }
  76213. }
  76214. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76215. return;
  76216. }
  76217. };
  76218. /**
  76219. * Base Url for the controller model.
  76220. */
  76221. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  76222. /**
  76223. * File name for the controller model.
  76224. */
  76225. ViveController.MODEL_FILENAME = 'wand.babylon';
  76226. return ViveController;
  76227. }(BABYLON.WebVRController));
  76228. BABYLON.ViveController = ViveController;
  76229. })(BABYLON || (BABYLON = {}));
  76230. //# sourceMappingURL=babylon.viveController.js.map
  76231. var BABYLON;
  76232. (function (BABYLON) {
  76233. /**
  76234. * Generic Controller
  76235. */
  76236. var GenericController = /** @class */ (function (_super) {
  76237. __extends(GenericController, _super);
  76238. /**
  76239. * Creates a new GenericController from a gamepad
  76240. * @param vrGamepad the gamepad that the controller should be created from
  76241. */
  76242. function GenericController(vrGamepad) {
  76243. return _super.call(this, vrGamepad) || this;
  76244. }
  76245. /**
  76246. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76247. * @param scene scene in which to add meshes
  76248. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76249. */
  76250. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76251. var _this = this;
  76252. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  76253. _this._defaultModel = newMeshes[1];
  76254. _this.attachToMesh(_this._defaultModel);
  76255. if (meshLoaded) {
  76256. meshLoaded(_this._defaultModel);
  76257. }
  76258. });
  76259. };
  76260. /**
  76261. * Called once for each button that changed state since the last frame
  76262. * @param buttonIdx Which button index changed
  76263. * @param state New state of the button
  76264. * @param changes Which properties on the state changed since last frame
  76265. */
  76266. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76267. console.log("Button id: " + buttonIdx + "state: ");
  76268. console.dir(state);
  76269. };
  76270. /**
  76271. * Base Url for the controller model.
  76272. */
  76273. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76274. /**
  76275. * File name for the controller model.
  76276. */
  76277. GenericController.MODEL_FILENAME = 'generic.babylon';
  76278. return GenericController;
  76279. }(BABYLON.WebVRController));
  76280. BABYLON.GenericController = GenericController;
  76281. })(BABYLON || (BABYLON = {}));
  76282. //# sourceMappingURL=babylon.genericController.js.map
  76283. var BABYLON;
  76284. (function (BABYLON) {
  76285. /**
  76286. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  76287. */
  76288. var LoadedMeshInfo = /** @class */ (function () {
  76289. function LoadedMeshInfo() {
  76290. /**
  76291. * Map of the button meshes contained in the controller
  76292. */
  76293. this.buttonMeshes = {};
  76294. /**
  76295. * Map of the axis meshes contained in the controller
  76296. */
  76297. this.axisMeshes = {};
  76298. }
  76299. return LoadedMeshInfo;
  76300. }());
  76301. /**
  76302. * Defines the WindowsMotionController object that the state of the windows motion controller
  76303. */
  76304. var WindowsMotionController = /** @class */ (function (_super) {
  76305. __extends(WindowsMotionController, _super);
  76306. /**
  76307. * Creates a new WindowsMotionController from a gamepad
  76308. * @param vrGamepad the gamepad that the controller should be created from
  76309. */
  76310. function WindowsMotionController(vrGamepad) {
  76311. var _this = _super.call(this, vrGamepad) || this;
  76312. _this._mapping = {
  76313. // Semantic button names
  76314. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  76315. // A mapping of the button name to glTF model node name
  76316. // that should be transformed by button value.
  76317. buttonMeshNames: {
  76318. 'trigger': 'SELECT',
  76319. 'menu': 'MENU',
  76320. 'grip': 'GRASP',
  76321. 'thumbstick': 'THUMBSTICK_PRESS',
  76322. 'trackpad': 'TOUCHPAD_PRESS'
  76323. },
  76324. // This mapping is used to translate from the Motion Controller to Babylon semantics
  76325. buttonObservableNames: {
  76326. 'trigger': 'onTriggerStateChangedObservable',
  76327. 'menu': 'onSecondaryButtonStateChangedObservable',
  76328. 'grip': 'onMainButtonStateChangedObservable',
  76329. 'thumbstick': 'onPadStateChangedObservable',
  76330. 'trackpad': 'onTrackpadChangedObservable'
  76331. },
  76332. // A mapping of the axis name to glTF model node name
  76333. // that should be transformed by axis value.
  76334. // This array mirrors the browserGamepad.axes array, such that
  76335. // the mesh corresponding to axis 0 is in this array index 0.
  76336. axisMeshNames: [
  76337. 'THUMBSTICK_X',
  76338. 'THUMBSTICK_Y',
  76339. 'TOUCHPAD_TOUCH_X',
  76340. 'TOUCHPAD_TOUCH_Y'
  76341. ],
  76342. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  76343. };
  76344. /**
  76345. * Fired when the trackpad on this controller is clicked
  76346. */
  76347. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  76348. /**
  76349. * Fired when the trackpad on this controller is modified
  76350. */
  76351. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  76352. /**
  76353. * The current x and y values of this controller's trackpad
  76354. */
  76355. _this.trackpad = { x: 0, y: 0 };
  76356. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  76357. _this._loadedMeshInfo = null;
  76358. return _this;
  76359. }
  76360. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  76361. /**
  76362. * Fired when the trigger on this controller is modified
  76363. */
  76364. get: function () {
  76365. return this.onTriggerStateChangedObservable;
  76366. },
  76367. enumerable: true,
  76368. configurable: true
  76369. });
  76370. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  76371. /**
  76372. * Fired when the menu button on this controller is modified
  76373. */
  76374. get: function () {
  76375. return this.onSecondaryButtonStateChangedObservable;
  76376. },
  76377. enumerable: true,
  76378. configurable: true
  76379. });
  76380. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  76381. /**
  76382. * Fired when the grip button on this controller is modified
  76383. */
  76384. get: function () {
  76385. return this.onMainButtonStateChangedObservable;
  76386. },
  76387. enumerable: true,
  76388. configurable: true
  76389. });
  76390. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  76391. /**
  76392. * Fired when the thumbstick button on this controller is modified
  76393. */
  76394. get: function () {
  76395. return this.onPadStateChangedObservable;
  76396. },
  76397. enumerable: true,
  76398. configurable: true
  76399. });
  76400. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  76401. /**
  76402. * Fired when the touchpad button on this controller is modified
  76403. */
  76404. get: function () {
  76405. return this.onTrackpadChangedObservable;
  76406. },
  76407. enumerable: true,
  76408. configurable: true
  76409. });
  76410. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  76411. /**
  76412. * Fired when the touchpad values on this controller are modified
  76413. */
  76414. get: function () {
  76415. return this.onTrackpadValuesChangedObservable;
  76416. },
  76417. enumerable: true,
  76418. configurable: true
  76419. });
  76420. WindowsMotionController.prototype._updateTrackpad = function () {
  76421. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  76422. this.trackpad.x = this.browserGamepad["axes"][2];
  76423. this.trackpad.y = this.browserGamepad["axes"][3];
  76424. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  76425. }
  76426. };
  76427. /**
  76428. * Called once per frame by the engine.
  76429. */
  76430. WindowsMotionController.prototype.update = function () {
  76431. _super.prototype.update.call(this);
  76432. if (this.browserGamepad.axes) {
  76433. this._updateTrackpad();
  76434. // Only need to animate axes if there is a loaded mesh
  76435. if (this._loadedMeshInfo) {
  76436. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  76437. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  76438. }
  76439. }
  76440. }
  76441. };
  76442. /**
  76443. * Called once for each button that changed state since the last frame
  76444. * @param buttonIdx Which button index changed
  76445. * @param state New state of the button
  76446. * @param changes Which properties on the state changed since last frame
  76447. */
  76448. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76449. var buttonName = this._mapping.buttons[buttonIdx];
  76450. if (!buttonName) {
  76451. return;
  76452. }
  76453. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  76454. this._updateTrackpad();
  76455. // Only emit events for buttons that we know how to map from index to name
  76456. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  76457. if (observable) {
  76458. observable.notifyObservers(state);
  76459. }
  76460. this._lerpButtonTransform(buttonName, state.value);
  76461. };
  76462. /**
  76463. * Moves the buttons on the controller mesh based on their current state
  76464. * @param buttonName the name of the button to move
  76465. * @param buttonValue the value of the button which determines the buttons new position
  76466. */
  76467. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  76468. // If there is no loaded mesh, there is nothing to transform.
  76469. if (!this._loadedMeshInfo) {
  76470. return;
  76471. }
  76472. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  76473. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76474. return;
  76475. }
  76476. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  76477. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  76478. };
  76479. /**
  76480. * Moves the axis on the controller mesh based on its current state
  76481. * @param axis the index of the axis
  76482. * @param axisValue the value of the axis which determines the meshes new position
  76483. * @hidden
  76484. */
  76485. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  76486. if (!this._loadedMeshInfo) {
  76487. return;
  76488. }
  76489. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  76490. if (!meshInfo) {
  76491. return;
  76492. }
  76493. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76494. return;
  76495. }
  76496. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  76497. var lerpValue = axisValue * 0.5 + 0.5;
  76498. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  76499. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  76500. };
  76501. /**
  76502. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76503. * @param scene scene in which to add meshes
  76504. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76505. */
  76506. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  76507. var _this = this;
  76508. if (forceDefault === void 0) { forceDefault = false; }
  76509. var path;
  76510. var filename;
  76511. // Checking if GLB loader is present
  76512. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  76513. // Determine the device specific folder based on the ID suffix
  76514. var device = 'default';
  76515. if (this.id && !forceDefault) {
  76516. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  76517. device = ((match && match[0]) || device);
  76518. }
  76519. // Hand
  76520. if (this.hand === 'left') {
  76521. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  76522. }
  76523. else { // Right is the default if no hand is specified
  76524. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  76525. }
  76526. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  76527. }
  76528. else {
  76529. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  76530. path = BABYLON.GenericController.MODEL_BASE_URL;
  76531. filename = BABYLON.GenericController.MODEL_FILENAME;
  76532. }
  76533. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  76534. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  76535. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  76536. if (!_this._loadedMeshInfo) {
  76537. return;
  76538. }
  76539. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  76540. _this.attachToMesh(_this._defaultModel);
  76541. if (meshLoaded) {
  76542. meshLoaded(_this._defaultModel);
  76543. }
  76544. }, null, function (scene, message) {
  76545. BABYLON.Tools.Log(message);
  76546. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  76547. if (!forceDefault) {
  76548. _this.initControllerMesh(scene, meshLoaded, true);
  76549. }
  76550. });
  76551. };
  76552. /**
  76553. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  76554. * can be transformed by button presses and axes values, based on this._mapping.
  76555. *
  76556. * @param scene scene in which the meshes exist
  76557. * @param meshes list of meshes that make up the controller model to process
  76558. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  76559. */
  76560. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  76561. var loadedMeshInfo = null;
  76562. // Create a new mesh to contain the glTF hierarchy
  76563. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  76564. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  76565. var childMesh = null;
  76566. for (var i = 0; i < meshes.length; i++) {
  76567. var mesh = meshes[i];
  76568. if (!mesh.parent) {
  76569. // Exclude controller meshes from picking results
  76570. mesh.isPickable = false;
  76571. // Handle root node, attach to the new parentMesh
  76572. childMesh = mesh;
  76573. break;
  76574. }
  76575. }
  76576. if (childMesh) {
  76577. childMesh.setParent(parentMesh);
  76578. // Create our mesh info. Note that this method will always return non-null.
  76579. loadedMeshInfo = this.createMeshInfo(parentMesh);
  76580. }
  76581. else {
  76582. BABYLON.Tools.Warn('Could not find root node in model file.');
  76583. }
  76584. return loadedMeshInfo;
  76585. };
  76586. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  76587. var loadedMeshInfo = new LoadedMeshInfo();
  76588. var i;
  76589. loadedMeshInfo.rootNode = rootNode;
  76590. // Reset the caches
  76591. loadedMeshInfo.buttonMeshes = {};
  76592. loadedMeshInfo.axisMeshes = {};
  76593. // Button Meshes
  76594. for (i = 0; i < this._mapping.buttons.length; i++) {
  76595. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  76596. if (!buttonMeshName) {
  76597. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  76598. continue;
  76599. }
  76600. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  76601. if (!buttonMesh) {
  76602. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  76603. continue;
  76604. }
  76605. var buttonMeshInfo = {
  76606. index: i,
  76607. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  76608. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  76609. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  76610. };
  76611. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  76612. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  76613. }
  76614. else {
  76615. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  76616. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  76617. '(VALUE: ' + !!buttonMeshInfo.value +
  76618. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  76619. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  76620. ')');
  76621. }
  76622. }
  76623. // Axis Meshes
  76624. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  76625. var axisMeshName = this._mapping.axisMeshNames[i];
  76626. if (!axisMeshName) {
  76627. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  76628. continue;
  76629. }
  76630. var axisMesh = getChildByName(rootNode, axisMeshName);
  76631. if (!axisMesh) {
  76632. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  76633. continue;
  76634. }
  76635. var axisMeshInfo = {
  76636. index: i,
  76637. value: getImmediateChildByName(axisMesh, 'VALUE'),
  76638. min: getImmediateChildByName(axisMesh, 'MIN'),
  76639. max: getImmediateChildByName(axisMesh, 'MAX')
  76640. };
  76641. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  76642. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  76643. }
  76644. else {
  76645. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  76646. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  76647. '(VALUE: ' + !!axisMeshInfo.value +
  76648. ', MIN: ' + !!axisMeshInfo.min +
  76649. ', MAX:' + !!axisMeshInfo.max +
  76650. ')');
  76651. }
  76652. }
  76653. // Pointing Ray
  76654. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  76655. if (!loadedMeshInfo.pointingPoseNode) {
  76656. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  76657. }
  76658. else {
  76659. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  76660. }
  76661. return loadedMeshInfo;
  76662. // Look through all children recursively. This will return null if no mesh exists with the given name.
  76663. function getChildByName(node, name) {
  76664. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  76665. }
  76666. // Look through only immediate children. This will return null if no mesh exists with the given name.
  76667. function getImmediateChildByName(node, name) {
  76668. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  76669. }
  76670. };
  76671. /**
  76672. * Gets the ray of the controller in the direction the controller is pointing
  76673. * @param length the length the resulting ray should be
  76674. * @returns a ray in the direction the controller is pointing
  76675. */
  76676. WindowsMotionController.prototype.getForwardRay = function (length) {
  76677. if (length === void 0) { length = 100; }
  76678. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  76679. return _super.prototype.getForwardRay.call(this, length);
  76680. }
  76681. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  76682. var origin = m.getTranslation();
  76683. var forward = new BABYLON.Vector3(0, 0, -1);
  76684. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76685. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76686. return new BABYLON.Ray(origin, direction, length);
  76687. };
  76688. /**
  76689. * Disposes of the controller
  76690. */
  76691. WindowsMotionController.prototype.dispose = function () {
  76692. _super.prototype.dispose.call(this);
  76693. this.onTrackpadChangedObservable.clear();
  76694. };
  76695. /**
  76696. * The base url used to load the left and right controller models
  76697. */
  76698. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  76699. /**
  76700. * The name of the left controller model file
  76701. */
  76702. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  76703. /**
  76704. * The name of the right controller model file
  76705. */
  76706. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  76707. /**
  76708. * The controller name prefix for this controller type
  76709. */
  76710. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  76711. /**
  76712. * The controller id pattern for this controller type
  76713. */
  76714. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  76715. return WindowsMotionController;
  76716. }(BABYLON.WebVRController));
  76717. BABYLON.WindowsMotionController = WindowsMotionController;
  76718. })(BABYLON || (BABYLON = {}));
  76719. //# sourceMappingURL=babylon.windowsMotionController.js.map
  76720. var BABYLON;
  76721. (function (BABYLON) {
  76722. /**
  76723. * Gear VR Controller
  76724. */
  76725. var GearVRController = /** @class */ (function (_super) {
  76726. __extends(GearVRController, _super);
  76727. /**
  76728. * Creates a new GearVRController from a gamepad
  76729. * @param vrGamepad the gamepad that the controller should be created from
  76730. */
  76731. function GearVRController(vrGamepad) {
  76732. var _this = _super.call(this, vrGamepad) || this;
  76733. _this._maxRotationDistFromHeadset = Math.PI / 5;
  76734. _this._draggedRoomRotation = 0;
  76735. _this._tmpVector = new BABYLON.Vector3();
  76736. _this._buttonIndexToObservableNameMap = [
  76737. 'onTrackpadChangedObservable',
  76738. 'onTriggerStateChangedObservable' // Trigger
  76739. ];
  76740. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  76741. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  76742. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  76743. return _this;
  76744. }
  76745. /**
  76746. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76747. * @param poseData raw pose fromthe device
  76748. */
  76749. GearVRController.prototype.updateFromDevice = function (poseData) {
  76750. _super.prototype.updateFromDevice.call(this, poseData);
  76751. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  76752. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  76753. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  76754. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  76755. // Find the radian distance away that the headset is from the controllers rotation
  76756. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  76757. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  76758. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  76759. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  76760. this._draggedRoomRotation += rotationAmount;
  76761. // Rotate controller around headset
  76762. var sin = Math.sin(-rotationAmount);
  76763. var cos = Math.cos(-rotationAmount);
  76764. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  76765. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  76766. }
  76767. }
  76768. }
  76769. };
  76770. /**
  76771. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76772. * @param scene scene in which to add meshes
  76773. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76774. */
  76775. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76776. var _this = this;
  76777. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  76778. // Offset the controller so it will rotate around the users wrist
  76779. var mesh = new BABYLON.Mesh("", scene);
  76780. newMeshes[1].parent = mesh;
  76781. newMeshes[1].position.z = -0.15;
  76782. _this._defaultModel = mesh;
  76783. _this.attachToMesh(_this._defaultModel);
  76784. if (meshLoaded) {
  76785. meshLoaded(_this._defaultModel);
  76786. }
  76787. });
  76788. };
  76789. /**
  76790. * Called once for each button that changed state since the last frame
  76791. * @param buttonIdx Which button index changed
  76792. * @param state New state of the button
  76793. * @param changes Which properties on the state changed since last frame
  76794. */
  76795. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76796. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  76797. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  76798. // Only emit events for buttons that we know how to map from index to observable
  76799. var observable = this[observableName];
  76800. if (observable) {
  76801. observable.notifyObservers(state);
  76802. }
  76803. }
  76804. };
  76805. /**
  76806. * Base Url for the controller model.
  76807. */
  76808. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76809. /**
  76810. * File name for the controller model.
  76811. */
  76812. GearVRController.MODEL_FILENAME = 'generic.babylon';
  76813. /**
  76814. * Gamepad Id prefix used to identify this controller.
  76815. */
  76816. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  76817. return GearVRController;
  76818. }(BABYLON.WebVRController));
  76819. BABYLON.GearVRController = GearVRController;
  76820. })(BABYLON || (BABYLON = {}));
  76821. //# sourceMappingURL=babylon.gearVRController.js.map
  76822. var BABYLON;
  76823. (function (BABYLON) {
  76824. /**
  76825. * Google Daydream controller
  76826. */
  76827. var DaydreamController = /** @class */ (function (_super) {
  76828. __extends(DaydreamController, _super);
  76829. /**
  76830. * Creates a new DaydreamController from a gamepad
  76831. * @param vrGamepad the gamepad that the controller should be created from
  76832. */
  76833. function DaydreamController(vrGamepad) {
  76834. var _this = _super.call(this, vrGamepad) || this;
  76835. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  76836. return _this;
  76837. }
  76838. /**
  76839. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76840. * @param scene scene in which to add meshes
  76841. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76842. */
  76843. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76844. var _this = this;
  76845. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  76846. _this._defaultModel = newMeshes[1];
  76847. _this.attachToMesh(_this._defaultModel);
  76848. if (meshLoaded) {
  76849. meshLoaded(_this._defaultModel);
  76850. }
  76851. });
  76852. };
  76853. /**
  76854. * Called once for each button that changed state since the last frame
  76855. * @param buttonIdx Which button index changed
  76856. * @param state New state of the button
  76857. * @param changes Which properties on the state changed since last frame
  76858. */
  76859. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76860. // Daydream controller only has 1 GamepadButton (on the trackpad).
  76861. if (buttonIdx === 0) {
  76862. var observable = this.onTriggerStateChangedObservable;
  76863. if (observable) {
  76864. observable.notifyObservers(state);
  76865. }
  76866. }
  76867. else {
  76868. // If the app or home buttons are ever made available
  76869. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  76870. }
  76871. };
  76872. /**
  76873. * Base Url for the controller model.
  76874. */
  76875. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76876. /**
  76877. * File name for the controller model.
  76878. */
  76879. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  76880. /**
  76881. * Gamepad Id prefix used to identify Daydream Controller.
  76882. */
  76883. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  76884. return DaydreamController;
  76885. }(BABYLON.WebVRController));
  76886. BABYLON.DaydreamController = DaydreamController;
  76887. })(BABYLON || (BABYLON = {}));
  76888. //# sourceMappingURL=babylon.daydreamController.js.map
  76889. var BABYLON;
  76890. (function (BABYLON) {
  76891. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  76892. get: function () {
  76893. if (!this._gamepadManager) {
  76894. this._gamepadManager = new BABYLON.GamepadManager(this);
  76895. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  76896. if (!component) {
  76897. component = new GamepadSystemSceneComponent(this);
  76898. this._addComponent(component);
  76899. }
  76900. }
  76901. return this._gamepadManager;
  76902. },
  76903. enumerable: true,
  76904. configurable: true
  76905. });
  76906. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  76907. this.add(new BABYLON.FreeCameraGamepadInput());
  76908. return this;
  76909. };
  76910. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  76911. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  76912. return this;
  76913. };
  76914. /**
  76915. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  76916. */
  76917. var GamepadSystemSceneComponent = /** @class */ (function () {
  76918. /**
  76919. * Creates a new instance of the component for the given scene
  76920. * @param scene Defines the scene to register the component in
  76921. */
  76922. function GamepadSystemSceneComponent(scene) {
  76923. /**
  76924. * The component name helpfull to identify the component in the list of scene components.
  76925. */
  76926. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  76927. this.scene = scene;
  76928. }
  76929. /**
  76930. * Registers the component in a given scene
  76931. */
  76932. GamepadSystemSceneComponent.prototype.register = function () {
  76933. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  76934. };
  76935. /**
  76936. * Rebuilds the elements related to this component in case of
  76937. * context lost for instance.
  76938. */
  76939. GamepadSystemSceneComponent.prototype.rebuild = function () {
  76940. // Nothing to do for gamepads
  76941. };
  76942. /**
  76943. * Disposes the component and the associated ressources
  76944. */
  76945. GamepadSystemSceneComponent.prototype.dispose = function () {
  76946. var gamepadManager = this.scene._gamepadManager;
  76947. if (gamepadManager) {
  76948. gamepadManager.dispose();
  76949. this.scene._gamepadManager = null;
  76950. }
  76951. };
  76952. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  76953. var gamepadManager = this.scene._gamepadManager;
  76954. if (gamepadManager && gamepadManager._isMonitoring) {
  76955. gamepadManager._checkGamepadsStatus();
  76956. }
  76957. };
  76958. return GamepadSystemSceneComponent;
  76959. }());
  76960. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  76961. })(BABYLON || (BABYLON = {}));
  76962. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  76963. var BABYLON;
  76964. (function (BABYLON) {
  76965. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  76966. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  76967. });
  76968. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  76969. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  76970. });
  76971. var FollowCamera = /** @class */ (function (_super) {
  76972. __extends(FollowCamera, _super);
  76973. function FollowCamera(name, position, scene, lockedTarget) {
  76974. if (lockedTarget === void 0) { lockedTarget = null; }
  76975. var _this = _super.call(this, name, position, scene) || this;
  76976. _this.radius = 12;
  76977. _this.rotationOffset = 0;
  76978. _this.heightOffset = 4;
  76979. _this.cameraAcceleration = 0.05;
  76980. _this.maxCameraSpeed = 20;
  76981. _this.lockedTarget = lockedTarget;
  76982. return _this;
  76983. }
  76984. FollowCamera.prototype.getRadians = function (degrees) {
  76985. return degrees * Math.PI / 180;
  76986. };
  76987. FollowCamera.prototype.follow = function (cameraTarget) {
  76988. if (!cameraTarget)
  76989. return;
  76990. var yRotation;
  76991. if (cameraTarget.rotationQuaternion) {
  76992. var rotMatrix = new BABYLON.Matrix();
  76993. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  76994. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  76995. }
  76996. else {
  76997. yRotation = cameraTarget.rotation.y;
  76998. }
  76999. var radians = this.getRadians(this.rotationOffset) + yRotation;
  77000. var targetPosition = cameraTarget.getAbsolutePosition();
  77001. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  77002. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  77003. var dx = targetX - this.position.x;
  77004. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  77005. var dz = (targetZ) - this.position.z;
  77006. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  77007. var vy = dy * this.cameraAcceleration;
  77008. var vz = dz * this.cameraAcceleration * 2;
  77009. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  77010. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77011. }
  77012. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  77013. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77014. }
  77015. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  77016. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77017. }
  77018. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  77019. this.setTarget(targetPosition);
  77020. };
  77021. /** @hidden */
  77022. FollowCamera.prototype._checkInputs = function () {
  77023. _super.prototype._checkInputs.call(this);
  77024. if (this.lockedTarget) {
  77025. this.follow(this.lockedTarget);
  77026. }
  77027. };
  77028. FollowCamera.prototype.getClassName = function () {
  77029. return "FollowCamera";
  77030. };
  77031. __decorate([
  77032. BABYLON.serialize()
  77033. ], FollowCamera.prototype, "radius", void 0);
  77034. __decorate([
  77035. BABYLON.serialize()
  77036. ], FollowCamera.prototype, "rotationOffset", void 0);
  77037. __decorate([
  77038. BABYLON.serialize()
  77039. ], FollowCamera.prototype, "heightOffset", void 0);
  77040. __decorate([
  77041. BABYLON.serialize()
  77042. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  77043. __decorate([
  77044. BABYLON.serialize()
  77045. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  77046. __decorate([
  77047. BABYLON.serializeAsMeshReference("lockedTargetId")
  77048. ], FollowCamera.prototype, "lockedTarget", void 0);
  77049. return FollowCamera;
  77050. }(BABYLON.TargetCamera));
  77051. BABYLON.FollowCamera = FollowCamera;
  77052. var ArcFollowCamera = /** @class */ (function (_super) {
  77053. __extends(ArcFollowCamera, _super);
  77054. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  77055. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  77056. _this.alpha = alpha;
  77057. _this.beta = beta;
  77058. _this.radius = radius;
  77059. _this.target = target;
  77060. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  77061. _this.follow();
  77062. return _this;
  77063. }
  77064. ArcFollowCamera.prototype.follow = function () {
  77065. if (!this.target) {
  77066. return;
  77067. }
  77068. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  77069. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  77070. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  77071. var targetPosition = this.target.getAbsolutePosition();
  77072. this.position = targetPosition.add(this._cartesianCoordinates);
  77073. this.setTarget(targetPosition);
  77074. };
  77075. /** @hidden */
  77076. ArcFollowCamera.prototype._checkInputs = function () {
  77077. _super.prototype._checkInputs.call(this);
  77078. this.follow();
  77079. };
  77080. ArcFollowCamera.prototype.getClassName = function () {
  77081. return "ArcFollowCamera";
  77082. };
  77083. return ArcFollowCamera;
  77084. }(BABYLON.TargetCamera));
  77085. BABYLON.ArcFollowCamera = ArcFollowCamera;
  77086. })(BABYLON || (BABYLON = {}));
  77087. //# sourceMappingURL=babylon.followCamera.js.map
  77088. var BABYLON;
  77089. (function (BABYLON) {
  77090. // We're mainly based on the logic defined into the FreeCamera code
  77091. var UniversalCamera = /** @class */ (function (_super) {
  77092. __extends(UniversalCamera, _super);
  77093. //-- end properties for backward compatibility for inputs
  77094. function UniversalCamera(name, position, scene) {
  77095. var _this = _super.call(this, name, position, scene) || this;
  77096. _this.inputs.addGamepad();
  77097. return _this;
  77098. }
  77099. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  77100. //-- Begin properties for backward compatibility for inputs
  77101. get: function () {
  77102. var gamepad = this.inputs.attached["gamepad"];
  77103. if (gamepad)
  77104. return gamepad.gamepadAngularSensibility;
  77105. return 0;
  77106. },
  77107. set: function (value) {
  77108. var gamepad = this.inputs.attached["gamepad"];
  77109. if (gamepad)
  77110. gamepad.gamepadAngularSensibility = value;
  77111. },
  77112. enumerable: true,
  77113. configurable: true
  77114. });
  77115. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  77116. get: function () {
  77117. var gamepad = this.inputs.attached["gamepad"];
  77118. if (gamepad)
  77119. return gamepad.gamepadMoveSensibility;
  77120. return 0;
  77121. },
  77122. set: function (value) {
  77123. var gamepad = this.inputs.attached["gamepad"];
  77124. if (gamepad)
  77125. gamepad.gamepadMoveSensibility = value;
  77126. },
  77127. enumerable: true,
  77128. configurable: true
  77129. });
  77130. UniversalCamera.prototype.getClassName = function () {
  77131. return "UniversalCamera";
  77132. };
  77133. return UniversalCamera;
  77134. }(BABYLON.TouchCamera));
  77135. BABYLON.UniversalCamera = UniversalCamera;
  77136. })(BABYLON || (BABYLON = {}));
  77137. //# sourceMappingURL=babylon.universalCamera.js.map
  77138. var BABYLON;
  77139. (function (BABYLON) {
  77140. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  77141. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  77142. });
  77143. // We're mainly based on the logic defined into the FreeCamera code
  77144. var GamepadCamera = /** @class */ (function (_super) {
  77145. __extends(GamepadCamera, _super);
  77146. //-- end properties for backward compatibility for inputs
  77147. function GamepadCamera(name, position, scene) {
  77148. return _super.call(this, name, position, scene) || this;
  77149. }
  77150. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  77151. //-- Begin properties for backward compatibility for inputs
  77152. get: function () {
  77153. var gamepad = this.inputs.attached["gamepad"];
  77154. if (gamepad)
  77155. return gamepad.gamepadAngularSensibility;
  77156. return 0;
  77157. },
  77158. set: function (value) {
  77159. var gamepad = this.inputs.attached["gamepad"];
  77160. if (gamepad)
  77161. gamepad.gamepadAngularSensibility = value;
  77162. },
  77163. enumerable: true,
  77164. configurable: true
  77165. });
  77166. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  77167. get: function () {
  77168. var gamepad = this.inputs.attached["gamepad"];
  77169. if (gamepad)
  77170. return gamepad.gamepadMoveSensibility;
  77171. return 0;
  77172. },
  77173. set: function (value) {
  77174. var gamepad = this.inputs.attached["gamepad"];
  77175. if (gamepad)
  77176. gamepad.gamepadMoveSensibility = value;
  77177. },
  77178. enumerable: true,
  77179. configurable: true
  77180. });
  77181. GamepadCamera.prototype.getClassName = function () {
  77182. return "GamepadCamera";
  77183. };
  77184. return GamepadCamera;
  77185. }(BABYLON.UniversalCamera));
  77186. BABYLON.GamepadCamera = GamepadCamera;
  77187. })(BABYLON || (BABYLON = {}));
  77188. //# sourceMappingURL=babylon.gamepadCamera.js.map
  77189. var BABYLON;
  77190. (function (BABYLON) {
  77191. var PostProcessRenderPipelineManager = /** @class */ (function () {
  77192. function PostProcessRenderPipelineManager() {
  77193. this._renderPipelines = {};
  77194. }
  77195. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  77196. this._renderPipelines[renderPipeline._name] = renderPipeline;
  77197. };
  77198. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  77199. if (unique === void 0) { unique = false; }
  77200. var renderPipeline = this._renderPipelines[renderPipelineName];
  77201. if (!renderPipeline) {
  77202. return;
  77203. }
  77204. renderPipeline._attachCameras(cameras, unique);
  77205. };
  77206. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  77207. var renderPipeline = this._renderPipelines[renderPipelineName];
  77208. if (!renderPipeline) {
  77209. return;
  77210. }
  77211. renderPipeline._detachCameras(cameras);
  77212. };
  77213. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77214. var renderPipeline = this._renderPipelines[renderPipelineName];
  77215. if (!renderPipeline) {
  77216. return;
  77217. }
  77218. renderPipeline._enableEffect(renderEffectName, cameras);
  77219. };
  77220. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77221. var renderPipeline = this._renderPipelines[renderPipelineName];
  77222. if (!renderPipeline) {
  77223. return;
  77224. }
  77225. renderPipeline._disableEffect(renderEffectName, cameras);
  77226. };
  77227. PostProcessRenderPipelineManager.prototype.update = function () {
  77228. for (var renderPipelineName in this._renderPipelines) {
  77229. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77230. var pipeline = this._renderPipelines[renderPipelineName];
  77231. if (!pipeline.isSupported) {
  77232. pipeline.dispose();
  77233. delete this._renderPipelines[renderPipelineName];
  77234. }
  77235. else {
  77236. pipeline._update();
  77237. }
  77238. }
  77239. }
  77240. };
  77241. /** @hidden */
  77242. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  77243. for (var renderPipelineName in this._renderPipelines) {
  77244. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77245. var pipeline = this._renderPipelines[renderPipelineName];
  77246. pipeline._rebuild();
  77247. }
  77248. }
  77249. };
  77250. PostProcessRenderPipelineManager.prototype.dispose = function () {
  77251. for (var renderPipelineName in this._renderPipelines) {
  77252. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77253. var pipeline = this._renderPipelines[renderPipelineName];
  77254. pipeline.dispose();
  77255. }
  77256. }
  77257. };
  77258. return PostProcessRenderPipelineManager;
  77259. }());
  77260. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  77261. })(BABYLON || (BABYLON = {}));
  77262. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  77263. var BABYLON;
  77264. (function (BABYLON) {
  77265. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  77266. get: function () {
  77267. if (!this._postProcessRenderPipelineManager) {
  77268. // Register the G Buffer component to the scene.
  77269. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  77270. if (!component) {
  77271. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  77272. this._addComponent(component);
  77273. }
  77274. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  77275. }
  77276. return this._postProcessRenderPipelineManager;
  77277. },
  77278. enumerable: true,
  77279. configurable: true
  77280. });
  77281. /**
  77282. * Defines the Render Pipeline scene component responsible to rendering pipelines
  77283. */
  77284. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  77285. /**
  77286. * Creates a new instance of the component for the given scene
  77287. * @param scene Defines the scene to register the component in
  77288. */
  77289. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  77290. /**
  77291. * The component name helpfull to identify the component in the list of scene components.
  77292. */
  77293. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  77294. this.scene = scene;
  77295. }
  77296. /**
  77297. * Registers the component in a given scene
  77298. */
  77299. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  77300. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  77301. };
  77302. /**
  77303. * Rebuilds the elements related to this component in case of
  77304. * context lost for instance.
  77305. */
  77306. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  77307. if (this.scene._postProcessRenderPipelineManager) {
  77308. this.scene._postProcessRenderPipelineManager._rebuild();
  77309. }
  77310. };
  77311. /**
  77312. * Disposes the component and the associated ressources
  77313. */
  77314. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  77315. if (this.scene._postProcessRenderPipelineManager) {
  77316. this.scene._postProcessRenderPipelineManager.dispose();
  77317. }
  77318. };
  77319. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77320. if (this.scene._postProcessRenderPipelineManager) {
  77321. this.scene._postProcessRenderPipelineManager.update();
  77322. }
  77323. };
  77324. return PostProcessRenderPipelineManagerSceneComponent;
  77325. }());
  77326. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  77327. })(BABYLON || (BABYLON = {}));
  77328. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  77329. var BABYLON;
  77330. (function (BABYLON) {
  77331. /**
  77332. * This represents a set of one or more post processes in Babylon.
  77333. * A post process can be used to apply a shader to a texture after it is rendered.
  77334. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  77335. */
  77336. var PostProcessRenderEffect = /** @class */ (function () {
  77337. /**
  77338. * Instantiates a post process render effect.
  77339. * A post process can be used to apply a shader to a texture after it is rendered.
  77340. * @param engine The engine the effect is tied to
  77341. * @param name The name of the effect
  77342. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  77343. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  77344. */
  77345. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  77346. this._name = name;
  77347. this._singleInstance = singleInstance || true;
  77348. this._getPostProcesses = getPostProcesses;
  77349. this._cameras = {};
  77350. this._indicesForCamera = {};
  77351. this._postProcesses = {};
  77352. }
  77353. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  77354. /**
  77355. * Checks if all the post processes in the effect are supported.
  77356. */
  77357. get: function () {
  77358. for (var index in this._postProcesses) {
  77359. if (this._postProcesses.hasOwnProperty(index)) {
  77360. var pps = this._postProcesses[index];
  77361. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  77362. if (!pps[ppIndex].isSupported) {
  77363. return false;
  77364. }
  77365. }
  77366. }
  77367. }
  77368. return true;
  77369. },
  77370. enumerable: true,
  77371. configurable: true
  77372. });
  77373. /**
  77374. * Updates the current state of the effect
  77375. * @hidden
  77376. */
  77377. PostProcessRenderEffect.prototype._update = function () {
  77378. };
  77379. /**
  77380. * Attaches the effect on cameras
  77381. * @param cameras The camera to attach to.
  77382. * @hidden
  77383. */
  77384. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  77385. var _this = this;
  77386. var cameraKey;
  77387. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77388. if (!cams) {
  77389. return;
  77390. }
  77391. for (var i = 0; i < cams.length; i++) {
  77392. var camera = cams[i];
  77393. var cameraName = camera.name;
  77394. if (this._singleInstance) {
  77395. cameraKey = 0;
  77396. }
  77397. else {
  77398. cameraKey = cameraName;
  77399. }
  77400. if (!this._postProcesses[cameraKey]) {
  77401. var postProcess = this._getPostProcesses();
  77402. if (postProcess) {
  77403. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  77404. }
  77405. }
  77406. if (!this._indicesForCamera[cameraName]) {
  77407. this._indicesForCamera[cameraName] = [];
  77408. }
  77409. this._postProcesses[cameraKey].forEach(function (postProcess) {
  77410. var index = camera.attachPostProcess(postProcess);
  77411. _this._indicesForCamera[cameraName].push(index);
  77412. });
  77413. if (!this._cameras[cameraName]) {
  77414. this._cameras[cameraName] = camera;
  77415. }
  77416. }
  77417. };
  77418. /**
  77419. * Detatches the effect on cameras
  77420. * @param cameras The camera to detatch from.
  77421. * @hidden
  77422. */
  77423. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  77424. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77425. if (!cams) {
  77426. return;
  77427. }
  77428. for (var i = 0; i < cams.length; i++) {
  77429. var camera = cams[i];
  77430. var cameraName = camera.name;
  77431. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77432. camera.detachPostProcess(postProcess);
  77433. });
  77434. if (this._cameras[cameraName]) {
  77435. //this._indicesForCamera.splice(index, 1);
  77436. this._cameras[cameraName] = null;
  77437. }
  77438. }
  77439. };
  77440. /**
  77441. * Enables the effect on given cameras
  77442. * @param cameras The camera to enable.
  77443. * @hidden
  77444. */
  77445. PostProcessRenderEffect.prototype._enable = function (cameras) {
  77446. var _this = this;
  77447. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77448. if (!cams) {
  77449. return;
  77450. }
  77451. for (var i = 0; i < cams.length; i++) {
  77452. var camera = cams[i];
  77453. var cameraName = camera.name;
  77454. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  77455. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  77456. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77457. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  77458. });
  77459. }
  77460. }
  77461. }
  77462. };
  77463. /**
  77464. * Disables the effect on the given cameras
  77465. * @param cameras The camera to disable.
  77466. * @hidden
  77467. */
  77468. PostProcessRenderEffect.prototype._disable = function (cameras) {
  77469. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77470. if (!cams) {
  77471. return;
  77472. }
  77473. for (var i = 0; i < cams.length; i++) {
  77474. var camera = cams[i];
  77475. var cameraName = camera.name;
  77476. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77477. camera.detachPostProcess(postProcess);
  77478. });
  77479. }
  77480. };
  77481. /**
  77482. * Gets a list of the post processes contained in the effect.
  77483. * @param camera The camera to get the post processes on.
  77484. * @returns The list of the post processes in the effect.
  77485. */
  77486. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  77487. if (this._singleInstance) {
  77488. return this._postProcesses[0];
  77489. }
  77490. else {
  77491. if (!camera) {
  77492. return null;
  77493. }
  77494. return this._postProcesses[camera.name];
  77495. }
  77496. };
  77497. return PostProcessRenderEffect;
  77498. }());
  77499. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  77500. })(BABYLON || (BABYLON = {}));
  77501. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  77502. var BABYLON;
  77503. (function (BABYLON) {
  77504. var PostProcessRenderPipeline = /** @class */ (function () {
  77505. function PostProcessRenderPipeline(engine, name) {
  77506. this.engine = engine;
  77507. this._name = name;
  77508. this._renderEffects = {};
  77509. this._renderEffectsForIsolatedPass = new Array();
  77510. this._cameras = [];
  77511. }
  77512. PostProcessRenderPipeline.prototype.getClassName = function () {
  77513. return "PostProcessRenderPipeline";
  77514. };
  77515. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  77516. get: function () {
  77517. for (var renderEffectName in this._renderEffects) {
  77518. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77519. if (!this._renderEffects[renderEffectName].isSupported) {
  77520. return false;
  77521. }
  77522. }
  77523. }
  77524. return true;
  77525. },
  77526. enumerable: true,
  77527. configurable: true
  77528. });
  77529. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  77530. this._renderEffects[renderEffect._name] = renderEffect;
  77531. };
  77532. // private
  77533. /** @hidden */
  77534. PostProcessRenderPipeline.prototype._rebuild = function () {
  77535. };
  77536. /** @hidden */
  77537. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  77538. var renderEffects = this._renderEffects[renderEffectName];
  77539. if (!renderEffects) {
  77540. return;
  77541. }
  77542. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77543. };
  77544. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  77545. var renderEffects = this._renderEffects[renderEffectName];
  77546. if (!renderEffects) {
  77547. return;
  77548. }
  77549. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77550. };
  77551. /** @hidden */
  77552. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  77553. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77554. if (!cams) {
  77555. return;
  77556. }
  77557. var indicesToDelete = [];
  77558. var i;
  77559. for (i = 0; i < cams.length; i++) {
  77560. var camera = cams[i];
  77561. var cameraName = camera.name;
  77562. if (this._cameras.indexOf(camera) === -1) {
  77563. this._cameras[cameraName] = camera;
  77564. }
  77565. else if (unique) {
  77566. indicesToDelete.push(i);
  77567. }
  77568. }
  77569. for (i = 0; i < indicesToDelete.length; i++) {
  77570. cameras.splice(indicesToDelete[i], 1);
  77571. }
  77572. for (var renderEffectName in this._renderEffects) {
  77573. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77574. this._renderEffects[renderEffectName]._attachCameras(cams);
  77575. }
  77576. }
  77577. };
  77578. /** @hidden */
  77579. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  77580. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77581. if (!cams) {
  77582. return;
  77583. }
  77584. for (var renderEffectName in this._renderEffects) {
  77585. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77586. this._renderEffects[renderEffectName]._detachCameras(cams);
  77587. }
  77588. }
  77589. for (var i = 0; i < cams.length; i++) {
  77590. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  77591. }
  77592. };
  77593. /** @hidden */
  77594. PostProcessRenderPipeline.prototype._update = function () {
  77595. for (var renderEffectName in this._renderEffects) {
  77596. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77597. this._renderEffects[renderEffectName]._update();
  77598. }
  77599. }
  77600. for (var i = 0; i < this._cameras.length; i++) {
  77601. var cameraName = this._cameras[i].name;
  77602. if (this._renderEffectsForIsolatedPass[cameraName]) {
  77603. this._renderEffectsForIsolatedPass[cameraName]._update();
  77604. }
  77605. }
  77606. };
  77607. /** @hidden */
  77608. PostProcessRenderPipeline.prototype._reset = function () {
  77609. this._renderEffects = {};
  77610. this._renderEffectsForIsolatedPass = new Array();
  77611. };
  77612. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  77613. // 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)
  77614. var effectKeys = Object.keys(this._renderEffects);
  77615. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  77616. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  77617. if (postProcesses) {
  77618. postProcesses[0].samples = sampleCount;
  77619. return true;
  77620. }
  77621. }
  77622. return false;
  77623. };
  77624. PostProcessRenderPipeline.prototype.dispose = function () {
  77625. // Must be implemented by children
  77626. };
  77627. __decorate([
  77628. BABYLON.serialize()
  77629. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  77630. return PostProcessRenderPipeline;
  77631. }());
  77632. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  77633. })(BABYLON || (BABYLON = {}));
  77634. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  77635. var BABYLON;
  77636. (function (BABYLON) {
  77637. /**
  77638. * This represents a depth renderer in Babylon.
  77639. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  77640. */
  77641. var DepthRenderer = /** @class */ (function () {
  77642. /**
  77643. * Instantiates a depth renderer
  77644. * @param scene The scene the renderer belongs to
  77645. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  77646. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  77647. */
  77648. function DepthRenderer(scene, type, camera) {
  77649. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  77650. if (camera === void 0) { camera = null; }
  77651. var _this = this;
  77652. /**
  77653. * Specifiess that the depth renderer will only be used within
  77654. * the camera it is created for.
  77655. * This can help forcing its rendering during the camera processing.
  77656. */
  77657. this.useOnlyInActiveCamera = false;
  77658. this._scene = scene;
  77659. // Register the G Buffer component to the scene.
  77660. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  77661. if (!component) {
  77662. component = new BABYLON.DepthRendererSceneComponent(scene);
  77663. scene._addComponent(component);
  77664. }
  77665. this._camera = camera;
  77666. var engine = scene.getEngine();
  77667. // Render target
  77668. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  77669. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77670. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77671. this._depthMap.refreshRate = 1;
  77672. this._depthMap.renderParticles = false;
  77673. this._depthMap.renderList = null;
  77674. // Camera to get depth map from to support multiple concurrent cameras
  77675. this._depthMap.activeCamera = this._camera;
  77676. this._depthMap.ignoreCameraViewport = true;
  77677. this._depthMap.useCameraPostProcesses = false;
  77678. // set default depth value to 1.0 (far away)
  77679. this._depthMap.onClearObservable.add(function (engine) {
  77680. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  77681. });
  77682. // Custom render function
  77683. var renderSubMesh = function (subMesh) {
  77684. var mesh = subMesh.getRenderingMesh();
  77685. var scene = _this._scene;
  77686. var engine = scene.getEngine();
  77687. var material = subMesh.getMaterial();
  77688. if (!material) {
  77689. return;
  77690. }
  77691. // Culling and reverse (right handed system)
  77692. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77693. // Managing instances
  77694. var batch = mesh._getInstancesRenderList(subMesh._id);
  77695. if (batch.mustReturn) {
  77696. return;
  77697. }
  77698. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77699. var camera = _this._camera || scene.activeCamera;
  77700. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  77701. engine.enableEffect(_this._effect);
  77702. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77703. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77704. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  77705. // Alpha test
  77706. if (material && material.needAlphaTesting()) {
  77707. var alphaTexture = material.getAlphaTestTexture();
  77708. if (alphaTexture) {
  77709. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77710. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77711. }
  77712. }
  77713. // Bones
  77714. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77715. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77716. }
  77717. // Draw
  77718. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77719. }
  77720. };
  77721. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77722. var index;
  77723. if (depthOnlySubMeshes.length) {
  77724. engine.setColorWrite(false);
  77725. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77726. renderSubMesh(depthOnlySubMeshes.data[index]);
  77727. }
  77728. engine.setColorWrite(true);
  77729. }
  77730. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77731. renderSubMesh(opaqueSubMeshes.data[index]);
  77732. }
  77733. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77734. renderSubMesh(alphaTestSubMeshes.data[index]);
  77735. }
  77736. };
  77737. }
  77738. /**
  77739. * Creates the depth rendering effect and checks if the effect is ready.
  77740. * @param subMesh The submesh to be used to render the depth map of
  77741. * @param useInstances If multiple world instances should be used
  77742. * @returns if the depth renderer is ready to render the depth map
  77743. */
  77744. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  77745. var material = subMesh.getMaterial();
  77746. if (material.disableDepthWrite) {
  77747. return false;
  77748. }
  77749. var defines = [];
  77750. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77751. var mesh = subMesh.getMesh();
  77752. // Alpha test
  77753. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  77754. defines.push("#define ALPHATEST");
  77755. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77756. attribs.push(BABYLON.VertexBuffer.UVKind);
  77757. defines.push("#define UV1");
  77758. }
  77759. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77760. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77761. defines.push("#define UV2");
  77762. }
  77763. }
  77764. // Bones
  77765. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77766. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77767. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77768. if (mesh.numBoneInfluencers > 4) {
  77769. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77770. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77771. }
  77772. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77773. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77774. }
  77775. else {
  77776. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77777. }
  77778. // Instances
  77779. if (useInstances) {
  77780. defines.push("#define INSTANCES");
  77781. attribs.push("world0");
  77782. attribs.push("world1");
  77783. attribs.push("world2");
  77784. attribs.push("world3");
  77785. }
  77786. // Get correct effect
  77787. var join = defines.join("\n");
  77788. if (this._cachedDefines !== join) {
  77789. this._cachedDefines = join;
  77790. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  77791. }
  77792. return this._effect.isReady();
  77793. };
  77794. /**
  77795. * Gets the texture which the depth map will be written to.
  77796. * @returns The depth map texture
  77797. */
  77798. DepthRenderer.prototype.getDepthMap = function () {
  77799. return this._depthMap;
  77800. };
  77801. /**
  77802. * Disposes of the depth renderer.
  77803. */
  77804. DepthRenderer.prototype.dispose = function () {
  77805. this._depthMap.dispose();
  77806. };
  77807. return DepthRenderer;
  77808. }());
  77809. BABYLON.DepthRenderer = DepthRenderer;
  77810. })(BABYLON || (BABYLON = {}));
  77811. //# sourceMappingURL=babylon.depthRenderer.js.map
  77812. var BABYLON;
  77813. (function (BABYLON) {
  77814. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  77815. camera = camera || this.activeCamera;
  77816. if (!camera) {
  77817. throw "No camera available to enable depth renderer";
  77818. }
  77819. if (!this._depthRenderer) {
  77820. this._depthRenderer = {};
  77821. }
  77822. if (!this._depthRenderer[camera.id]) {
  77823. var textureType = 0;
  77824. if (this.getEngine().getCaps().textureHalfFloatRender) {
  77825. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77826. }
  77827. else if (this.getEngine().getCaps().textureFloatRender) {
  77828. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77829. }
  77830. else {
  77831. throw "Depth renderer does not support int texture type";
  77832. }
  77833. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  77834. }
  77835. return this._depthRenderer[camera.id];
  77836. };
  77837. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  77838. camera = camera || this.activeCamera;
  77839. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  77840. return;
  77841. }
  77842. this._depthRenderer[camera.id].dispose();
  77843. delete this._depthRenderer[camera.id];
  77844. };
  77845. /**
  77846. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  77847. * in several rendering techniques.
  77848. */
  77849. var DepthRendererSceneComponent = /** @class */ (function () {
  77850. /**
  77851. * Creates a new instance of the component for the given scene
  77852. * @param scene Defines the scene to register the component in
  77853. */
  77854. function DepthRendererSceneComponent(scene) {
  77855. /**
  77856. * The component name helpfull to identify the component in the list of scene components.
  77857. */
  77858. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  77859. this.scene = scene;
  77860. }
  77861. /**
  77862. * Registers the component in a given scene
  77863. */
  77864. DepthRendererSceneComponent.prototype.register = function () {
  77865. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  77866. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  77867. };
  77868. /**
  77869. * Rebuilds the elements related to this component in case of
  77870. * context lost for instance.
  77871. */
  77872. DepthRendererSceneComponent.prototype.rebuild = function () {
  77873. // Nothing to do for this component
  77874. };
  77875. /**
  77876. * Disposes the component and the associated ressources
  77877. */
  77878. DepthRendererSceneComponent.prototype.dispose = function () {
  77879. for (var key in this.scene._depthRenderer) {
  77880. this.scene._depthRenderer[key].dispose();
  77881. }
  77882. };
  77883. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77884. if (this.scene._depthRenderer) {
  77885. for (var key in this.scene._depthRenderer) {
  77886. var depthRenderer = this.scene._depthRenderer[key];
  77887. if (!depthRenderer.useOnlyInActiveCamera) {
  77888. renderTargets.push(depthRenderer.getDepthMap());
  77889. }
  77890. }
  77891. }
  77892. };
  77893. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  77894. if (this.scene._depthRenderer) {
  77895. for (var key in this.scene._depthRenderer) {
  77896. var depthRenderer = this.scene._depthRenderer[key];
  77897. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  77898. renderTargets.push(depthRenderer.getDepthMap());
  77899. }
  77900. }
  77901. }
  77902. };
  77903. return DepthRendererSceneComponent;
  77904. }());
  77905. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  77906. })(BABYLON || (BABYLON = {}));
  77907. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  77908. var BABYLON;
  77909. (function (BABYLON) {
  77910. /**
  77911. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77912. */
  77913. var GeometryBufferRenderer = /** @class */ (function () {
  77914. /**
  77915. * Creates a new G Buffer for the scene
  77916. * @param scene The scene the buffer belongs to
  77917. * @param ratio How big is the buffer related to the main canvas.
  77918. */
  77919. function GeometryBufferRenderer(scene, ratio) {
  77920. if (ratio === void 0) { ratio = 1; }
  77921. this._enablePosition = false;
  77922. this._scene = scene;
  77923. this._ratio = ratio;
  77924. // Register the G Buffer component to the scene.
  77925. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  77926. if (!component) {
  77927. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  77928. scene._addComponent(component);
  77929. }
  77930. // Render target
  77931. this._createRenderTargets();
  77932. }
  77933. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77934. /**
  77935. * Set the render list (meshes to be rendered) used in the G buffer.
  77936. */
  77937. set: function (meshes) {
  77938. this._multiRenderTarget.renderList = meshes;
  77939. },
  77940. enumerable: true,
  77941. configurable: true
  77942. });
  77943. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77944. /**
  77945. * Gets wether or not G buffer are supported by the running hardware.
  77946. * This requires draw buffer supports
  77947. */
  77948. get: function () {
  77949. return this._multiRenderTarget.isSupported;
  77950. },
  77951. enumerable: true,
  77952. configurable: true
  77953. });
  77954. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77955. /**
  77956. * Gets wether or not position are enabled for the G buffer.
  77957. */
  77958. get: function () {
  77959. return this._enablePosition;
  77960. },
  77961. /**
  77962. * Sets wether or not position are enabled for the G buffer.
  77963. */
  77964. set: function (enable) {
  77965. this._enablePosition = enable;
  77966. this.dispose();
  77967. this._createRenderTargets();
  77968. },
  77969. enumerable: true,
  77970. configurable: true
  77971. });
  77972. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77973. /**
  77974. * Gets the scene associated with the buffer.
  77975. */
  77976. get: function () {
  77977. return this._scene;
  77978. },
  77979. enumerable: true,
  77980. configurable: true
  77981. });
  77982. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77983. /**
  77984. * Gets the ratio used by the buffer during its creation.
  77985. * How big is the buffer related to the main canvas.
  77986. */
  77987. get: function () {
  77988. return this._ratio;
  77989. },
  77990. enumerable: true,
  77991. configurable: true
  77992. });
  77993. /**
  77994. * Checks wether everything is ready to render a submesh to the G buffer.
  77995. * @param subMesh the submesh to check readiness for
  77996. * @param useInstances is the mesh drawn using instance or not
  77997. * @returns true if ready otherwise false
  77998. */
  77999. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78000. var material = subMesh.getMaterial();
  78001. if (material && material.disableDepthWrite) {
  78002. return false;
  78003. }
  78004. var defines = [];
  78005. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78006. var mesh = subMesh.getMesh();
  78007. // Alpha test
  78008. if (material && material.needAlphaTesting()) {
  78009. defines.push("#define ALPHATEST");
  78010. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78011. attribs.push(BABYLON.VertexBuffer.UVKind);
  78012. defines.push("#define UV1");
  78013. }
  78014. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78015. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78016. defines.push("#define UV2");
  78017. }
  78018. }
  78019. // Buffers
  78020. if (this._enablePosition) {
  78021. defines.push("#define POSITION");
  78022. }
  78023. // Bones
  78024. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78025. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78026. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78027. if (mesh.numBoneInfluencers > 4) {
  78028. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78029. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78030. }
  78031. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78032. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78033. }
  78034. else {
  78035. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78036. }
  78037. // Instances
  78038. if (useInstances) {
  78039. defines.push("#define INSTANCES");
  78040. attribs.push("world0");
  78041. attribs.push("world1");
  78042. attribs.push("world2");
  78043. attribs.push("world3");
  78044. }
  78045. // Get correct effect
  78046. var join = defines.join("\n");
  78047. if (this._cachedDefines !== join) {
  78048. this._cachedDefines = join;
  78049. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78050. }
  78051. return this._effect.isReady();
  78052. };
  78053. /**
  78054. * Gets the current underlying G Buffer.
  78055. * @returns the buffer
  78056. */
  78057. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78058. return this._multiRenderTarget;
  78059. };
  78060. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78061. /**
  78062. * Gets the number of samples used to render the buffer (anti aliasing).
  78063. */
  78064. get: function () {
  78065. return this._multiRenderTarget.samples;
  78066. },
  78067. /**
  78068. * Sets the number of samples used to render the buffer (anti aliasing).
  78069. */
  78070. set: function (value) {
  78071. this._multiRenderTarget.samples = value;
  78072. },
  78073. enumerable: true,
  78074. configurable: true
  78075. });
  78076. /**
  78077. * Disposes the renderer and frees up associated resources.
  78078. */
  78079. GeometryBufferRenderer.prototype.dispose = function () {
  78080. this.getGBuffer().dispose();
  78081. };
  78082. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78083. var _this = this;
  78084. var engine = this._scene.getEngine();
  78085. var count = this._enablePosition ? 3 : 2;
  78086. 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 });
  78087. if (!this.isSupported) {
  78088. return;
  78089. }
  78090. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78091. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78092. this._multiRenderTarget.refreshRate = 1;
  78093. this._multiRenderTarget.renderParticles = false;
  78094. this._multiRenderTarget.renderList = null;
  78095. // set default depth value to 1.0 (far away)
  78096. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78097. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78098. });
  78099. // Custom render function
  78100. var renderSubMesh = function (subMesh) {
  78101. var mesh = subMesh.getRenderingMesh();
  78102. var scene = _this._scene;
  78103. var engine = scene.getEngine();
  78104. var material = subMesh.getMaterial();
  78105. if (!material) {
  78106. return;
  78107. }
  78108. // Culling
  78109. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78110. // Managing instances
  78111. var batch = mesh._getInstancesRenderList(subMesh._id);
  78112. if (batch.mustReturn) {
  78113. return;
  78114. }
  78115. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78116. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78117. engine.enableEffect(_this._effect);
  78118. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78119. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78120. _this._effect.setMatrix("view", scene.getViewMatrix());
  78121. // Alpha test
  78122. if (material && material.needAlphaTesting()) {
  78123. var alphaTexture = material.getAlphaTestTexture();
  78124. if (alphaTexture) {
  78125. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78126. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78127. }
  78128. }
  78129. // Bones
  78130. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78131. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78132. }
  78133. // Draw
  78134. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78135. }
  78136. };
  78137. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78138. var index;
  78139. if (depthOnlySubMeshes.length) {
  78140. engine.setColorWrite(false);
  78141. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78142. renderSubMesh(depthOnlySubMeshes.data[index]);
  78143. }
  78144. engine.setColorWrite(true);
  78145. }
  78146. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78147. renderSubMesh(opaqueSubMeshes.data[index]);
  78148. }
  78149. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78150. renderSubMesh(alphaTestSubMeshes.data[index]);
  78151. }
  78152. };
  78153. };
  78154. return GeometryBufferRenderer;
  78155. }());
  78156. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78157. })(BABYLON || (BABYLON = {}));
  78158. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78159. var BABYLON;
  78160. (function (BABYLON) {
  78161. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  78162. get: function () {
  78163. this._geometryBufferRenderer;
  78164. },
  78165. set: function (value) {
  78166. if (value && value.isSupported) {
  78167. this._geometryBufferRenderer = value;
  78168. }
  78169. ;
  78170. },
  78171. enumerable: true,
  78172. configurable: true
  78173. });
  78174. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  78175. if (ratio === void 0) { ratio = 1; }
  78176. if (this._geometryBufferRenderer) {
  78177. return this._geometryBufferRenderer;
  78178. }
  78179. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  78180. if (!this._geometryBufferRenderer.isSupported) {
  78181. this._geometryBufferRenderer = null;
  78182. }
  78183. return this._geometryBufferRenderer;
  78184. };
  78185. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  78186. if (!this._geometryBufferRenderer) {
  78187. return;
  78188. }
  78189. this._geometryBufferRenderer.dispose();
  78190. this._geometryBufferRenderer = null;
  78191. };
  78192. /**
  78193. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  78194. * in several rendering techniques.
  78195. */
  78196. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  78197. /**
  78198. * Creates a new instance of the component for the given scene
  78199. * @param scene Defines the scene to register the component in
  78200. */
  78201. function GeometryBufferRendererSceneComponent(scene) {
  78202. /**
  78203. * The component name helpfull to identify the component in the list of scene components.
  78204. */
  78205. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  78206. this.scene = scene;
  78207. }
  78208. /**
  78209. * Registers the component in a given scene
  78210. */
  78211. GeometryBufferRendererSceneComponent.prototype.register = function () {
  78212. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  78213. };
  78214. /**
  78215. * Rebuilds the elements related to this component in case of
  78216. * context lost for instance.
  78217. */
  78218. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  78219. // Nothing to do for this component
  78220. };
  78221. /**
  78222. * Disposes the component and the associated ressources
  78223. */
  78224. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  78225. // Nothing to do for this component
  78226. };
  78227. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78228. if (this.scene._geometryBufferRenderer) {
  78229. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  78230. }
  78231. };
  78232. return GeometryBufferRendererSceneComponent;
  78233. }());
  78234. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  78235. })(BABYLON || (BABYLON = {}));
  78236. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  78237. var BABYLON;
  78238. (function (BABYLON) {
  78239. var SSAORenderingPipeline = /** @class */ (function (_super) {
  78240. __extends(SSAORenderingPipeline, _super);
  78241. /**
  78242. * @constructor
  78243. * @param {string} name - The rendering pipeline name
  78244. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78245. * @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 }
  78246. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78247. */
  78248. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  78249. var _this = _super.call(this, scene.getEngine(), name) || this;
  78250. // Members
  78251. /**
  78252. * The PassPostProcess id in the pipeline that contains the original scene color
  78253. */
  78254. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78255. /**
  78256. * The SSAO PostProcess id in the pipeline
  78257. */
  78258. _this.SSAORenderEffect = "SSAORenderEffect";
  78259. /**
  78260. * The horizontal blur PostProcess id in the pipeline
  78261. */
  78262. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78263. /**
  78264. * The vertical blur PostProcess id in the pipeline
  78265. */
  78266. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78267. /**
  78268. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78269. */
  78270. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78271. /**
  78272. * The output strength of the SSAO post-process. Default value is 1.0.
  78273. */
  78274. _this.totalStrength = 1.0;
  78275. /**
  78276. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  78277. */
  78278. _this.radius = 0.0001;
  78279. /**
  78280. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  78281. * Must not be equal to fallOff and superior to fallOff.
  78282. * Default value is 0.975
  78283. */
  78284. _this.area = 0.0075;
  78285. /**
  78286. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  78287. * Must not be equal to area and inferior to area.
  78288. * Default value is 0.0
  78289. */
  78290. _this.fallOff = 0.000001;
  78291. /**
  78292. * The base color of the SSAO post-process
  78293. * The final result is "base + ssao" between [0, 1]
  78294. */
  78295. _this.base = 0.5;
  78296. _this._firstUpdate = true;
  78297. _this._scene = scene;
  78298. // Set up assets
  78299. _this._createRandomTexture();
  78300. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78301. var ssaoRatio = ratio.ssaoRatio || ratio;
  78302. var combineRatio = ratio.combineRatio || ratio;
  78303. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78304. _this._createSSAOPostProcess(ssaoRatio);
  78305. _this._createBlurPostProcess(ssaoRatio);
  78306. _this._createSSAOCombinePostProcess(combineRatio);
  78307. // Set up pipeline
  78308. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78309. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78310. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78311. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78312. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78313. // Finish
  78314. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78315. if (cameras)
  78316. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78317. return _this;
  78318. }
  78319. // Public Methods
  78320. /**
  78321. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78322. */
  78323. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78324. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78325. for (var i = 0; i < this._scene.cameras.length; i++) {
  78326. var camera = this._scene.cameras[i];
  78327. this._originalColorPostProcess.dispose(camera);
  78328. this._ssaoPostProcess.dispose(camera);
  78329. this._blurHPostProcess.dispose(camera);
  78330. this._blurVPostProcess.dispose(camera);
  78331. this._ssaoCombinePostProcess.dispose(camera);
  78332. }
  78333. this._randomTexture.dispose();
  78334. if (disableDepthRender)
  78335. this._scene.disableDepthRenderer();
  78336. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78337. _super.prototype.dispose.call(this);
  78338. };
  78339. // Private Methods
  78340. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  78341. var _this = this;
  78342. var size = 16;
  78343. 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);
  78344. 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);
  78345. this._blurHPostProcess.onActivateObservable.add(function () {
  78346. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  78347. _this._blurHPostProcess.kernel = size * dw;
  78348. });
  78349. this._blurVPostProcess.onActivateObservable.add(function () {
  78350. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  78351. _this._blurVPostProcess.kernel = size * dw;
  78352. });
  78353. };
  78354. /** @hidden */
  78355. SSAORenderingPipeline.prototype._rebuild = function () {
  78356. this._firstUpdate = true;
  78357. _super.prototype._rebuild.call(this);
  78358. };
  78359. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78360. var _this = this;
  78361. var numSamples = 16;
  78362. var sampleSphere = [
  78363. 0.5381, 0.1856, -0.4319,
  78364. 0.1379, 0.2486, 0.4430,
  78365. 0.3371, 0.5679, -0.0057,
  78366. -0.6999, -0.0451, -0.0019,
  78367. 0.0689, -0.1598, -0.8547,
  78368. 0.0560, 0.0069, -0.1843,
  78369. -0.0146, 0.1402, 0.0762,
  78370. 0.0100, -0.1924, -0.0344,
  78371. -0.3577, -0.5301, -0.4358,
  78372. -0.3169, 0.1063, 0.0158,
  78373. 0.0103, -0.5869, 0.0046,
  78374. -0.0897, -0.4940, 0.3287,
  78375. 0.7119, -0.0154, -0.0918,
  78376. -0.0533, 0.0596, -0.5411,
  78377. 0.0352, -0.0631, 0.5460,
  78378. -0.4776, 0.2847, -0.0271
  78379. ];
  78380. var samplesFactor = 1.0 / numSamples;
  78381. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  78382. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78383. "area", "fallOff", "base", "range", "viewport"
  78384. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78385. this._ssaoPostProcess.onApply = function (effect) {
  78386. if (_this._firstUpdate) {
  78387. effect.setArray3("sampleSphere", sampleSphere);
  78388. effect.setFloat("samplesFactor", samplesFactor);
  78389. effect.setFloat("randTextureTiles", 4.0);
  78390. }
  78391. effect.setFloat("totalStrength", _this.totalStrength);
  78392. effect.setFloat("radius", _this.radius);
  78393. effect.setFloat("area", _this.area);
  78394. effect.setFloat("fallOff", _this.fallOff);
  78395. effect.setFloat("base", _this.base);
  78396. effect.setTexture("textureSampler", _this._depthTexture);
  78397. effect.setTexture("randomSampler", _this._randomTexture);
  78398. };
  78399. };
  78400. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78401. var _this = this;
  78402. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78403. this._ssaoCombinePostProcess.onApply = function (effect) {
  78404. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  78405. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78406. };
  78407. };
  78408. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  78409. var size = 512;
  78410. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78411. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78412. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78413. var context = this._randomTexture.getContext();
  78414. var rand = function (min, max) {
  78415. return Math.random() * (max - min) + min;
  78416. };
  78417. var randVector = BABYLON.Vector3.Zero();
  78418. for (var x = 0; x < size; x++) {
  78419. for (var y = 0; y < size; y++) {
  78420. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  78421. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  78422. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  78423. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78424. context.fillRect(x, y, 1, 1);
  78425. }
  78426. }
  78427. this._randomTexture.update(false);
  78428. };
  78429. __decorate([
  78430. BABYLON.serialize()
  78431. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  78432. __decorate([
  78433. BABYLON.serialize()
  78434. ], SSAORenderingPipeline.prototype, "radius", void 0);
  78435. __decorate([
  78436. BABYLON.serialize()
  78437. ], SSAORenderingPipeline.prototype, "area", void 0);
  78438. __decorate([
  78439. BABYLON.serialize()
  78440. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  78441. __decorate([
  78442. BABYLON.serialize()
  78443. ], SSAORenderingPipeline.prototype, "base", void 0);
  78444. return SSAORenderingPipeline;
  78445. }(BABYLON.PostProcessRenderPipeline));
  78446. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  78447. })(BABYLON || (BABYLON = {}));
  78448. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  78449. var BABYLON;
  78450. (function (BABYLON) {
  78451. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  78452. __extends(SSAO2RenderingPipeline, _super);
  78453. /**
  78454. * @constructor
  78455. * @param {string} name - The rendering pipeline name
  78456. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78457. * @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 }
  78458. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78459. */
  78460. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  78461. var _this = _super.call(this, scene.getEngine(), name) || this;
  78462. // Members
  78463. /**
  78464. * The PassPostProcess id in the pipeline that contains the original scene color
  78465. */
  78466. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78467. /**
  78468. * The SSAO PostProcess id in the pipeline
  78469. */
  78470. _this.SSAORenderEffect = "SSAORenderEffect";
  78471. /**
  78472. * The horizontal blur PostProcess id in the pipeline
  78473. */
  78474. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78475. /**
  78476. * The vertical blur PostProcess id in the pipeline
  78477. */
  78478. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78479. /**
  78480. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78481. */
  78482. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78483. /**
  78484. * The output strength of the SSAO post-process. Default value is 1.0.
  78485. */
  78486. _this.totalStrength = 1.0;
  78487. /**
  78488. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  78489. */
  78490. _this.maxZ = 100.0;
  78491. /**
  78492. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  78493. */
  78494. _this.minZAspect = 0.2;
  78495. _this._samples = 8;
  78496. _this._textureSamples = 1;
  78497. /**
  78498. * Are we using bilateral blur ?
  78499. */
  78500. _this._expensiveBlur = true;
  78501. /**
  78502. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  78503. */
  78504. _this.radius = 2.0;
  78505. /**
  78506. * The base color of the SSAO post-process
  78507. * The final result is "base + ssao" between [0, 1]
  78508. */
  78509. _this.base = 0;
  78510. _this._firstUpdate = true;
  78511. _this._bits = new Uint32Array(1);
  78512. _this._scene = scene;
  78513. _this._ratio = ratio;
  78514. if (!_this.isSupported) {
  78515. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  78516. return _this;
  78517. }
  78518. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  78519. var blurRatio = _this._ratio.blurRatio || ratio;
  78520. // Set up assets
  78521. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  78522. _this._createRandomTexture();
  78523. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  78524. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  78525. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78526. _this._originalColorPostProcess.samples = _this.textureSamples;
  78527. _this._createSSAOPostProcess(1.0);
  78528. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  78529. _this._createSSAOCombinePostProcess(blurRatio);
  78530. // Set up pipeline
  78531. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78532. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78533. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78534. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78535. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78536. // Finish
  78537. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78538. if (cameras)
  78539. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78540. return _this;
  78541. }
  78542. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  78543. get: function () {
  78544. return this._samples;
  78545. },
  78546. /**
  78547. * Number of samples used for the SSAO calculations. Default value is 8
  78548. */
  78549. set: function (n) {
  78550. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  78551. this._samples = n;
  78552. this._sampleSphere = this._generateHemisphere();
  78553. this._firstUpdate = true;
  78554. },
  78555. enumerable: true,
  78556. configurable: true
  78557. });
  78558. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  78559. get: function () {
  78560. return this._textureSamples;
  78561. },
  78562. /**
  78563. * Number of samples to use for antialiasing
  78564. */
  78565. set: function (n) {
  78566. this._textureSamples = n;
  78567. this._originalColorPostProcess.samples = n;
  78568. this._blurHPostProcess.samples = n;
  78569. this._blurVPostProcess.samples = n;
  78570. this._ssaoPostProcess.samples = n;
  78571. this._ssaoCombinePostProcess.samples = n;
  78572. },
  78573. enumerable: true,
  78574. configurable: true
  78575. });
  78576. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  78577. get: function () {
  78578. return this._expensiveBlur;
  78579. },
  78580. set: function (b) {
  78581. 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"]);
  78582. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  78583. this._expensiveBlur = b;
  78584. this._firstUpdate = true;
  78585. },
  78586. enumerable: true,
  78587. configurable: true
  78588. });
  78589. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  78590. /**
  78591. * Support test.
  78592. */
  78593. get: function () {
  78594. var engine = BABYLON.Engine.LastCreatedEngine;
  78595. if (!engine) {
  78596. return false;
  78597. }
  78598. return engine.getCaps().drawBuffersExtension;
  78599. },
  78600. enumerable: true,
  78601. configurable: true
  78602. });
  78603. // Public Methods
  78604. /**
  78605. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78606. */
  78607. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  78608. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  78609. for (var i = 0; i < this._scene.cameras.length; i++) {
  78610. var camera = this._scene.cameras[i];
  78611. this._originalColorPostProcess.dispose(camera);
  78612. this._ssaoPostProcess.dispose(camera);
  78613. this._blurHPostProcess.dispose(camera);
  78614. this._blurVPostProcess.dispose(camera);
  78615. this._ssaoCombinePostProcess.dispose(camera);
  78616. }
  78617. this._randomTexture.dispose();
  78618. if (disableGeometryBufferRenderer)
  78619. this._scene.disableGeometryBufferRenderer();
  78620. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78621. _super.prototype.dispose.call(this);
  78622. };
  78623. // Private Methods
  78624. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  78625. var _this = this;
  78626. this._samplerOffsets = [];
  78627. var expensive = this.expensiveBlur;
  78628. for (var i = -8; i < 8; i++) {
  78629. this._samplerOffsets.push(i * 2 + 0.5);
  78630. }
  78631. 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");
  78632. this._blurHPostProcess.onApply = function (effect) {
  78633. if (!_this._scene.activeCamera) {
  78634. return;
  78635. }
  78636. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  78637. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78638. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78639. effect.setFloat("radius", _this.radius);
  78640. effect.setTexture("depthSampler", _this._depthTexture);
  78641. if (_this._firstUpdate) {
  78642. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78643. }
  78644. };
  78645. 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");
  78646. this._blurVPostProcess.onApply = function (effect) {
  78647. if (!_this._scene.activeCamera) {
  78648. return;
  78649. }
  78650. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  78651. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78652. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78653. effect.setFloat("radius", _this.radius);
  78654. effect.setTexture("depthSampler", _this._depthTexture);
  78655. if (_this._firstUpdate) {
  78656. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78657. _this._firstUpdate = false;
  78658. }
  78659. };
  78660. this._blurHPostProcess.samples = this.textureSamples;
  78661. this._blurVPostProcess.samples = this.textureSamples;
  78662. };
  78663. /** @hidden */
  78664. SSAO2RenderingPipeline.prototype._rebuild = function () {
  78665. this._firstUpdate = true;
  78666. _super.prototype._rebuild.call(this);
  78667. };
  78668. //Van der Corput radical inverse
  78669. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  78670. this._bits[0] = i;
  78671. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  78672. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  78673. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  78674. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  78675. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  78676. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  78677. };
  78678. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  78679. return [i / n, this._radicalInverse_VdC(i)];
  78680. };
  78681. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  78682. var phi = v * 2.0 * Math.PI;
  78683. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  78684. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  78685. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  78686. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  78687. };
  78688. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  78689. var numSamples = this.samples;
  78690. var result = [];
  78691. var vector;
  78692. var i = 0;
  78693. while (i < numSamples) {
  78694. if (numSamples < 16) {
  78695. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  78696. }
  78697. else {
  78698. var rand = this._hammersley(i, numSamples);
  78699. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  78700. }
  78701. result.push(vector.x, vector.y, vector.z);
  78702. i++;
  78703. }
  78704. return result;
  78705. };
  78706. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78707. var _this = this;
  78708. var numSamples = this.samples;
  78709. this._sampleSphere = this._generateHemisphere();
  78710. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  78711. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78712. "base", "range", "projection", "near", "far", "texelSize",
  78713. "xViewport", "yViewport", "maxZ", "minZAspect"
  78714. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78715. this._ssaoPostProcess.onApply = function (effect) {
  78716. if (_this._firstUpdate) {
  78717. effect.setArray3("sampleSphere", _this._sampleSphere);
  78718. effect.setFloat("randTextureTiles", 32.0);
  78719. }
  78720. if (!_this._scene.activeCamera) {
  78721. return;
  78722. }
  78723. effect.setFloat("samplesFactor", 1 / _this.samples);
  78724. effect.setFloat("totalStrength", _this.totalStrength);
  78725. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  78726. effect.setFloat("radius", _this.radius);
  78727. effect.setFloat("maxZ", _this.maxZ);
  78728. effect.setFloat("minZAspect", _this.minZAspect);
  78729. effect.setFloat("base", _this.base);
  78730. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78731. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78732. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  78733. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  78734. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  78735. effect.setTexture("textureSampler", _this._depthTexture);
  78736. effect.setTexture("normalSampler", _this._normalTexture);
  78737. effect.setTexture("randomSampler", _this._randomTexture);
  78738. };
  78739. this._ssaoPostProcess.samples = this.textureSamples;
  78740. };
  78741. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78742. var _this = this;
  78743. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78744. this._ssaoCombinePostProcess.onApply = function (effect) {
  78745. var viewport = _this._scene.activeCamera.viewport;
  78746. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  78747. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78748. };
  78749. this._ssaoCombinePostProcess.samples = this.textureSamples;
  78750. };
  78751. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  78752. var size = 128;
  78753. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78754. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78755. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78756. var context = this._randomTexture.getContext();
  78757. var rand = function (min, max) {
  78758. return Math.random() * (max - min) + min;
  78759. };
  78760. var randVector = BABYLON.Vector3.Zero();
  78761. for (var x = 0; x < size; x++) {
  78762. for (var y = 0; y < size; y++) {
  78763. randVector.x = rand(0.0, 1.0);
  78764. randVector.y = rand(0.0, 1.0);
  78765. randVector.z = 0.0;
  78766. randVector.normalize();
  78767. randVector.scaleInPlace(255);
  78768. randVector.x = Math.floor(randVector.x);
  78769. randVector.y = Math.floor(randVector.y);
  78770. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78771. context.fillRect(x, y, 1, 1);
  78772. }
  78773. }
  78774. this._randomTexture.update(false);
  78775. };
  78776. /**
  78777. * Serialize the rendering pipeline (Used when exporting)
  78778. * @returns the serialized object
  78779. */
  78780. SSAO2RenderingPipeline.prototype.serialize = function () {
  78781. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78782. serializationObject.customType = "SSAO2RenderingPipeline";
  78783. return serializationObject;
  78784. };
  78785. /**
  78786. * Parse the serialized pipeline
  78787. * @param source Source pipeline.
  78788. * @param scene The scene to load the pipeline to.
  78789. * @param rootUrl The URL of the serialized pipeline.
  78790. * @returns An instantiated pipeline from the serialized object.
  78791. */
  78792. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  78793. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78794. };
  78795. __decorate([
  78796. BABYLON.serialize()
  78797. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  78798. __decorate([
  78799. BABYLON.serialize()
  78800. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  78801. __decorate([
  78802. BABYLON.serialize()
  78803. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  78804. __decorate([
  78805. BABYLON.serialize("samples")
  78806. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  78807. __decorate([
  78808. BABYLON.serialize("textureSamples")
  78809. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  78810. __decorate([
  78811. BABYLON.serialize()
  78812. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  78813. __decorate([
  78814. BABYLON.serialize("expensiveBlur")
  78815. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  78816. __decorate([
  78817. BABYLON.serialize()
  78818. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  78819. __decorate([
  78820. BABYLON.serialize()
  78821. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  78822. return SSAO2RenderingPipeline;
  78823. }(BABYLON.PostProcessRenderPipeline));
  78824. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  78825. })(BABYLON || (BABYLON = {}));
  78826. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  78827. // BABYLON.JS Chromatic Aberration GLSL Shader
  78828. // Author: Olivier Guyot
  78829. // Separates very slightly R, G and B colors on the edges of the screen
  78830. // Inspired by Francois Tarlier & Martins Upitis
  78831. var BABYLON;
  78832. (function (BABYLON) {
  78833. var LensRenderingPipeline = /** @class */ (function (_super) {
  78834. __extends(LensRenderingPipeline, _super);
  78835. /**
  78836. * @constructor
  78837. *
  78838. * Effect parameters are as follow:
  78839. * {
  78840. * chromatic_aberration: number; // from 0 to x (1 for realism)
  78841. * edge_blur: number; // from 0 to x (1 for realism)
  78842. * distortion: number; // from 0 to x (1 for realism)
  78843. * grain_amount: number; // from 0 to 1
  78844. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  78845. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  78846. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  78847. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  78848. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  78849. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  78850. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  78851. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  78852. * }
  78853. * Note: if an effect parameter is unset, effect is disabled
  78854. *
  78855. * @param {string} name - The rendering pipeline name
  78856. * @param {object} parameters - An object containing all parameters (see above)
  78857. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78858. * @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)
  78859. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78860. */
  78861. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  78862. if (ratio === void 0) { ratio = 1.0; }
  78863. var _this = _super.call(this, scene.getEngine(), name) || this;
  78864. // Lens effects can be of the following:
  78865. // - chromatic aberration (slight shift of RGB colors)
  78866. // - blur on the edge of the lens
  78867. // - lens distortion
  78868. // - depth-of-field blur & highlights enhancing
  78869. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  78870. // - grain effect (noise or custom texture)
  78871. // Two additional texture samplers are needed:
  78872. // - depth map (for depth-of-field)
  78873. // - grain texture
  78874. /**
  78875. * The chromatic aberration PostProcess id in the pipeline
  78876. */
  78877. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  78878. /**
  78879. * The highlights enhancing PostProcess id in the pipeline
  78880. */
  78881. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  78882. /**
  78883. * The depth-of-field PostProcess id in the pipeline
  78884. */
  78885. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  78886. _this._scene = scene;
  78887. // Fetch texture samplers
  78888. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78889. if (parameters.grain_texture) {
  78890. _this._grainTexture = parameters.grain_texture;
  78891. }
  78892. else {
  78893. _this._createGrainTexture();
  78894. }
  78895. // save parameters
  78896. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  78897. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  78898. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  78899. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  78900. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  78901. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  78902. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  78903. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  78904. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  78905. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  78906. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  78907. // Create effects
  78908. _this._createChromaticAberrationPostProcess(ratio);
  78909. _this._createHighlightsPostProcess(ratio);
  78910. _this._createDepthOfFieldPostProcess(ratio / 4);
  78911. // Set up pipeline
  78912. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  78913. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  78914. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  78915. if (_this._highlightsGain === -1) {
  78916. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  78917. }
  78918. // Finish
  78919. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78920. if (cameras) {
  78921. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78922. }
  78923. return _this;
  78924. }
  78925. // public methods (self explanatory)
  78926. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  78927. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  78928. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  78929. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  78930. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  78931. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  78932. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  78933. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  78934. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  78935. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  78936. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  78937. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  78938. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  78939. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  78940. };
  78941. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  78942. this._highlightsPostProcess.updateEffect();
  78943. };
  78944. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  78945. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  78946. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  78947. this._highlightsGain = amount;
  78948. };
  78949. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  78950. if (this._highlightsGain === -1) {
  78951. this._highlightsGain = 1.0;
  78952. }
  78953. this._highlightsThreshold = amount;
  78954. };
  78955. LensRenderingPipeline.prototype.disableHighlights = function () {
  78956. this._highlightsGain = -1;
  78957. };
  78958. /**
  78959. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  78960. */
  78961. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78962. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78963. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78964. this._chromaticAberrationPostProcess = null;
  78965. this._highlightsPostProcess = null;
  78966. this._depthOfFieldPostProcess = null;
  78967. this._grainTexture.dispose();
  78968. if (disableDepthRender)
  78969. this._scene.disableDepthRenderer();
  78970. };
  78971. // colors shifting and distortion
  78972. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  78973. var _this = this;
  78974. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  78975. [], // samplers
  78976. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78977. this._chromaticAberrationPostProcess.onApply = function (effect) {
  78978. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  78979. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78980. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78981. effect.setFloat('radialIntensity', 1);
  78982. effect.setFloat2('direction', 17, 17);
  78983. effect.setFloat2('centerPosition', 0.5, 0.5);
  78984. };
  78985. };
  78986. // highlights enhancing
  78987. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  78988. var _this = this;
  78989. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  78990. [], // samplers
  78991. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  78992. this._highlightsPostProcess.onApply = function (effect) {
  78993. effect.setFloat('gain', _this._highlightsGain);
  78994. effect.setFloat('threshold', _this._highlightsThreshold);
  78995. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  78996. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78997. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78998. };
  78999. };
  79000. // colors shifting and distortion
  79001. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  79002. var _this = this;
  79003. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  79004. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  79005. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  79006. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79007. this._depthOfFieldPostProcess.onApply = function (effect) {
  79008. effect.setTexture("depthSampler", _this._depthTexture);
  79009. effect.setTexture("grainSampler", _this._grainTexture);
  79010. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  79011. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  79012. effect.setFloat('grain_amount', _this._grainAmount);
  79013. effect.setBool('blur_noise', _this._blurNoise);
  79014. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79015. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79016. effect.setFloat('distortion', _this._distortion);
  79017. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  79018. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  79019. effect.setFloat('aperture', _this._dofAperture);
  79020. effect.setFloat('darken', _this._dofDarken);
  79021. effect.setFloat('edge_blur', _this._edgeBlur);
  79022. effect.setBool('highlights', (_this._highlightsGain !== -1));
  79023. if (_this._scene.activeCamera) {
  79024. effect.setFloat('near', _this._scene.activeCamera.minZ);
  79025. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  79026. }
  79027. };
  79028. };
  79029. // creates a black and white random noise texture, 512x512
  79030. LensRenderingPipeline.prototype._createGrainTexture = function () {
  79031. var size = 512;
  79032. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79033. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  79034. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  79035. var context = this._grainTexture.getContext();
  79036. var rand = function (min, max) {
  79037. return Math.random() * (max - min) + min;
  79038. };
  79039. var value;
  79040. for (var x = 0; x < size; x++) {
  79041. for (var y = 0; y < size; y++) {
  79042. value = Math.floor(rand(0.42, 0.58) * 255);
  79043. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  79044. context.fillRect(x, y, 1, 1);
  79045. }
  79046. }
  79047. this._grainTexture.update(false);
  79048. };
  79049. return LensRenderingPipeline;
  79050. }(BABYLON.PostProcessRenderPipeline));
  79051. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  79052. })(BABYLON || (BABYLON = {}));
  79053. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  79054. var BABYLON;
  79055. (function (BABYLON) {
  79056. var StandardRenderingPipeline = /** @class */ (function (_super) {
  79057. __extends(StandardRenderingPipeline, _super);
  79058. /**
  79059. * @constructor
  79060. * @param {string} name - The rendering pipeline name
  79061. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79062. * @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)
  79063. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  79064. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79065. */
  79066. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  79067. if (originalPostProcess === void 0) { originalPostProcess = null; }
  79068. var _this = _super.call(this, scene.getEngine(), name) || this;
  79069. /**
  79070. * Post-process used to down scale an image x4
  79071. */
  79072. _this.downSampleX4PostProcess = null;
  79073. /**
  79074. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  79075. */
  79076. _this.brightPassPostProcess = null;
  79077. /**
  79078. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  79079. */
  79080. _this.blurHPostProcesses = [];
  79081. /**
  79082. * Post-process array storing all the vertical blur post-processes used by the pipeline
  79083. */
  79084. _this.blurVPostProcesses = [];
  79085. /**
  79086. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  79087. */
  79088. _this.textureAdderPostProcess = null;
  79089. /**
  79090. * Post-process used to create volumetric lighting effect
  79091. */
  79092. _this.volumetricLightPostProcess = null;
  79093. /**
  79094. * Post-process used to smooth the previous volumetric light post-process on the X axis
  79095. */
  79096. _this.volumetricLightSmoothXPostProcess = null;
  79097. /**
  79098. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  79099. */
  79100. _this.volumetricLightSmoothYPostProcess = null;
  79101. /**
  79102. * Post-process used to merge the volumetric light effect and the real scene color
  79103. */
  79104. _this.volumetricLightMergePostProces = null;
  79105. /**
  79106. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  79107. */
  79108. _this.volumetricLightFinalPostProcess = null;
  79109. /**
  79110. * Base post-process used to calculate the average luminance of the final image for HDR
  79111. */
  79112. _this.luminancePostProcess = null;
  79113. /**
  79114. * Post-processes used to create down sample post-processes in order to get
  79115. * the average luminance of the final image for HDR
  79116. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  79117. */
  79118. _this.luminanceDownSamplePostProcesses = [];
  79119. /**
  79120. * Post-process used to create a HDR effect (light adaptation)
  79121. */
  79122. _this.hdrPostProcess = null;
  79123. /**
  79124. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  79125. */
  79126. _this.textureAdderFinalPostProcess = null;
  79127. /**
  79128. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  79129. */
  79130. _this.lensFlareFinalPostProcess = null;
  79131. /**
  79132. * Post-process used to merge the final HDR post-process and the real scene color
  79133. */
  79134. _this.hdrFinalPostProcess = null;
  79135. /**
  79136. * Post-process used to create a lens flare effect
  79137. */
  79138. _this.lensFlarePostProcess = null;
  79139. /**
  79140. * Post-process that merges the result of the lens flare post-process and the real scene color
  79141. */
  79142. _this.lensFlareComposePostProcess = null;
  79143. /**
  79144. * Post-process used to create a motion blur effect
  79145. */
  79146. _this.motionBlurPostProcess = null;
  79147. /**
  79148. * Post-process used to create a depth of field effect
  79149. */
  79150. _this.depthOfFieldPostProcess = null;
  79151. /**
  79152. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  79153. */
  79154. _this.fxaaPostProcess = null;
  79155. // Values
  79156. /**
  79157. * Represents the brightness threshold in order to configure the illuminated surfaces
  79158. */
  79159. _this.brightThreshold = 1.0;
  79160. /**
  79161. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  79162. */
  79163. _this.blurWidth = 512.0;
  79164. /**
  79165. * Sets if the blur for highlighted surfaces must be only horizontal
  79166. */
  79167. _this.horizontalBlur = false;
  79168. /**
  79169. * Sets the overall exposure used by the pipeline
  79170. */
  79171. _this.exposure = 1.0;
  79172. /**
  79173. * Texture used typically to simulate "dirty" on camera lens
  79174. */
  79175. _this.lensTexture = null;
  79176. /**
  79177. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  79178. */
  79179. _this.volumetricLightCoefficient = 0.2;
  79180. /**
  79181. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  79182. */
  79183. _this.volumetricLightPower = 4.0;
  79184. /**
  79185. * Used the set the blur intensity to smooth the volumetric lights
  79186. */
  79187. _this.volumetricLightBlurScale = 64.0;
  79188. /**
  79189. * Light (spot or directional) used to generate the volumetric lights rays
  79190. * The source light must have a shadow generate so the pipeline can get its
  79191. * depth map
  79192. */
  79193. _this.sourceLight = null;
  79194. /**
  79195. * For eye adaptation, represents the minimum luminance the eye can see
  79196. */
  79197. _this.hdrMinimumLuminance = 1.0;
  79198. /**
  79199. * For eye adaptation, represents the decrease luminance speed
  79200. */
  79201. _this.hdrDecreaseRate = 0.5;
  79202. /**
  79203. * For eye adaptation, represents the increase luminance speed
  79204. */
  79205. _this.hdrIncreaseRate = 0.5;
  79206. /**
  79207. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  79208. */
  79209. _this.lensColorTexture = null;
  79210. /**
  79211. * The overall strengh for the lens flare effect
  79212. */
  79213. _this.lensFlareStrength = 20.0;
  79214. /**
  79215. * Dispersion coefficient for lens flare ghosts
  79216. */
  79217. _this.lensFlareGhostDispersal = 1.4;
  79218. /**
  79219. * Main lens flare halo width
  79220. */
  79221. _this.lensFlareHaloWidth = 0.7;
  79222. /**
  79223. * Based on the lens distortion effect, defines how much the lens flare result
  79224. * is distorted
  79225. */
  79226. _this.lensFlareDistortionStrength = 16.0;
  79227. /**
  79228. * Lens star texture must be used to simulate rays on the flares and is available
  79229. * in the documentation
  79230. */
  79231. _this.lensStarTexture = null;
  79232. /**
  79233. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  79234. * flare effect by taking account of the dirt texture
  79235. */
  79236. _this.lensFlareDirtTexture = null;
  79237. /**
  79238. * Represents the focal length for the depth of field effect
  79239. */
  79240. _this.depthOfFieldDistance = 10.0;
  79241. /**
  79242. * Represents the blur intensity for the blurred part of the depth of field effect
  79243. */
  79244. _this.depthOfFieldBlurWidth = 64.0;
  79245. /**
  79246. * For motion blur, defines how much the image is blurred by the movement
  79247. */
  79248. _this.motionStrength = 1.0;
  79249. /**
  79250. * List of animations for the pipeline (IAnimatable implementation)
  79251. */
  79252. _this.animations = [];
  79253. _this._currentDepthOfFieldSource = null;
  79254. _this._hdrCurrentLuminance = 1.0;
  79255. // Getters and setters
  79256. _this._bloomEnabled = false;
  79257. _this._depthOfFieldEnabled = false;
  79258. _this._vlsEnabled = false;
  79259. _this._lensFlareEnabled = false;
  79260. _this._hdrEnabled = false;
  79261. _this._motionBlurEnabled = false;
  79262. _this._fxaaEnabled = false;
  79263. _this._motionBlurSamples = 64.0;
  79264. _this._volumetricLightStepsCount = 50.0;
  79265. _this._samples = 1;
  79266. _this._cameras = cameras || [];
  79267. // Initialize
  79268. _this._scene = scene;
  79269. _this._basePostProcess = originalPostProcess;
  79270. _this._ratio = ratio;
  79271. // Misc
  79272. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79273. // Finish
  79274. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79275. _this._buildPipeline();
  79276. return _this;
  79277. }
  79278. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  79279. /**
  79280. * Specifies if the bloom pipeline is enabled
  79281. */
  79282. get: function () {
  79283. return this._bloomEnabled;
  79284. },
  79285. set: function (enabled) {
  79286. if (this._bloomEnabled === enabled) {
  79287. return;
  79288. }
  79289. this._bloomEnabled = enabled;
  79290. this._buildPipeline();
  79291. },
  79292. enumerable: true,
  79293. configurable: true
  79294. });
  79295. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  79296. /**
  79297. * Specifies if the depth of field pipeline is enabed
  79298. */
  79299. get: function () {
  79300. return this._depthOfFieldEnabled;
  79301. },
  79302. set: function (enabled) {
  79303. if (this._depthOfFieldEnabled === enabled) {
  79304. return;
  79305. }
  79306. this._depthOfFieldEnabled = enabled;
  79307. this._buildPipeline();
  79308. },
  79309. enumerable: true,
  79310. configurable: true
  79311. });
  79312. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  79313. /**
  79314. * Specifies if the lens flare pipeline is enabed
  79315. */
  79316. get: function () {
  79317. return this._lensFlareEnabled;
  79318. },
  79319. set: function (enabled) {
  79320. if (this._lensFlareEnabled === enabled) {
  79321. return;
  79322. }
  79323. this._lensFlareEnabled = enabled;
  79324. this._buildPipeline();
  79325. },
  79326. enumerable: true,
  79327. configurable: true
  79328. });
  79329. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  79330. /**
  79331. * Specifies if the HDR pipeline is enabled
  79332. */
  79333. get: function () {
  79334. return this._hdrEnabled;
  79335. },
  79336. set: function (enabled) {
  79337. if (this._hdrEnabled === enabled) {
  79338. return;
  79339. }
  79340. this._hdrEnabled = enabled;
  79341. this._buildPipeline();
  79342. },
  79343. enumerable: true,
  79344. configurable: true
  79345. });
  79346. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  79347. /**
  79348. * Specifies if the volumetric lights scattering effect is enabled
  79349. */
  79350. get: function () {
  79351. return this._vlsEnabled;
  79352. },
  79353. set: function (enabled) {
  79354. if (this._vlsEnabled === enabled) {
  79355. return;
  79356. }
  79357. if (enabled) {
  79358. var geometry = this._scene.enableGeometryBufferRenderer();
  79359. if (!geometry) {
  79360. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  79361. return;
  79362. }
  79363. }
  79364. this._vlsEnabled = enabled;
  79365. this._buildPipeline();
  79366. },
  79367. enumerable: true,
  79368. configurable: true
  79369. });
  79370. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  79371. /**
  79372. * Specifies if the motion blur effect is enabled
  79373. */
  79374. get: function () {
  79375. return this._motionBlurEnabled;
  79376. },
  79377. set: function (enabled) {
  79378. if (this._motionBlurEnabled === enabled) {
  79379. return;
  79380. }
  79381. this._motionBlurEnabled = enabled;
  79382. this._buildPipeline();
  79383. },
  79384. enumerable: true,
  79385. configurable: true
  79386. });
  79387. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  79388. /**
  79389. * Specifies if anti-aliasing is enabled
  79390. */
  79391. get: function () {
  79392. return this._fxaaEnabled;
  79393. },
  79394. set: function (enabled) {
  79395. if (this._fxaaEnabled === enabled) {
  79396. return;
  79397. }
  79398. this._fxaaEnabled = enabled;
  79399. this._buildPipeline();
  79400. },
  79401. enumerable: true,
  79402. configurable: true
  79403. });
  79404. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  79405. /**
  79406. * Specifies the number of steps used to calculate the volumetric lights
  79407. * Typically in interval [50, 200]
  79408. */
  79409. get: function () {
  79410. return this._volumetricLightStepsCount;
  79411. },
  79412. set: function (count) {
  79413. if (this.volumetricLightPostProcess) {
  79414. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  79415. }
  79416. this._volumetricLightStepsCount = count;
  79417. },
  79418. enumerable: true,
  79419. configurable: true
  79420. });
  79421. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  79422. /**
  79423. * Specifies the number of samples used for the motion blur effect
  79424. * Typically in interval [16, 64]
  79425. */
  79426. get: function () {
  79427. return this._motionBlurSamples;
  79428. },
  79429. set: function (samples) {
  79430. if (this.motionBlurPostProcess) {
  79431. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  79432. }
  79433. this._motionBlurSamples = samples;
  79434. },
  79435. enumerable: true,
  79436. configurable: true
  79437. });
  79438. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  79439. /**
  79440. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79441. */
  79442. get: function () {
  79443. return this._samples;
  79444. },
  79445. set: function (sampleCount) {
  79446. if (this._samples === sampleCount) {
  79447. return;
  79448. }
  79449. this._samples = sampleCount;
  79450. this._buildPipeline();
  79451. },
  79452. enumerable: true,
  79453. configurable: true
  79454. });
  79455. StandardRenderingPipeline.prototype._buildPipeline = function () {
  79456. var _this = this;
  79457. var ratio = this._ratio;
  79458. var scene = this._scene;
  79459. this._disposePostProcesses();
  79460. this._reset();
  79461. // Create pass post-process
  79462. if (!this._basePostProcess) {
  79463. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  79464. this.originalPostProcess.onApply = function (effect) {
  79465. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  79466. };
  79467. }
  79468. else {
  79469. this.originalPostProcess = this._basePostProcess;
  79470. }
  79471. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  79472. this._currentDepthOfFieldSource = this.originalPostProcess;
  79473. if (this._bloomEnabled) {
  79474. // Create down sample X4 post-process
  79475. this._createDownSampleX4PostProcess(scene, ratio / 2);
  79476. // Create bright pass post-process
  79477. this._createBrightPassPostProcess(scene, ratio / 2);
  79478. // Create gaussian blur post-processes (down sampling blurs)
  79479. this._createBlurPostProcesses(scene, ratio / 4, 1);
  79480. // Create texture adder post-process
  79481. this._createTextureAdderPostProcess(scene, ratio);
  79482. // Create depth-of-field source post-process
  79483. 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);
  79484. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  79485. }
  79486. if (this._vlsEnabled) {
  79487. // Create volumetric light
  79488. this._createVolumetricLightPostProcess(scene, ratio);
  79489. // Create volumetric light final post-process
  79490. 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);
  79491. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  79492. }
  79493. if (this._lensFlareEnabled) {
  79494. // Create lens flare post-process
  79495. this._createLensFlarePostProcess(scene, ratio);
  79496. // Create depth-of-field source post-process post lens-flare and disable it now
  79497. 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);
  79498. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  79499. }
  79500. if (this._hdrEnabled) {
  79501. // Create luminance
  79502. this._createLuminancePostProcesses(scene, this._floatTextureType);
  79503. // Create HDR
  79504. this._createHdrPostProcess(scene, ratio);
  79505. // Create depth-of-field source post-process post hdr and disable it now
  79506. 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);
  79507. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  79508. }
  79509. if (this._depthOfFieldEnabled) {
  79510. // Create gaussian blur used by depth-of-field
  79511. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  79512. // Create depth-of-field post-process
  79513. this._createDepthOfFieldPostProcess(scene, ratio);
  79514. }
  79515. if (this._motionBlurEnabled) {
  79516. // Create motion blur post-process
  79517. this._createMotionBlurPostProcess(scene, ratio);
  79518. }
  79519. if (this._fxaaEnabled) {
  79520. // Create fxaa post-process
  79521. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79522. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  79523. }
  79524. if (this._cameras !== null) {
  79525. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79526. }
  79527. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  79528. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79529. }
  79530. };
  79531. // Down Sample X4 Post-Processs
  79532. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  79533. var _this = this;
  79534. var downSampleX4Offsets = new Array(32);
  79535. 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);
  79536. this.downSampleX4PostProcess.onApply = function (effect) {
  79537. var id = 0;
  79538. var width = _this.downSampleX4PostProcess.width;
  79539. var height = _this.downSampleX4PostProcess.height;
  79540. for (var i = -2; i < 2; i++) {
  79541. for (var j = -2; j < 2; j++) {
  79542. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  79543. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  79544. id += 2;
  79545. }
  79546. }
  79547. effect.setArray2("dsOffsets", downSampleX4Offsets);
  79548. };
  79549. // Add to pipeline
  79550. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  79551. };
  79552. // Brightpass Post-Process
  79553. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  79554. var _this = this;
  79555. var brightOffsets = new Array(8);
  79556. 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);
  79557. this.brightPassPostProcess.onApply = function (effect) {
  79558. var sU = (1.0 / _this.brightPassPostProcess.width);
  79559. var sV = (1.0 / _this.brightPassPostProcess.height);
  79560. brightOffsets[0] = -0.5 * sU;
  79561. brightOffsets[1] = 0.5 * sV;
  79562. brightOffsets[2] = 0.5 * sU;
  79563. brightOffsets[3] = 0.5 * sV;
  79564. brightOffsets[4] = -0.5 * sU;
  79565. brightOffsets[5] = -0.5 * sV;
  79566. brightOffsets[6] = 0.5 * sU;
  79567. brightOffsets[7] = -0.5 * sV;
  79568. effect.setArray2("dsOffsets", brightOffsets);
  79569. effect.setFloat("brightThreshold", _this.brightThreshold);
  79570. };
  79571. // Add to pipeline
  79572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  79573. };
  79574. // Create blur H&V post-processes
  79575. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  79576. var _this = this;
  79577. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  79578. var engine = scene.getEngine();
  79579. 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);
  79580. 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);
  79581. blurX.onActivateObservable.add(function () {
  79582. var dw = blurX.width / engine.getRenderWidth();
  79583. blurX.kernel = _this[blurWidthKey] * dw;
  79584. });
  79585. blurY.onActivateObservable.add(function () {
  79586. var dw = blurY.height / engine.getRenderHeight();
  79587. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  79588. });
  79589. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  79590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  79591. this.blurHPostProcesses.push(blurX);
  79592. this.blurVPostProcesses.push(blurY);
  79593. };
  79594. // Create texture adder post-process
  79595. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  79596. var _this = this;
  79597. 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);
  79598. this.textureAdderPostProcess.onApply = function (effect) {
  79599. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  79600. effect.setTexture("lensSampler", _this.lensTexture);
  79601. effect.setFloat("exposure", _this.exposure);
  79602. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  79603. };
  79604. // Add to pipeline
  79605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  79606. };
  79607. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  79608. var _this = this;
  79609. var geometryRenderer = scene.enableGeometryBufferRenderer();
  79610. geometryRenderer.enablePosition = true;
  79611. var geometry = geometryRenderer.getGBuffer();
  79612. // Base post-process
  79613. 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));
  79614. var depthValues = BABYLON.Vector2.Zero();
  79615. this.volumetricLightPostProcess.onApply = function (effect) {
  79616. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  79617. var generator = _this.sourceLight.getShadowGenerator();
  79618. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  79619. effect.setTexture("positionSampler", geometry.textures[2]);
  79620. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  79621. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  79622. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  79623. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  79624. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  79625. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  79626. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  79627. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  79628. effect.setVector2("depthValues", depthValues);
  79629. }
  79630. };
  79631. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  79632. // Smooth
  79633. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  79634. // Merge
  79635. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  79636. this.volumetricLightMergePostProces.onApply = function (effect) {
  79637. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  79638. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  79639. };
  79640. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  79641. };
  79642. // Create luminance
  79643. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  79644. var _this = this;
  79645. // Create luminance
  79646. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  79647. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  79648. var offsets = [];
  79649. this.luminancePostProcess.onApply = function (effect) {
  79650. var sU = (1.0 / _this.luminancePostProcess.width);
  79651. var sV = (1.0 / _this.luminancePostProcess.height);
  79652. offsets[0] = -0.5 * sU;
  79653. offsets[1] = 0.5 * sV;
  79654. offsets[2] = 0.5 * sU;
  79655. offsets[3] = 0.5 * sV;
  79656. offsets[4] = -0.5 * sU;
  79657. offsets[5] = -0.5 * sV;
  79658. offsets[6] = 0.5 * sU;
  79659. offsets[7] = -0.5 * sV;
  79660. effect.setArray2("lumOffsets", offsets);
  79661. };
  79662. // Add to pipeline
  79663. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  79664. // Create down sample luminance
  79665. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  79666. var size = Math.pow(3, i);
  79667. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  79668. if (i === 0) {
  79669. defines += "#define FINAL_DOWN_SAMPLER";
  79670. }
  79671. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  79672. this.luminanceDownSamplePostProcesses.push(postProcess);
  79673. }
  79674. // Create callbacks and add effects
  79675. var lastLuminance = this.luminancePostProcess;
  79676. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  79677. var downSampleOffsets = new Array(18);
  79678. pp.onApply = function (effect) {
  79679. if (!lastLuminance) {
  79680. return;
  79681. }
  79682. var id = 0;
  79683. for (var x = -1; x < 2; x++) {
  79684. for (var y = -1; y < 2; y++) {
  79685. downSampleOffsets[id] = x / lastLuminance.width;
  79686. downSampleOffsets[id + 1] = y / lastLuminance.height;
  79687. id += 2;
  79688. }
  79689. }
  79690. effect.setArray2("dsOffsets", downSampleOffsets);
  79691. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  79692. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79693. lastLuminance = _this.luminancePostProcess;
  79694. }
  79695. else {
  79696. lastLuminance = pp;
  79697. }
  79698. };
  79699. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79700. pp.onAfterRender = function (effect) {
  79701. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  79702. 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);
  79703. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  79704. };
  79705. }
  79706. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  79707. });
  79708. };
  79709. // Create HDR post-process
  79710. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  79711. var _this = this;
  79712. 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);
  79713. var outputLiminance = 1;
  79714. var time = 0;
  79715. var lastTime = 0;
  79716. this.hdrPostProcess.onApply = function (effect) {
  79717. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  79718. time += scene.getEngine().getDeltaTime();
  79719. if (outputLiminance < 0) {
  79720. outputLiminance = _this._hdrCurrentLuminance;
  79721. }
  79722. else {
  79723. var dt = (lastTime - time) / 1000.0;
  79724. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  79725. outputLiminance += _this.hdrDecreaseRate * dt;
  79726. }
  79727. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  79728. outputLiminance -= _this.hdrIncreaseRate * dt;
  79729. }
  79730. else {
  79731. outputLiminance = _this._hdrCurrentLuminance;
  79732. }
  79733. }
  79734. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  79735. effect.setFloat("averageLuminance", outputLiminance);
  79736. lastTime = time;
  79737. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  79738. };
  79739. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  79740. };
  79741. // Create lens flare post-process
  79742. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  79743. var _this = this;
  79744. 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);
  79745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  79746. this._createBlurPostProcesses(scene, ratio / 4, 2);
  79747. 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);
  79748. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  79749. var resolution = new BABYLON.Vector2(0, 0);
  79750. // Lens flare
  79751. this.lensFlarePostProcess.onApply = function (effect) {
  79752. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  79753. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  79754. effect.setFloat("strength", _this.lensFlareStrength);
  79755. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  79756. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  79757. // Shift
  79758. resolution.x = _this.lensFlarePostProcess.width;
  79759. resolution.y = _this.lensFlarePostProcess.height;
  79760. effect.setVector2("resolution", resolution);
  79761. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  79762. };
  79763. // Compose
  79764. 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);
  79765. 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);
  79766. this.lensFlareComposePostProcess.onApply = function (effect) {
  79767. if (!_this._scene.activeCamera) {
  79768. return;
  79769. }
  79770. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79771. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  79772. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  79773. // Lens start rotation matrix
  79774. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  79775. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  79776. 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));
  79777. camRot *= 4.0;
  79778. 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);
  79779. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  79780. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  79781. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  79782. };
  79783. };
  79784. // Create depth-of-field post-process
  79785. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  79786. var _this = this;
  79787. 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);
  79788. this.depthOfFieldPostProcess.onApply = function (effect) {
  79789. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79790. effect.setTexture("depthSampler", _this._getDepthTexture());
  79791. effect.setFloat("distance", _this.depthOfFieldDistance);
  79792. };
  79793. // Add to pipeline
  79794. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  79795. };
  79796. // Create motion blur post-process
  79797. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  79798. var _this = this;
  79799. 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);
  79800. var motionScale = 0;
  79801. var prevViewProjection = BABYLON.Matrix.Identity();
  79802. var invViewProjection = BABYLON.Matrix.Identity();
  79803. var viewProjection = BABYLON.Matrix.Identity();
  79804. var screenSize = BABYLON.Vector2.Zero();
  79805. this.motionBlurPostProcess.onApply = function (effect) {
  79806. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  79807. viewProjection.invertToRef(invViewProjection);
  79808. effect.setMatrix("inverseViewProjection", invViewProjection);
  79809. effect.setMatrix("prevViewProjection", prevViewProjection);
  79810. prevViewProjection = viewProjection;
  79811. screenSize.x = _this.motionBlurPostProcess.width;
  79812. screenSize.y = _this.motionBlurPostProcess.height;
  79813. effect.setVector2("screenSize", screenSize);
  79814. motionScale = scene.getEngine().getFps() / 60.0;
  79815. effect.setFloat("motionScale", motionScale);
  79816. effect.setFloat("motionStrength", _this.motionStrength);
  79817. effect.setTexture("depthSampler", _this._getDepthTexture());
  79818. };
  79819. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  79820. };
  79821. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  79822. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  79823. var renderer = this._scene.enableGeometryBufferRenderer();
  79824. return renderer.getGBuffer().textures[0];
  79825. }
  79826. return this._scene.enableDepthRenderer().getDepthMap();
  79827. };
  79828. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  79829. for (var i = 0; i < this._cameras.length; i++) {
  79830. var camera = this._cameras[i];
  79831. if (this.originalPostProcess) {
  79832. this.originalPostProcess.dispose(camera);
  79833. }
  79834. if (this.downSampleX4PostProcess) {
  79835. this.downSampleX4PostProcess.dispose(camera);
  79836. }
  79837. if (this.brightPassPostProcess) {
  79838. this.brightPassPostProcess.dispose(camera);
  79839. }
  79840. if (this.textureAdderPostProcess) {
  79841. this.textureAdderPostProcess.dispose(camera);
  79842. }
  79843. if (this.textureAdderFinalPostProcess) {
  79844. this.textureAdderFinalPostProcess.dispose(camera);
  79845. }
  79846. if (this.volumetricLightPostProcess) {
  79847. this.volumetricLightPostProcess.dispose(camera);
  79848. }
  79849. if (this.volumetricLightSmoothXPostProcess) {
  79850. this.volumetricLightSmoothXPostProcess.dispose(camera);
  79851. }
  79852. if (this.volumetricLightSmoothYPostProcess) {
  79853. this.volumetricLightSmoothYPostProcess.dispose(camera);
  79854. }
  79855. if (this.volumetricLightMergePostProces) {
  79856. this.volumetricLightMergePostProces.dispose(camera);
  79857. }
  79858. if (this.volumetricLightFinalPostProcess) {
  79859. this.volumetricLightFinalPostProcess.dispose(camera);
  79860. }
  79861. if (this.lensFlarePostProcess) {
  79862. this.lensFlarePostProcess.dispose(camera);
  79863. }
  79864. if (this.lensFlareComposePostProcess) {
  79865. this.lensFlareComposePostProcess.dispose(camera);
  79866. }
  79867. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  79868. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  79869. }
  79870. if (this.luminancePostProcess) {
  79871. this.luminancePostProcess.dispose(camera);
  79872. }
  79873. if (this.hdrPostProcess) {
  79874. this.hdrPostProcess.dispose(camera);
  79875. }
  79876. if (this.hdrFinalPostProcess) {
  79877. this.hdrFinalPostProcess.dispose(camera);
  79878. }
  79879. if (this.depthOfFieldPostProcess) {
  79880. this.depthOfFieldPostProcess.dispose(camera);
  79881. }
  79882. if (this.motionBlurPostProcess) {
  79883. this.motionBlurPostProcess.dispose(camera);
  79884. }
  79885. if (this.fxaaPostProcess) {
  79886. this.fxaaPostProcess.dispose(camera);
  79887. }
  79888. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  79889. this.blurHPostProcesses[j].dispose(camera);
  79890. }
  79891. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  79892. this.blurVPostProcesses[j].dispose(camera);
  79893. }
  79894. }
  79895. this.originalPostProcess = null;
  79896. this.downSampleX4PostProcess = null;
  79897. this.brightPassPostProcess = null;
  79898. this.textureAdderPostProcess = null;
  79899. this.textureAdderFinalPostProcess = null;
  79900. this.volumetricLightPostProcess = null;
  79901. this.volumetricLightSmoothXPostProcess = null;
  79902. this.volumetricLightSmoothYPostProcess = null;
  79903. this.volumetricLightMergePostProces = null;
  79904. this.volumetricLightFinalPostProcess = null;
  79905. this.lensFlarePostProcess = null;
  79906. this.lensFlareComposePostProcess = null;
  79907. this.luminancePostProcess = null;
  79908. this.hdrPostProcess = null;
  79909. this.hdrFinalPostProcess = null;
  79910. this.depthOfFieldPostProcess = null;
  79911. this.motionBlurPostProcess = null;
  79912. this.fxaaPostProcess = null;
  79913. this.luminanceDownSamplePostProcesses = [];
  79914. this.blurHPostProcesses = [];
  79915. this.blurVPostProcesses = [];
  79916. };
  79917. /**
  79918. * Dispose of the pipeline and stop all post processes
  79919. */
  79920. StandardRenderingPipeline.prototype.dispose = function () {
  79921. this._disposePostProcesses();
  79922. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79923. _super.prototype.dispose.call(this);
  79924. };
  79925. /**
  79926. * Serialize the rendering pipeline (Used when exporting)
  79927. * @returns the serialized object
  79928. */
  79929. StandardRenderingPipeline.prototype.serialize = function () {
  79930. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79931. if (this.sourceLight) {
  79932. serializationObject.sourceLightId = this.sourceLight.id;
  79933. }
  79934. serializationObject.customType = "StandardRenderingPipeline";
  79935. return serializationObject;
  79936. };
  79937. /**
  79938. * Parse the serialized pipeline
  79939. * @param source Source pipeline.
  79940. * @param scene The scene to load the pipeline to.
  79941. * @param rootUrl The URL of the serialized pipeline.
  79942. * @returns An instantiated pipeline from the serialized object.
  79943. */
  79944. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  79945. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79946. if (source.sourceLightId) {
  79947. p.sourceLight = scene.getLightByID(source.sourceLightId);
  79948. }
  79949. return p;
  79950. };
  79951. // Luminance steps
  79952. StandardRenderingPipeline.LuminanceSteps = 6;
  79953. __decorate([
  79954. BABYLON.serialize()
  79955. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  79956. __decorate([
  79957. BABYLON.serialize()
  79958. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  79959. __decorate([
  79960. BABYLON.serialize()
  79961. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  79962. __decorate([
  79963. BABYLON.serialize()
  79964. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  79965. __decorate([
  79966. BABYLON.serializeAsTexture("lensTexture")
  79967. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  79968. __decorate([
  79969. BABYLON.serialize()
  79970. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  79971. __decorate([
  79972. BABYLON.serialize()
  79973. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  79974. __decorate([
  79975. BABYLON.serialize()
  79976. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  79977. __decorate([
  79978. BABYLON.serialize()
  79979. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  79980. __decorate([
  79981. BABYLON.serialize()
  79982. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  79983. __decorate([
  79984. BABYLON.serialize()
  79985. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  79986. __decorate([
  79987. BABYLON.serializeAsTexture("lensColorTexture")
  79988. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  79989. __decorate([
  79990. BABYLON.serialize()
  79991. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  79992. __decorate([
  79993. BABYLON.serialize()
  79994. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  79995. __decorate([
  79996. BABYLON.serialize()
  79997. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  79998. __decorate([
  79999. BABYLON.serialize()
  80000. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  80001. __decorate([
  80002. BABYLON.serializeAsTexture("lensStarTexture")
  80003. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  80004. __decorate([
  80005. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  80006. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  80007. __decorate([
  80008. BABYLON.serialize()
  80009. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  80010. __decorate([
  80011. BABYLON.serialize()
  80012. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  80013. __decorate([
  80014. BABYLON.serialize()
  80015. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  80016. __decorate([
  80017. BABYLON.serialize()
  80018. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  80019. __decorate([
  80020. BABYLON.serialize()
  80021. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  80022. __decorate([
  80023. BABYLON.serialize()
  80024. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  80025. __decorate([
  80026. BABYLON.serialize()
  80027. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  80028. __decorate([
  80029. BABYLON.serialize()
  80030. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  80031. __decorate([
  80032. BABYLON.serialize()
  80033. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  80034. __decorate([
  80035. BABYLON.serialize()
  80036. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  80037. __decorate([
  80038. BABYLON.serialize()
  80039. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  80040. __decorate([
  80041. BABYLON.serialize()
  80042. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  80043. __decorate([
  80044. BABYLON.serialize()
  80045. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  80046. __decorate([
  80047. BABYLON.serialize()
  80048. ], StandardRenderingPipeline.prototype, "samples", null);
  80049. return StandardRenderingPipeline;
  80050. }(BABYLON.PostProcessRenderPipeline));
  80051. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  80052. })(BABYLON || (BABYLON = {}));
  80053. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  80054. var BABYLON;
  80055. (function (BABYLON) {
  80056. var FxaaPostProcess = /** @class */ (function (_super) {
  80057. __extends(FxaaPostProcess, _super);
  80058. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80059. if (camera === void 0) { camera = null; }
  80060. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80061. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  80062. var defines = _this._getDefines();
  80063. _this.updateEffect(defines);
  80064. _this.onApplyObservable.add(function (effect) {
  80065. var texelSize = _this.texelSize;
  80066. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  80067. });
  80068. return _this;
  80069. }
  80070. FxaaPostProcess.prototype._getDefines = function () {
  80071. var engine = this.getEngine();
  80072. if (!engine) {
  80073. return null;
  80074. }
  80075. var glInfo = engine.getGlInfo();
  80076. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  80077. return "#define MALI 1\n";
  80078. }
  80079. return null;
  80080. };
  80081. return FxaaPostProcess;
  80082. }(BABYLON.PostProcess));
  80083. BABYLON.FxaaPostProcess = FxaaPostProcess;
  80084. })(BABYLON || (BABYLON = {}));
  80085. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  80086. var BABYLON;
  80087. (function (BABYLON) {
  80088. /**
  80089. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  80090. */
  80091. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  80092. __extends(ChromaticAberrationPostProcess, _super);
  80093. /**
  80094. * Creates a new instance ChromaticAberrationPostProcess
  80095. * @param name The name of the effect.
  80096. * @param screenWidth The width of the screen to apply the effect on.
  80097. * @param screenHeight The height of the screen to apply the effect on.
  80098. * @param options The required width/height ratio to downsize to before computing the render pass.
  80099. * @param camera The camera to apply the render pass to.
  80100. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80101. * @param engine The engine which the post process will be applied. (default: current engine)
  80102. * @param reusable If the post process can be reused on the same frame. (default: false)
  80103. * @param textureType Type of textures used when performing the post process. (default: 0)
  80104. * @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)
  80105. */
  80106. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80107. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80108. if (blockCompilation === void 0) { blockCompilation = false; }
  80109. 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;
  80110. /**
  80111. * The amount of seperation of rgb channels (default: 30)
  80112. */
  80113. _this.aberrationAmount = 30;
  80114. /**
  80115. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  80116. */
  80117. _this.radialIntensity = 0;
  80118. /**
  80119. * 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))
  80120. */
  80121. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  80122. /**
  80123. * 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))
  80124. */
  80125. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  80126. _this.onApplyObservable.add(function (effect) {
  80127. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  80128. effect.setFloat('screen_width', screenWidth);
  80129. effect.setFloat('screen_height', screenHeight);
  80130. effect.setFloat('radialIntensity', _this.radialIntensity);
  80131. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  80132. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  80133. });
  80134. return _this;
  80135. }
  80136. return ChromaticAberrationPostProcess;
  80137. }(BABYLON.PostProcess));
  80138. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  80139. })(BABYLON || (BABYLON = {}));
  80140. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  80141. var BABYLON;
  80142. (function (BABYLON) {
  80143. /**
  80144. * The GrainPostProcess adds noise to the image at mid luminance levels
  80145. */
  80146. var GrainPostProcess = /** @class */ (function (_super) {
  80147. __extends(GrainPostProcess, _super);
  80148. /**
  80149. * Creates a new instance of @see GrainPostProcess
  80150. * @param name The name of the effect.
  80151. * @param options The required width/height ratio to downsize to before computing the render pass.
  80152. * @param camera The camera to apply the render pass to.
  80153. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80154. * @param engine The engine which the post process will be applied. (default: current engine)
  80155. * @param reusable If the post process can be reused on the same frame. (default: false)
  80156. * @param textureType Type of textures used when performing the post process. (default: 0)
  80157. * @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)
  80158. */
  80159. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80160. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80161. if (blockCompilation === void 0) { blockCompilation = false; }
  80162. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80163. /**
  80164. * The intensity of the grain added (default: 30)
  80165. */
  80166. _this.intensity = 30;
  80167. /**
  80168. * If the grain should be randomized on every frame
  80169. */
  80170. _this.animated = false;
  80171. _this.onApplyObservable.add(function (effect) {
  80172. effect.setFloat('intensity', _this.intensity);
  80173. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  80174. });
  80175. return _this;
  80176. }
  80177. return GrainPostProcess;
  80178. }(BABYLON.PostProcess));
  80179. BABYLON.GrainPostProcess = GrainPostProcess;
  80180. })(BABYLON || (BABYLON = {}));
  80181. //# sourceMappingURL=babylon.grainPostProcess.js.map
  80182. var BABYLON;
  80183. (function (BABYLON) {
  80184. /**
  80185. * The SharpenPostProcess applies a sharpen kernel to every pixel
  80186. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80187. */
  80188. var SharpenPostProcess = /** @class */ (function (_super) {
  80189. __extends(SharpenPostProcess, _super);
  80190. /**
  80191. * Creates a new instance ConvolutionPostProcess
  80192. * @param name The name of the effect.
  80193. * @param options The required width/height ratio to downsize to before computing the render pass.
  80194. * @param camera The camera to apply the render pass to.
  80195. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80196. * @param engine The engine which the post process will be applied. (default: current engine)
  80197. * @param reusable If the post process can be reused on the same frame. (default: false)
  80198. * @param textureType Type of textures used when performing the post process. (default: 0)
  80199. * @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)
  80200. */
  80201. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80202. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80203. if (blockCompilation === void 0) { blockCompilation = false; }
  80204. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80205. /**
  80206. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  80207. */
  80208. _this.colorAmount = 1.0;
  80209. /**
  80210. * How much sharpness should be applied (default: 0.3)
  80211. */
  80212. _this.edgeAmount = 0.3;
  80213. _this.onApply = function (effect) {
  80214. effect.setFloat2("screenSize", _this.width, _this.height);
  80215. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  80216. };
  80217. return _this;
  80218. }
  80219. return SharpenPostProcess;
  80220. }(BABYLON.PostProcess));
  80221. BABYLON.SharpenPostProcess = SharpenPostProcess;
  80222. })(BABYLON || (BABYLON = {}));
  80223. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  80224. var BABYLON;
  80225. (function (BABYLON) {
  80226. /**
  80227. * The Blur Post Process which blurs an image based on a kernel and direction.
  80228. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  80229. */
  80230. var BlurPostProcess = /** @class */ (function (_super) {
  80231. __extends(BlurPostProcess, _super);
  80232. /**
  80233. * Creates a new instance BlurPostProcess
  80234. * @param name The name of the effect.
  80235. * @param direction The direction in which to blur the image.
  80236. * @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.
  80237. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  80238. * @param camera The camera to apply the render pass to.
  80239. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80240. * @param engine The engine which the post process will be applied. (default: current engine)
  80241. * @param reusable If the post process can be reused on the same frame. (default: false)
  80242. * @param textureType Type of textures used when performing the post process. (default: 0)
  80243. * @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)
  80244. */
  80245. function BlurPostProcess(name,
  80246. /** The direction in which to blur the image. */
  80247. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  80248. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80249. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80250. if (defines === void 0) { defines = ""; }
  80251. if (blockCompilation === void 0) { blockCompilation = false; }
  80252. 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;
  80253. _this.direction = direction;
  80254. _this.blockCompilation = blockCompilation;
  80255. _this._packedFloat = false;
  80256. _this._staticDefines = "";
  80257. _this._staticDefines = defines;
  80258. _this.onApplyObservable.add(function (effect) {
  80259. if (_this._outputTexture) {
  80260. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  80261. }
  80262. else {
  80263. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  80264. }
  80265. });
  80266. _this.kernel = kernel;
  80267. return _this;
  80268. }
  80269. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  80270. /**
  80271. * Gets the length in pixels of the blur sample region
  80272. */
  80273. get: function () {
  80274. return this._idealKernel;
  80275. },
  80276. /**
  80277. * Sets the length in pixels of the blur sample region
  80278. */
  80279. set: function (v) {
  80280. if (this._idealKernel === v) {
  80281. return;
  80282. }
  80283. v = Math.max(v, 1);
  80284. this._idealKernel = v;
  80285. this._kernel = this._nearestBestKernel(v);
  80286. if (!this.blockCompilation) {
  80287. this._updateParameters();
  80288. }
  80289. },
  80290. enumerable: true,
  80291. configurable: true
  80292. });
  80293. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  80294. /**
  80295. * Gets wether or not the blur is unpacking/repacking floats
  80296. */
  80297. get: function () {
  80298. return this._packedFloat;
  80299. },
  80300. /**
  80301. * Sets wether or not the blur needs to unpack/repack floats
  80302. */
  80303. set: function (v) {
  80304. if (this._packedFloat === v) {
  80305. return;
  80306. }
  80307. this._packedFloat = v;
  80308. if (!this.blockCompilation) {
  80309. this._updateParameters();
  80310. }
  80311. },
  80312. enumerable: true,
  80313. configurable: true
  80314. });
  80315. /**
  80316. * Updates the effect with the current post process compile time values and recompiles the shader.
  80317. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80318. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80319. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80320. * @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
  80321. * @param onCompiled Called when the shader has been compiled.
  80322. * @param onError Called if there is an error when compiling a shader.
  80323. */
  80324. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80325. if (defines === void 0) { defines = null; }
  80326. if (uniforms === void 0) { uniforms = null; }
  80327. if (samplers === void 0) { samplers = null; }
  80328. this._updateParameters(onCompiled, onError);
  80329. };
  80330. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  80331. // Generate sampling offsets and weights
  80332. var N = this._kernel;
  80333. var centerIndex = (N - 1) / 2;
  80334. // Generate Gaussian sampling weights over kernel
  80335. var offsets = [];
  80336. var weights = [];
  80337. var totalWeight = 0;
  80338. for (var i = 0; i < N; i++) {
  80339. var u = i / (N - 1);
  80340. var w = this._gaussianWeight(u * 2.0 - 1);
  80341. offsets[i] = (i - centerIndex);
  80342. weights[i] = w;
  80343. totalWeight += w;
  80344. }
  80345. // Normalize weights
  80346. for (var i = 0; i < weights.length; i++) {
  80347. weights[i] /= totalWeight;
  80348. }
  80349. // Optimize: combine samples to take advantage of hardware linear sampling
  80350. // Walk from left to center, combining pairs (symmetrically)
  80351. var linearSamplingWeights = [];
  80352. var linearSamplingOffsets = [];
  80353. var linearSamplingMap = [];
  80354. for (var i = 0; i <= centerIndex; i += 2) {
  80355. var j = Math.min(i + 1, Math.floor(centerIndex));
  80356. var singleCenterSample = i === j;
  80357. if (singleCenterSample) {
  80358. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80359. }
  80360. else {
  80361. var sharedCell = j === centerIndex;
  80362. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  80363. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  80364. if (offsetLinear === 0) {
  80365. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80366. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  80367. }
  80368. else {
  80369. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  80370. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  80371. }
  80372. }
  80373. }
  80374. for (var i = 0; i < linearSamplingMap.length; i++) {
  80375. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  80376. linearSamplingWeights[i] = linearSamplingMap[i].w;
  80377. }
  80378. // Replace with optimized
  80379. offsets = linearSamplingOffsets;
  80380. weights = linearSamplingWeights;
  80381. // Generate shaders
  80382. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  80383. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  80384. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  80385. var defines = "";
  80386. defines += this._staticDefines;
  80387. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  80388. if (this._staticDefines.indexOf("DOF") != -1) {
  80389. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  80390. varyingCount--;
  80391. }
  80392. for (var i = 0; i < varyingCount; i++) {
  80393. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  80394. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  80395. }
  80396. var depCount = 0;
  80397. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  80398. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  80399. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  80400. depCount++;
  80401. }
  80402. if (this.packedFloat) {
  80403. defines += "#define PACKEDFLOAT 1";
  80404. }
  80405. this.blockCompilation = false;
  80406. _super.prototype.updateEffect.call(this, defines, null, null, {
  80407. varyingCount: varyingCount,
  80408. depCount: depCount
  80409. }, onCompiled, onError);
  80410. };
  80411. /**
  80412. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  80413. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  80414. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  80415. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  80416. * The gaps between physical kernels are compensated for in the weighting of the samples
  80417. * @param idealKernel Ideal blur kernel.
  80418. * @return Nearest best kernel.
  80419. */
  80420. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  80421. var v = Math.round(idealKernel);
  80422. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  80423. var k = _a[_i];
  80424. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  80425. return Math.max(k, 3);
  80426. }
  80427. }
  80428. return Math.max(v, 3);
  80429. };
  80430. /**
  80431. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  80432. * @param x The point on the Gaussian distribution to sample.
  80433. * @return the value of the Gaussian function at x.
  80434. */
  80435. BlurPostProcess.prototype._gaussianWeight = function (x) {
  80436. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  80437. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  80438. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  80439. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  80440. // truncated at around 1.3% of peak strength.
  80441. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  80442. var sigma = (1 / 3);
  80443. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  80444. var exponent = -((x * x) / (2.0 * sigma * sigma));
  80445. var weight = (1.0 / denominator) * Math.exp(exponent);
  80446. return weight;
  80447. };
  80448. /**
  80449. * Generates a string that can be used as a floating point number in GLSL.
  80450. * @param x Value to print.
  80451. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  80452. * @return GLSL float string.
  80453. */
  80454. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  80455. if (decimalFigures === void 0) { decimalFigures = 8; }
  80456. return x.toFixed(decimalFigures).replace(/0+$/, '');
  80457. };
  80458. return BlurPostProcess;
  80459. }(BABYLON.PostProcess));
  80460. BABYLON.BlurPostProcess = BlurPostProcess;
  80461. })(BABYLON || (BABYLON = {}));
  80462. //# sourceMappingURL=babylon.blurPostProcess.js.map
  80463. var BABYLON;
  80464. (function (BABYLON) {
  80465. /**
  80466. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  80467. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  80468. * based on samples that have a large difference in distance than the center pixel.
  80469. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80470. */
  80471. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  80472. __extends(DepthOfFieldBlurPostProcess, _super);
  80473. /**
  80474. * Creates a new instance CircleOfConfusionPostProcess
  80475. * @param name The name of the effect.
  80476. * @param scene The scene the effect belongs to.
  80477. * @param direction The direction the blur should be applied.
  80478. * @param kernel The size of the kernel used to blur.
  80479. * @param options The required width/height ratio to downsize to before computing the render pass.
  80480. * @param camera The camera to apply the render pass to.
  80481. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  80482. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  80483. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80484. * @param engine The engine which the post process will be applied. (default: current engine)
  80485. * @param reusable If the post process can be reused on the same frame. (default: false)
  80486. * @param textureType Type of textures used when performing the post process. (default: 0)
  80487. * @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)
  80488. */
  80489. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  80490. if (imageToBlur === void 0) { imageToBlur = null; }
  80491. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80492. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80493. if (blockCompilation === void 0) { blockCompilation = false; }
  80494. 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;
  80495. _this.direction = direction;
  80496. _this.onApplyObservable.add(function (effect) {
  80497. if (imageToBlur != null) {
  80498. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  80499. }
  80500. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80501. if (scene.activeCamera) {
  80502. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80503. }
  80504. });
  80505. return _this;
  80506. }
  80507. return DepthOfFieldBlurPostProcess;
  80508. }(BABYLON.BlurPostProcess));
  80509. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  80510. })(BABYLON || (BABYLON = {}));
  80511. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  80512. var BABYLON;
  80513. (function (BABYLON) {
  80514. /**
  80515. * Options to be set when merging outputs from the default pipeline.
  80516. */
  80517. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  80518. function DepthOfFieldMergePostProcessOptions() {
  80519. }
  80520. return DepthOfFieldMergePostProcessOptions;
  80521. }());
  80522. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  80523. /**
  80524. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80525. */
  80526. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  80527. __extends(DepthOfFieldMergePostProcess, _super);
  80528. /**
  80529. * Creates a new instance of DepthOfFieldMergePostProcess
  80530. * @param name The name of the effect.
  80531. * @param originalFromInput Post process which's input will be used for the merge.
  80532. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  80533. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  80534. * @param options The required width/height ratio to downsize to before computing the render pass.
  80535. * @param camera The camera to apply the render pass to.
  80536. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80537. * @param engine The engine which the post process will be applied. (default: current engine)
  80538. * @param reusable If the post process can be reused on the same frame. (default: false)
  80539. * @param textureType Type of textures used when performing the post process. (default: 0)
  80540. * @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)
  80541. */
  80542. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80543. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80544. if (blockCompilation === void 0) { blockCompilation = false; }
  80545. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80546. _this.blurSteps = blurSteps;
  80547. _this.onApplyObservable.add(function (effect) {
  80548. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80549. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80550. blurSteps.forEach(function (step, index) {
  80551. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  80552. });
  80553. });
  80554. if (!blockCompilation) {
  80555. _this.updateEffect();
  80556. }
  80557. return _this;
  80558. }
  80559. /**
  80560. * Updates the effect with the current post process compile time values and recompiles the shader.
  80561. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80562. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80563. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80564. * @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
  80565. * @param onCompiled Called when the shader has been compiled.
  80566. * @param onError Called if there is an error when compiling a shader.
  80567. */
  80568. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80569. if (defines === void 0) { defines = null; }
  80570. if (uniforms === void 0) { uniforms = null; }
  80571. if (samplers === void 0) { samplers = null; }
  80572. if (!defines) {
  80573. defines = "";
  80574. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  80575. }
  80576. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  80577. };
  80578. return DepthOfFieldMergePostProcess;
  80579. }(BABYLON.PostProcess));
  80580. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  80581. })(BABYLON || (BABYLON = {}));
  80582. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  80583. var BABYLON;
  80584. (function (BABYLON) {
  80585. /**
  80586. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  80587. */
  80588. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  80589. __extends(CircleOfConfusionPostProcess, _super);
  80590. /**
  80591. * Creates a new instance CircleOfConfusionPostProcess
  80592. * @param name The name of the effect.
  80593. * @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.
  80594. * @param options The required width/height ratio to downsize to before computing the render pass.
  80595. * @param camera The camera to apply the render pass to.
  80596. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80597. * @param engine The engine which the post process will be applied. (default: current engine)
  80598. * @param reusable If the post process can be reused on the same frame. (default: false)
  80599. * @param textureType Type of textures used when performing the post process. (default: 0)
  80600. * @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)
  80601. */
  80602. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80603. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80604. if (blockCompilation === void 0) { blockCompilation = false; }
  80605. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80606. /**
  80607. * 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.
  80608. */
  80609. _this.lensSize = 50;
  80610. /**
  80611. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80612. */
  80613. _this.fStop = 1.4;
  80614. /**
  80615. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80616. */
  80617. _this.focusDistance = 2000;
  80618. /**
  80619. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  80620. */
  80621. _this.focalLength = 50;
  80622. _this._depthTexture = null;
  80623. _this._depthTexture = depthTexture;
  80624. _this.onApplyObservable.add(function (effect) {
  80625. if (!_this._depthTexture) {
  80626. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  80627. return;
  80628. }
  80629. effect.setTexture("depthSampler", _this._depthTexture);
  80630. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  80631. var aperture = _this.lensSize / _this.fStop;
  80632. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  80633. effect.setFloat('focusDistance', _this.focusDistance);
  80634. effect.setFloat('cocPrecalculation', cocPrecalculation);
  80635. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  80636. });
  80637. return _this;
  80638. }
  80639. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  80640. /**
  80641. * 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.
  80642. */
  80643. set: function (value) {
  80644. this._depthTexture = value;
  80645. },
  80646. enumerable: true,
  80647. configurable: true
  80648. });
  80649. return CircleOfConfusionPostProcess;
  80650. }(BABYLON.PostProcess));
  80651. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  80652. })(BABYLON || (BABYLON = {}));
  80653. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  80654. var BABYLON;
  80655. (function (BABYLON) {
  80656. /**
  80657. * Specifies the level of max blur that should be applied when using the depth of field effect
  80658. */
  80659. var DepthOfFieldEffectBlurLevel;
  80660. (function (DepthOfFieldEffectBlurLevel) {
  80661. /**
  80662. * Subtle blur
  80663. */
  80664. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  80665. /**
  80666. * Medium blur
  80667. */
  80668. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  80669. /**
  80670. * Large blur
  80671. */
  80672. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  80673. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  80674. ;
  80675. /**
  80676. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  80677. */
  80678. var DepthOfFieldEffect = /** @class */ (function (_super) {
  80679. __extends(DepthOfFieldEffect, _super);
  80680. /**
  80681. * Creates a new instance DepthOfFieldEffect
  80682. * @param scene The scene the effect belongs to.
  80683. * @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.
  80684. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80685. * @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)
  80686. */
  80687. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  80688. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  80689. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80690. if (blockCompilation === void 0) { blockCompilation = false; }
  80691. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  80692. return _this._effects;
  80693. }, true) || this;
  80694. /**
  80695. * @hidden Internal post processes in depth of field effect
  80696. */
  80697. _this._effects = [];
  80698. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  80699. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80700. // 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)
  80701. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  80702. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80703. _this._depthOfFieldBlurY = [];
  80704. _this._depthOfFieldBlurX = [];
  80705. var blurCount = 1;
  80706. var kernelSize = 15;
  80707. switch (blurLevel) {
  80708. case DepthOfFieldEffectBlurLevel.High: {
  80709. blurCount = 3;
  80710. kernelSize = 51;
  80711. break;
  80712. }
  80713. case DepthOfFieldEffectBlurLevel.Medium: {
  80714. blurCount = 2;
  80715. kernelSize = 31;
  80716. break;
  80717. }
  80718. default: {
  80719. kernelSize = 15;
  80720. blurCount = 1;
  80721. break;
  80722. }
  80723. }
  80724. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  80725. var ratio = 1.0;
  80726. for (var i = 0; i < blurCount; i++) {
  80727. 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);
  80728. blurY.autoClear = false;
  80729. ratio = 0.75 / Math.pow(2, i);
  80730. 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);
  80731. blurX.autoClear = false;
  80732. _this._depthOfFieldBlurY.push(blurY);
  80733. _this._depthOfFieldBlurX.push(blurX);
  80734. }
  80735. // Set all post processes on the effect.
  80736. _this._effects = [_this._circleOfConfusion];
  80737. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  80738. _this._effects.push(_this._depthOfFieldBlurY[i]);
  80739. _this._effects.push(_this._depthOfFieldBlurX[i]);
  80740. }
  80741. // Merge blurred images with original image based on circleOfConfusion
  80742. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80743. _this._dofMerge.autoClear = false;
  80744. _this._effects.push(_this._dofMerge);
  80745. return _this;
  80746. }
  80747. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  80748. get: function () {
  80749. return this._circleOfConfusion.focalLength;
  80750. },
  80751. /**
  80752. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  80753. */
  80754. set: function (value) {
  80755. this._circleOfConfusion.focalLength = value;
  80756. },
  80757. enumerable: true,
  80758. configurable: true
  80759. });
  80760. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  80761. get: function () {
  80762. return this._circleOfConfusion.fStop;
  80763. },
  80764. /**
  80765. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80766. */
  80767. set: function (value) {
  80768. this._circleOfConfusion.fStop = value;
  80769. },
  80770. enumerable: true,
  80771. configurable: true
  80772. });
  80773. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  80774. get: function () {
  80775. return this._circleOfConfusion.focusDistance;
  80776. },
  80777. /**
  80778. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80779. */
  80780. set: function (value) {
  80781. this._circleOfConfusion.focusDistance = value;
  80782. },
  80783. enumerable: true,
  80784. configurable: true
  80785. });
  80786. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  80787. get: function () {
  80788. return this._circleOfConfusion.lensSize;
  80789. },
  80790. /**
  80791. * 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.
  80792. */
  80793. set: function (value) {
  80794. this._circleOfConfusion.lensSize = value;
  80795. },
  80796. enumerable: true,
  80797. configurable: true
  80798. });
  80799. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  80800. /**
  80801. * 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.
  80802. */
  80803. set: function (value) {
  80804. this._circleOfConfusion.depthTexture = value;
  80805. },
  80806. enumerable: true,
  80807. configurable: true
  80808. });
  80809. /**
  80810. * Disposes each of the internal effects for a given camera.
  80811. * @param camera The camera to dispose the effect on.
  80812. */
  80813. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  80814. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80815. this._effects[effectIndex].dispose(camera);
  80816. }
  80817. };
  80818. /**
  80819. * @hidden Internal
  80820. */
  80821. DepthOfFieldEffect.prototype._updateEffects = function () {
  80822. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80823. this._effects[effectIndex].updateEffect();
  80824. }
  80825. };
  80826. /**
  80827. * Internal
  80828. * @returns if all the contained post processes are ready.
  80829. * @hidden
  80830. */
  80831. DepthOfFieldEffect.prototype._isReady = function () {
  80832. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80833. if (!this._effects[effectIndex].isReady()) {
  80834. return false;
  80835. }
  80836. }
  80837. return true;
  80838. };
  80839. return DepthOfFieldEffect;
  80840. }(BABYLON.PostProcessRenderEffect));
  80841. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  80842. })(BABYLON || (BABYLON = {}));
  80843. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  80844. var BABYLON;
  80845. (function (BABYLON) {
  80846. /**
  80847. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80848. */
  80849. var BloomMergePostProcess = /** @class */ (function (_super) {
  80850. __extends(BloomMergePostProcess, _super);
  80851. /**
  80852. * Creates a new instance of @see BloomMergePostProcess
  80853. * @param name The name of the effect.
  80854. * @param originalFromInput Post process which's input will be used for the merge.
  80855. * @param blurred Blurred highlights post process which's output will be used.
  80856. * @param weight Weight of the bloom to be added to the original input.
  80857. * @param options The required width/height ratio to downsize to before computing the render pass.
  80858. * @param camera The camera to apply the render pass to.
  80859. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80860. * @param engine The engine which the post process will be applied. (default: current engine)
  80861. * @param reusable If the post process can be reused on the same frame. (default: false)
  80862. * @param textureType Type of textures used when performing the post process. (default: 0)
  80863. * @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)
  80864. */
  80865. function BloomMergePostProcess(name, originalFromInput, blurred,
  80866. /** Weight of the bloom to be added to the original input. */
  80867. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80868. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80869. if (blockCompilation === void 0) { blockCompilation = false; }
  80870. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80871. _this.weight = weight;
  80872. _this.onApplyObservable.add(function (effect) {
  80873. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80874. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  80875. effect.setFloat("bloomWeight", _this.weight);
  80876. });
  80877. if (!blockCompilation) {
  80878. _this.updateEffect();
  80879. }
  80880. return _this;
  80881. }
  80882. return BloomMergePostProcess;
  80883. }(BABYLON.PostProcess));
  80884. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  80885. })(BABYLON || (BABYLON = {}));
  80886. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  80887. var BABYLON;
  80888. (function (BABYLON) {
  80889. /**
  80890. * 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.
  80891. */
  80892. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  80893. __extends(ExtractHighlightsPostProcess, _super);
  80894. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80895. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80896. if (blockCompilation === void 0) { blockCompilation = false; }
  80897. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80898. /**
  80899. * The luminance threshold, pixels below this value will be set to black.
  80900. */
  80901. _this.threshold = 0.9;
  80902. /** @hidden */
  80903. _this._exposure = 1;
  80904. /**
  80905. * Post process which has the input texture to be used when performing highlight extraction
  80906. * @hidden
  80907. */
  80908. _this._inputPostProcess = null;
  80909. _this.onApplyObservable.add(function (effect) {
  80910. if (_this._inputPostProcess) {
  80911. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  80912. }
  80913. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  80914. effect.setFloat('exposure', _this._exposure);
  80915. });
  80916. return _this;
  80917. }
  80918. return ExtractHighlightsPostProcess;
  80919. }(BABYLON.PostProcess));
  80920. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  80921. })(BABYLON || (BABYLON = {}));
  80922. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  80923. var BABYLON;
  80924. (function (BABYLON) {
  80925. /**
  80926. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  80927. */
  80928. var BloomEffect = /** @class */ (function (_super) {
  80929. __extends(BloomEffect, _super);
  80930. /**
  80931. * Creates a new instance of @see BloomEffect
  80932. * @param scene The scene the effect belongs to.
  80933. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  80934. * @param bloomKernel The size of the kernel to be used when applying the blur.
  80935. * @param bloomWeight The the strength of bloom.
  80936. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80937. * @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)
  80938. */
  80939. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  80940. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80941. if (blockCompilation === void 0) { blockCompilation = false; }
  80942. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  80943. return _this._effects;
  80944. }, true) || this;
  80945. _this.bloomScale = bloomScale;
  80946. /**
  80947. * @hidden Internal
  80948. */
  80949. _this._effects = [];
  80950. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80951. _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);
  80952. _this._blurX.alwaysForcePOT = true;
  80953. _this._blurX.autoClear = false;
  80954. _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);
  80955. _this._blurY.alwaysForcePOT = true;
  80956. _this._blurY.autoClear = false;
  80957. _this.kernel = bloomKernel;
  80958. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  80959. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80960. _this._merge.autoClear = false;
  80961. _this._effects.push(_this._merge);
  80962. return _this;
  80963. }
  80964. Object.defineProperty(BloomEffect.prototype, "threshold", {
  80965. /**
  80966. * The luminance threshold to find bright areas of the image to bloom.
  80967. */
  80968. get: function () {
  80969. return this._downscale.threshold;
  80970. },
  80971. set: function (value) {
  80972. this._downscale.threshold = value;
  80973. },
  80974. enumerable: true,
  80975. configurable: true
  80976. });
  80977. Object.defineProperty(BloomEffect.prototype, "weight", {
  80978. /**
  80979. * The strength of the bloom.
  80980. */
  80981. get: function () {
  80982. return this._merge.weight;
  80983. },
  80984. set: function (value) {
  80985. this._merge.weight = value;
  80986. },
  80987. enumerable: true,
  80988. configurable: true
  80989. });
  80990. Object.defineProperty(BloomEffect.prototype, "kernel", {
  80991. /**
  80992. * Specifies the size of the bloom blur kernel, relative to the final output size
  80993. */
  80994. get: function () {
  80995. return this._blurX.kernel / this.bloomScale;
  80996. },
  80997. set: function (value) {
  80998. this._blurX.kernel = value * this.bloomScale;
  80999. this._blurY.kernel = value * this.bloomScale;
  81000. },
  81001. enumerable: true,
  81002. configurable: true
  81003. });
  81004. /**
  81005. * Disposes each of the internal effects for a given camera.
  81006. * @param camera The camera to dispose the effect on.
  81007. */
  81008. BloomEffect.prototype.disposeEffects = function (camera) {
  81009. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81010. this._effects[effectIndex].dispose(camera);
  81011. }
  81012. };
  81013. /**
  81014. * @hidden Internal
  81015. */
  81016. BloomEffect.prototype._updateEffects = function () {
  81017. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81018. this._effects[effectIndex].updateEffect();
  81019. }
  81020. };
  81021. /**
  81022. * Internal
  81023. * @returns if all the contained post processes are ready.
  81024. * @hidden
  81025. */
  81026. BloomEffect.prototype._isReady = function () {
  81027. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81028. if (!this._effects[effectIndex].isReady()) {
  81029. return false;
  81030. }
  81031. }
  81032. return true;
  81033. };
  81034. return BloomEffect;
  81035. }(BABYLON.PostProcessRenderEffect));
  81036. BABYLON.BloomEffect = BloomEffect;
  81037. })(BABYLON || (BABYLON = {}));
  81038. //# sourceMappingURL=babylon.bloomEffect.js.map
  81039. var BABYLON;
  81040. (function (BABYLON) {
  81041. /**
  81042. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  81043. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  81044. */
  81045. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  81046. __extends(DefaultRenderingPipeline, _super);
  81047. /**
  81048. * @constructor
  81049. * @param {string} name - The rendering pipeline name (default: "")
  81050. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  81051. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  81052. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  81053. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  81054. */
  81055. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  81056. if (name === void 0) { name = ""; }
  81057. if (hdr === void 0) { hdr = true; }
  81058. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  81059. if (automaticBuild === void 0) { automaticBuild = true; }
  81060. var _this = _super.call(this, scene.getEngine(), name) || this;
  81061. _this._camerasToBeAttached = [];
  81062. /**
  81063. * ID of the sharpen post process,
  81064. */
  81065. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  81066. /**
  81067. * ID of the image processing post process;
  81068. */
  81069. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  81070. /**
  81071. * ID of the Fast Approximate Anti-Aliasing post process;
  81072. */
  81073. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  81074. /**
  81075. * ID of the chromatic aberration post process,
  81076. */
  81077. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  81078. /**
  81079. * ID of the grain post process
  81080. */
  81081. _this.GrainPostProcessId = "GrainPostProcessEffect";
  81082. /**
  81083. * Glow post process which adds a glow to emmisive areas of the image
  81084. */
  81085. _this._glowLayer = null;
  81086. /**
  81087. * Animations which can be used to tweak settings over a period of time
  81088. */
  81089. _this.animations = [];
  81090. _this._imageProcessingConfigurationObserver = null;
  81091. // Values
  81092. _this._sharpenEnabled = false;
  81093. _this._bloomEnabled = false;
  81094. _this._depthOfFieldEnabled = false;
  81095. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  81096. _this._fxaaEnabled = false;
  81097. _this._imageProcessingEnabled = true;
  81098. _this._bloomScale = 0.5;
  81099. _this._chromaticAberrationEnabled = false;
  81100. _this._grainEnabled = false;
  81101. _this._buildAllowed = true;
  81102. _this._resizeObserver = null;
  81103. _this._hardwareScaleLevel = 1.0;
  81104. _this._bloomKernel = 64;
  81105. /**
  81106. * Specifies the weight of the bloom in the final rendering
  81107. */
  81108. _this._bloomWeight = 0.15;
  81109. /**
  81110. * Specifies the luma threshold for the area that will be blurred by the bloom
  81111. */
  81112. _this._bloomThreshold = 0.9;
  81113. _this._samples = 1;
  81114. _this._hasCleared = false;
  81115. _this._prevPostProcess = null;
  81116. _this._prevPrevPostProcess = null;
  81117. _this._depthOfFieldSceneObserver = null;
  81118. _this._cameras = cameras || scene.cameras;
  81119. _this._cameras = _this._cameras.slice();
  81120. _this._camerasToBeAttached = _this._cameras.slice();
  81121. _this._buildAllowed = automaticBuild;
  81122. // Initialize
  81123. _this._scene = scene;
  81124. var caps = _this._scene.getEngine().getCaps();
  81125. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  81126. // Misc
  81127. if (_this._hdr) {
  81128. if (caps.textureHalfFloatRender) {
  81129. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81130. }
  81131. else if (caps.textureFloatRender) {
  81132. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81133. }
  81134. }
  81135. else {
  81136. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81137. }
  81138. // Attach
  81139. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81140. var engine = _this._scene.getEngine();
  81141. // Create post processes before hand so they can be modified before enabled.
  81142. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  81143. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81144. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  81145. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  81146. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  81147. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81148. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  81149. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81150. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  81151. _this._resizeObserver = engine.onResizeObservable.add(function () {
  81152. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  81153. _this.bloomKernel = _this.bloomKernel;
  81154. });
  81155. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  81156. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  81157. });
  81158. _this._buildPipeline();
  81159. return _this;
  81160. }
  81161. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  81162. get: function () {
  81163. return this._sharpenEnabled;
  81164. },
  81165. /**
  81166. * Enable or disable the sharpen process from the pipeline
  81167. */
  81168. set: function (enabled) {
  81169. if (this._sharpenEnabled === enabled) {
  81170. return;
  81171. }
  81172. this._sharpenEnabled = enabled;
  81173. this._buildPipeline();
  81174. },
  81175. enumerable: true,
  81176. configurable: true
  81177. });
  81178. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  81179. /**
  81180. * Specifies the size of the bloom blur kernel, relative to the final output size
  81181. */
  81182. get: function () {
  81183. return this._bloomKernel;
  81184. },
  81185. set: function (value) {
  81186. this._bloomKernel = value;
  81187. this.bloom.kernel = value / this._hardwareScaleLevel;
  81188. },
  81189. enumerable: true,
  81190. configurable: true
  81191. });
  81192. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  81193. get: function () {
  81194. return this._bloomWeight;
  81195. },
  81196. /**
  81197. * The strength of the bloom.
  81198. */
  81199. set: function (value) {
  81200. if (this._bloomWeight === value) {
  81201. return;
  81202. }
  81203. this.bloom.weight = value;
  81204. this._bloomWeight = value;
  81205. },
  81206. enumerable: true,
  81207. configurable: true
  81208. });
  81209. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  81210. get: function () {
  81211. return this._bloomThreshold;
  81212. },
  81213. /**
  81214. * The strength of the bloom.
  81215. */
  81216. set: function (value) {
  81217. if (this._bloomThreshold === value) {
  81218. return;
  81219. }
  81220. this.bloom.threshold = value;
  81221. this._bloomThreshold = value;
  81222. },
  81223. enumerable: true,
  81224. configurable: true
  81225. });
  81226. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  81227. get: function () {
  81228. return this._bloomScale;
  81229. },
  81230. /**
  81231. * The scale of the bloom, lower value will provide better performance.
  81232. */
  81233. set: function (value) {
  81234. if (this._bloomScale === value) {
  81235. return;
  81236. }
  81237. this._bloomScale = value;
  81238. // recreate bloom and dispose old as this setting is not dynamic
  81239. this._rebuildBloom();
  81240. this._buildPipeline();
  81241. },
  81242. enumerable: true,
  81243. configurable: true
  81244. });
  81245. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  81246. get: function () {
  81247. return this._bloomEnabled;
  81248. },
  81249. /**
  81250. * Enable or disable the bloom from the pipeline
  81251. */
  81252. set: function (enabled) {
  81253. if (this._bloomEnabled === enabled) {
  81254. return;
  81255. }
  81256. this._bloomEnabled = enabled;
  81257. this._buildPipeline();
  81258. },
  81259. enumerable: true,
  81260. configurable: true
  81261. });
  81262. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  81263. // recreate bloom and dispose old as this setting is not dynamic
  81264. var oldBloom = this.bloom;
  81265. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  81266. this.bloom.threshold = oldBloom.threshold;
  81267. for (var i = 0; i < this._cameras.length; i++) {
  81268. oldBloom.disposeEffects(this._cameras[i]);
  81269. }
  81270. };
  81271. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  81272. /**
  81273. * If the depth of field is enabled.
  81274. */
  81275. get: function () {
  81276. return this._depthOfFieldEnabled;
  81277. },
  81278. set: function (enabled) {
  81279. if (this._depthOfFieldEnabled === enabled) {
  81280. return;
  81281. }
  81282. this._depthOfFieldEnabled = enabled;
  81283. this._buildPipeline();
  81284. },
  81285. enumerable: true,
  81286. configurable: true
  81287. });
  81288. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  81289. /**
  81290. * Blur level of the depth of field effect. (Higher blur will effect performance)
  81291. */
  81292. get: function () {
  81293. return this._depthOfFieldBlurLevel;
  81294. },
  81295. set: function (value) {
  81296. if (this._depthOfFieldBlurLevel === value) {
  81297. return;
  81298. }
  81299. this._depthOfFieldBlurLevel = value;
  81300. // recreate dof and dispose old as this setting is not dynamic
  81301. var oldDof = this.depthOfField;
  81302. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  81303. this.depthOfField.focalLength = oldDof.focalLength;
  81304. this.depthOfField.focusDistance = oldDof.focusDistance;
  81305. this.depthOfField.fStop = oldDof.fStop;
  81306. this.depthOfField.lensSize = oldDof.lensSize;
  81307. for (var i = 0; i < this._cameras.length; i++) {
  81308. oldDof.disposeEffects(this._cameras[i]);
  81309. }
  81310. this._buildPipeline();
  81311. },
  81312. enumerable: true,
  81313. configurable: true
  81314. });
  81315. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  81316. get: function () {
  81317. return this._fxaaEnabled;
  81318. },
  81319. /**
  81320. * If the anti aliasing is enabled.
  81321. */
  81322. set: function (enabled) {
  81323. if (this._fxaaEnabled === enabled) {
  81324. return;
  81325. }
  81326. this._fxaaEnabled = enabled;
  81327. this._buildPipeline();
  81328. },
  81329. enumerable: true,
  81330. configurable: true
  81331. });
  81332. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  81333. get: function () {
  81334. return this._samples;
  81335. },
  81336. /**
  81337. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81338. */
  81339. set: function (sampleCount) {
  81340. if (this._samples === sampleCount) {
  81341. return;
  81342. }
  81343. this._samples = sampleCount;
  81344. this._buildPipeline();
  81345. },
  81346. enumerable: true,
  81347. configurable: true
  81348. });
  81349. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  81350. get: function () {
  81351. return this._imageProcessingEnabled;
  81352. },
  81353. /**
  81354. * If image processing is enabled.
  81355. */
  81356. set: function (enabled) {
  81357. if (this._imageProcessingEnabled === enabled) {
  81358. return;
  81359. }
  81360. this._imageProcessingEnabled = enabled;
  81361. this._buildPipeline();
  81362. },
  81363. enumerable: true,
  81364. configurable: true
  81365. });
  81366. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  81367. get: function () {
  81368. return this._glowLayer == null;
  81369. },
  81370. /**
  81371. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  81372. */
  81373. set: function (enabled) {
  81374. if (enabled && !this._glowLayer) {
  81375. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  81376. }
  81377. else if (!enabled && this._glowLayer) {
  81378. this._glowLayer.dispose();
  81379. this._glowLayer = null;
  81380. }
  81381. },
  81382. enumerable: true,
  81383. configurable: true
  81384. });
  81385. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  81386. get: function () {
  81387. return this._chromaticAberrationEnabled;
  81388. },
  81389. /**
  81390. * Enable or disable the chromaticAberration process from the pipeline
  81391. */
  81392. set: function (enabled) {
  81393. if (this._chromaticAberrationEnabled === enabled) {
  81394. return;
  81395. }
  81396. this._chromaticAberrationEnabled = enabled;
  81397. this._buildPipeline();
  81398. },
  81399. enumerable: true,
  81400. configurable: true
  81401. });
  81402. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  81403. get: function () {
  81404. return this._grainEnabled;
  81405. },
  81406. /**
  81407. * Enable or disable the grain process from the pipeline
  81408. */
  81409. set: function (enabled) {
  81410. if (this._grainEnabled === enabled) {
  81411. return;
  81412. }
  81413. this._grainEnabled = enabled;
  81414. this._buildPipeline();
  81415. },
  81416. enumerable: true,
  81417. configurable: true
  81418. });
  81419. /**
  81420. * Force the compilation of the entire pipeline.
  81421. */
  81422. DefaultRenderingPipeline.prototype.prepare = function () {
  81423. var previousState = this._buildAllowed;
  81424. this._buildAllowed = true;
  81425. this._buildPipeline();
  81426. this._buildAllowed = previousState;
  81427. };
  81428. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  81429. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  81430. if (this._hasCleared) {
  81431. postProcess.autoClear = false;
  81432. }
  81433. else {
  81434. postProcess.autoClear = true;
  81435. this._scene.autoClear = false;
  81436. this._hasCleared = true;
  81437. }
  81438. if (!skipTextureSharing) {
  81439. if (this._prevPrevPostProcess) {
  81440. postProcess.shareOutputWith(this._prevPrevPostProcess);
  81441. }
  81442. else {
  81443. postProcess.useOwnOutput();
  81444. }
  81445. if (this._prevPostProcess) {
  81446. this._prevPrevPostProcess = this._prevPostProcess;
  81447. }
  81448. this._prevPostProcess = postProcess;
  81449. }
  81450. };
  81451. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  81452. var _this = this;
  81453. if (!this._buildAllowed) {
  81454. return;
  81455. }
  81456. this._scene.autoClear = true;
  81457. var engine = this._scene.getEngine();
  81458. this._disposePostProcesses();
  81459. if (this._cameras !== null) {
  81460. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81461. // get back cameras to be used to reattach pipeline
  81462. this._cameras = this._camerasToBeAttached.slice();
  81463. }
  81464. this._reset();
  81465. this._prevPostProcess = null;
  81466. this._prevPrevPostProcess = null;
  81467. this._hasCleared = false;
  81468. if (this.depthOfFieldEnabled) {
  81469. // Multi camera suport
  81470. if (this._cameras.length > 1) {
  81471. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  81472. var camera = _a[_i];
  81473. var depthRenderer = this._scene.enableDepthRenderer(camera);
  81474. depthRenderer.useOnlyInActiveCamera = true;
  81475. }
  81476. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  81477. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  81478. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  81479. }
  81480. });
  81481. }
  81482. else {
  81483. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81484. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  81485. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  81486. }
  81487. if (!this.depthOfField._isReady()) {
  81488. this.depthOfField._updateEffects();
  81489. }
  81490. this.addEffect(this.depthOfField);
  81491. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  81492. }
  81493. else {
  81494. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81495. }
  81496. if (this.bloomEnabled) {
  81497. if (!this.bloom._isReady()) {
  81498. this.bloom._updateEffects();
  81499. }
  81500. this.addEffect(this.bloom);
  81501. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  81502. }
  81503. if (this._imageProcessingEnabled) {
  81504. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81505. if (this._hdr) {
  81506. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  81507. this._setAutoClearAndTextureSharing(this.imageProcessing);
  81508. }
  81509. else {
  81510. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  81511. }
  81512. }
  81513. if (this.sharpenEnabled) {
  81514. if (!this.sharpen.isReady()) {
  81515. this.sharpen.updateEffect();
  81516. }
  81517. this.addEffect(this._sharpenEffect);
  81518. this._setAutoClearAndTextureSharing(this.sharpen);
  81519. }
  81520. if (this.grainEnabled) {
  81521. if (!this.grain.isReady()) {
  81522. this.grain.updateEffect();
  81523. }
  81524. this.addEffect(this._grainEffect);
  81525. this._setAutoClearAndTextureSharing(this.grain);
  81526. }
  81527. if (this.chromaticAberrationEnabled) {
  81528. if (!this.chromaticAberration.isReady()) {
  81529. this.chromaticAberration.updateEffect();
  81530. }
  81531. this.addEffect(this._chromaticAberrationEffect);
  81532. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  81533. }
  81534. if (this.fxaaEnabled) {
  81535. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81536. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  81537. this._setAutoClearAndTextureSharing(this.fxaa, true);
  81538. }
  81539. if (this._cameras !== null) {
  81540. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81541. }
  81542. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  81543. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81544. }
  81545. };
  81546. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  81547. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  81548. for (var i = 0; i < this._cameras.length; i++) {
  81549. var camera = this._cameras[i];
  81550. if (this.imageProcessing) {
  81551. this.imageProcessing.dispose(camera);
  81552. }
  81553. if (this.fxaa) {
  81554. this.fxaa.dispose(camera);
  81555. }
  81556. // These are created in the constructor and should not be disposed on every pipeline change
  81557. if (disposeNonRecreated) {
  81558. if (this.sharpen) {
  81559. this.sharpen.dispose(camera);
  81560. }
  81561. if (this.depthOfField) {
  81562. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81563. this.depthOfField.disposeEffects(camera);
  81564. }
  81565. if (this.bloom) {
  81566. this.bloom.disposeEffects(camera);
  81567. }
  81568. if (this.chromaticAberration) {
  81569. this.chromaticAberration.dispose(camera);
  81570. }
  81571. if (this.grain) {
  81572. this.grain.dispose(camera);
  81573. }
  81574. if (this._glowLayer) {
  81575. this._glowLayer.dispose();
  81576. }
  81577. }
  81578. }
  81579. this.imageProcessing = null;
  81580. this.fxaa = null;
  81581. if (disposeNonRecreated) {
  81582. this.sharpen = null;
  81583. this._sharpenEffect = null;
  81584. this.depthOfField = null;
  81585. this.bloom = null;
  81586. this.chromaticAberration = null;
  81587. this._chromaticAberrationEffect = null;
  81588. this.grain = null;
  81589. this._grainEffect = null;
  81590. this._glowLayer = null;
  81591. }
  81592. };
  81593. /**
  81594. * Adds a camera to the pipeline
  81595. * @param camera the camera to be added
  81596. */
  81597. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  81598. this._camerasToBeAttached.push(camera);
  81599. this._buildPipeline();
  81600. };
  81601. /**
  81602. * Removes a camera from the pipeline
  81603. * @param camera the camera to remove
  81604. */
  81605. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  81606. var index = this._camerasToBeAttached.indexOf(camera);
  81607. this._camerasToBeAttached.splice(index, 1);
  81608. this._buildPipeline();
  81609. };
  81610. /**
  81611. * Dispose of the pipeline and stop all post processes
  81612. */
  81613. DefaultRenderingPipeline.prototype.dispose = function () {
  81614. this._disposePostProcesses(true);
  81615. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81616. this._scene.autoClear = true;
  81617. if (this._resizeObserver) {
  81618. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  81619. this._resizeObserver = null;
  81620. }
  81621. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  81622. _super.prototype.dispose.call(this);
  81623. };
  81624. /**
  81625. * Serialize the rendering pipeline (Used when exporting)
  81626. * @returns the serialized object
  81627. */
  81628. DefaultRenderingPipeline.prototype.serialize = function () {
  81629. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81630. serializationObject.customType = "DefaultRenderingPipeline";
  81631. return serializationObject;
  81632. };
  81633. /**
  81634. * Parse the serialized pipeline
  81635. * @param source Source pipeline.
  81636. * @param scene The scene to load the pipeline to.
  81637. * @param rootUrl The URL of the serialized pipeline.
  81638. * @returns An instantiated pipeline from the serialized object.
  81639. */
  81640. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81641. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  81642. };
  81643. __decorate([
  81644. BABYLON.serialize()
  81645. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  81646. __decorate([
  81647. BABYLON.serialize()
  81648. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  81649. __decorate([
  81650. BABYLON.serialize()
  81651. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  81652. __decorate([
  81653. BABYLON.serialize()
  81654. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  81655. __decorate([
  81656. BABYLON.serialize()
  81657. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  81658. __decorate([
  81659. BABYLON.serialize()
  81660. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  81661. __decorate([
  81662. BABYLON.serialize()
  81663. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  81664. __decorate([
  81665. BABYLON.serialize()
  81666. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  81667. __decorate([
  81668. BABYLON.serialize()
  81669. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  81670. __decorate([
  81671. BABYLON.serialize()
  81672. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  81673. __decorate([
  81674. BABYLON.serialize()
  81675. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  81676. __decorate([
  81677. BABYLON.serialize()
  81678. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  81679. __decorate([
  81680. BABYLON.serialize()
  81681. ], DefaultRenderingPipeline.prototype, "samples", null);
  81682. __decorate([
  81683. BABYLON.serialize()
  81684. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  81685. __decorate([
  81686. BABYLON.serialize()
  81687. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  81688. __decorate([
  81689. BABYLON.serialize()
  81690. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  81691. __decorate([
  81692. BABYLON.serialize()
  81693. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  81694. return DefaultRenderingPipeline;
  81695. }(BABYLON.PostProcessRenderPipeline));
  81696. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  81697. })(BABYLON || (BABYLON = {}));
  81698. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  81699. var BABYLON;
  81700. (function (BABYLON) {
  81701. /**
  81702. * @hidden
  81703. */
  81704. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  81705. __extends(ImageProcessingConfigurationDefines, _super);
  81706. function ImageProcessingConfigurationDefines() {
  81707. var _this = _super.call(this) || this;
  81708. _this.IMAGEPROCESSING = false;
  81709. _this.VIGNETTE = false;
  81710. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  81711. _this.VIGNETTEBLENDMODEOPAQUE = false;
  81712. _this.TONEMAPPING = false;
  81713. _this.TONEMAPPING_ACES = false;
  81714. _this.CONTRAST = false;
  81715. _this.COLORCURVES = false;
  81716. _this.COLORGRADING = false;
  81717. _this.COLORGRADING3D = false;
  81718. _this.SAMPLER3DGREENDEPTH = false;
  81719. _this.SAMPLER3DBGRMAP = false;
  81720. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  81721. _this.EXPOSURE = false;
  81722. _this.rebuild();
  81723. return _this;
  81724. }
  81725. return ImageProcessingConfigurationDefines;
  81726. }(BABYLON.MaterialDefines));
  81727. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  81728. /**
  81729. * This groups together the common properties used for image processing either in direct forward pass
  81730. * or through post processing effect depending on the use of the image processing pipeline in your scene
  81731. * or not.
  81732. */
  81733. var ImageProcessingConfiguration = /** @class */ (function () {
  81734. function ImageProcessingConfiguration() {
  81735. /**
  81736. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  81737. */
  81738. this.colorCurves = new BABYLON.ColorCurves();
  81739. this._colorCurvesEnabled = false;
  81740. this._colorGradingEnabled = false;
  81741. this._colorGradingWithGreenDepth = true;
  81742. this._colorGradingBGR = true;
  81743. /** @hidden */
  81744. this._exposure = 1.0;
  81745. this._toneMappingEnabled = false;
  81746. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  81747. this._contrast = 1.0;
  81748. /**
  81749. * Vignette stretch size.
  81750. */
  81751. this.vignetteStretch = 0;
  81752. /**
  81753. * Vignette centre X Offset.
  81754. */
  81755. this.vignetteCentreX = 0;
  81756. /**
  81757. * Vignette centre Y Offset.
  81758. */
  81759. this.vignetteCentreY = 0;
  81760. /**
  81761. * Vignette weight or intensity of the vignette effect.
  81762. */
  81763. this.vignetteWeight = 1.5;
  81764. /**
  81765. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81766. * if vignetteEnabled is set to true.
  81767. */
  81768. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81769. /**
  81770. * Camera field of view used by the Vignette effect.
  81771. */
  81772. this.vignetteCameraFov = 0.5;
  81773. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  81774. this._vignetteEnabled = false;
  81775. this._applyByPostProcess = false;
  81776. this._isEnabled = true;
  81777. /**
  81778. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  81779. */
  81780. this.onUpdateParameters = new BABYLON.Observable();
  81781. }
  81782. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  81783. /**
  81784. * Gets wether the color curves effect is enabled.
  81785. */
  81786. get: function () {
  81787. return this._colorCurvesEnabled;
  81788. },
  81789. /**
  81790. * Sets wether the color curves effect is enabled.
  81791. */
  81792. set: function (value) {
  81793. if (this._colorCurvesEnabled === value) {
  81794. return;
  81795. }
  81796. this._colorCurvesEnabled = value;
  81797. this._updateParameters();
  81798. },
  81799. enumerable: true,
  81800. configurable: true
  81801. });
  81802. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  81803. /**
  81804. * Gets wether the color grading effect is enabled.
  81805. */
  81806. get: function () {
  81807. return this._colorGradingEnabled;
  81808. },
  81809. /**
  81810. * Sets wether the color grading effect is enabled.
  81811. */
  81812. set: function (value) {
  81813. if (this._colorGradingEnabled === value) {
  81814. return;
  81815. }
  81816. this._colorGradingEnabled = value;
  81817. this._updateParameters();
  81818. },
  81819. enumerable: true,
  81820. configurable: true
  81821. });
  81822. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  81823. /**
  81824. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  81825. */
  81826. get: function () {
  81827. return this._colorGradingWithGreenDepth;
  81828. },
  81829. /**
  81830. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  81831. */
  81832. set: function (value) {
  81833. if (this._colorGradingWithGreenDepth === value) {
  81834. return;
  81835. }
  81836. this._colorGradingWithGreenDepth = value;
  81837. this._updateParameters();
  81838. },
  81839. enumerable: true,
  81840. configurable: true
  81841. });
  81842. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  81843. /**
  81844. * Gets wether the color grading texture contains BGR values.
  81845. */
  81846. get: function () {
  81847. return this._colorGradingBGR;
  81848. },
  81849. /**
  81850. * Sets wether the color grading texture contains BGR values.
  81851. */
  81852. set: function (value) {
  81853. if (this._colorGradingBGR === value) {
  81854. return;
  81855. }
  81856. this._colorGradingBGR = value;
  81857. this._updateParameters();
  81858. },
  81859. enumerable: true,
  81860. configurable: true
  81861. });
  81862. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  81863. /**
  81864. * Gets the Exposure used in the effect.
  81865. */
  81866. get: function () {
  81867. return this._exposure;
  81868. },
  81869. /**
  81870. * Sets the Exposure used in the effect.
  81871. */
  81872. set: function (value) {
  81873. if (this._exposure === value) {
  81874. return;
  81875. }
  81876. this._exposure = value;
  81877. this._updateParameters();
  81878. },
  81879. enumerable: true,
  81880. configurable: true
  81881. });
  81882. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  81883. /**
  81884. * Gets wether the tone mapping effect is enabled.
  81885. */
  81886. get: function () {
  81887. return this._toneMappingEnabled;
  81888. },
  81889. /**
  81890. * Sets wether the tone mapping effect is enabled.
  81891. */
  81892. set: function (value) {
  81893. if (this._toneMappingEnabled === value) {
  81894. return;
  81895. }
  81896. this._toneMappingEnabled = value;
  81897. this._updateParameters();
  81898. },
  81899. enumerable: true,
  81900. configurable: true
  81901. });
  81902. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  81903. /**
  81904. * Gets the type of tone mapping effect.
  81905. */
  81906. get: function () {
  81907. return this._toneMappingType;
  81908. },
  81909. /**
  81910. * Sets the type of tone mapping effect used in BabylonJS.
  81911. */
  81912. set: function (value) {
  81913. if (this._toneMappingType === value) {
  81914. return;
  81915. }
  81916. this._toneMappingType = value;
  81917. this._updateParameters();
  81918. },
  81919. enumerable: true,
  81920. configurable: true
  81921. });
  81922. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  81923. /**
  81924. * Gets the contrast used in the effect.
  81925. */
  81926. get: function () {
  81927. return this._contrast;
  81928. },
  81929. /**
  81930. * Sets the contrast used in the effect.
  81931. */
  81932. set: function (value) {
  81933. if (this._contrast === value) {
  81934. return;
  81935. }
  81936. this._contrast = value;
  81937. this._updateParameters();
  81938. },
  81939. enumerable: true,
  81940. configurable: true
  81941. });
  81942. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  81943. /**
  81944. * Gets the vignette blend mode allowing different kind of effect.
  81945. */
  81946. get: function () {
  81947. return this._vignetteBlendMode;
  81948. },
  81949. /**
  81950. * Sets the vignette blend mode allowing different kind of effect.
  81951. */
  81952. set: function (value) {
  81953. if (this._vignetteBlendMode === value) {
  81954. return;
  81955. }
  81956. this._vignetteBlendMode = value;
  81957. this._updateParameters();
  81958. },
  81959. enumerable: true,
  81960. configurable: true
  81961. });
  81962. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  81963. /**
  81964. * Gets wether the vignette effect is enabled.
  81965. */
  81966. get: function () {
  81967. return this._vignetteEnabled;
  81968. },
  81969. /**
  81970. * Sets wether the vignette effect is enabled.
  81971. */
  81972. set: function (value) {
  81973. if (this._vignetteEnabled === value) {
  81974. return;
  81975. }
  81976. this._vignetteEnabled = value;
  81977. this._updateParameters();
  81978. },
  81979. enumerable: true,
  81980. configurable: true
  81981. });
  81982. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  81983. /**
  81984. * Gets wether the image processing is applied through a post process or not.
  81985. */
  81986. get: function () {
  81987. return this._applyByPostProcess;
  81988. },
  81989. /**
  81990. * Sets wether the image processing is applied through a post process or not.
  81991. */
  81992. set: function (value) {
  81993. if (this._applyByPostProcess === value) {
  81994. return;
  81995. }
  81996. this._applyByPostProcess = value;
  81997. this._updateParameters();
  81998. },
  81999. enumerable: true,
  82000. configurable: true
  82001. });
  82002. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  82003. /**
  82004. * Gets wether the image processing is enabled or not.
  82005. */
  82006. get: function () {
  82007. return this._isEnabled;
  82008. },
  82009. /**
  82010. * Sets wether the image processing is enabled or not.
  82011. */
  82012. set: function (value) {
  82013. if (this._isEnabled === value) {
  82014. return;
  82015. }
  82016. this._isEnabled = value;
  82017. this._updateParameters();
  82018. },
  82019. enumerable: true,
  82020. configurable: true
  82021. });
  82022. /**
  82023. * Method called each time the image processing information changes requires to recompile the effect.
  82024. */
  82025. ImageProcessingConfiguration.prototype._updateParameters = function () {
  82026. this.onUpdateParameters.notifyObservers(this);
  82027. };
  82028. ImageProcessingConfiguration.prototype.getClassName = function () {
  82029. return "ImageProcessingConfiguration";
  82030. };
  82031. /**
  82032. * Prepare the list of uniforms associated with the Image Processing effects.
  82033. * @param uniformsList The list of uniforms used in the effect
  82034. * @param defines the list of defines currently in use
  82035. */
  82036. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  82037. if (defines.EXPOSURE) {
  82038. uniforms.push("exposureLinear");
  82039. }
  82040. if (defines.CONTRAST) {
  82041. uniforms.push("contrast");
  82042. }
  82043. if (defines.COLORGRADING) {
  82044. uniforms.push("colorTransformSettings");
  82045. }
  82046. if (defines.VIGNETTE) {
  82047. uniforms.push("vInverseScreenSize");
  82048. uniforms.push("vignetteSettings1");
  82049. uniforms.push("vignetteSettings2");
  82050. }
  82051. if (defines.COLORCURVES) {
  82052. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  82053. }
  82054. };
  82055. /**
  82056. * Prepare the list of samplers associated with the Image Processing effects.
  82057. * @param uniformsList The list of uniforms used in the effect
  82058. * @param defines the list of defines currently in use
  82059. */
  82060. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  82061. if (defines.COLORGRADING) {
  82062. samplersList.push("txColorTransform");
  82063. }
  82064. };
  82065. /**
  82066. * Prepare the list of defines associated to the shader.
  82067. * @param defines the list of defines to complete
  82068. */
  82069. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  82070. if (forPostProcess === void 0) { forPostProcess = false; }
  82071. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  82072. defines.VIGNETTE = false;
  82073. defines.TONEMAPPING = false;
  82074. defines.TONEMAPPING_ACES = false;
  82075. defines.CONTRAST = false;
  82076. defines.EXPOSURE = false;
  82077. defines.COLORCURVES = false;
  82078. defines.COLORGRADING = false;
  82079. defines.COLORGRADING3D = false;
  82080. defines.IMAGEPROCESSING = false;
  82081. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  82082. return;
  82083. }
  82084. defines.VIGNETTE = this.vignetteEnabled;
  82085. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  82086. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  82087. defines.TONEMAPPING = this.toneMappingEnabled;
  82088. switch (this._toneMappingType) {
  82089. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  82090. defines.TONEMAPPING_ACES = true;
  82091. break;
  82092. }
  82093. defines.CONTRAST = (this.contrast !== 1.0);
  82094. defines.EXPOSURE = (this.exposure !== 1.0);
  82095. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  82096. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  82097. if (defines.COLORGRADING) {
  82098. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  82099. }
  82100. else {
  82101. defines.COLORGRADING3D = false;
  82102. }
  82103. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  82104. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  82105. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  82106. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  82107. };
  82108. /**
  82109. * Returns true if all the image processing information are ready.
  82110. */
  82111. ImageProcessingConfiguration.prototype.isReady = function () {
  82112. // Color Grading texure can not be none blocking.
  82113. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  82114. };
  82115. /**
  82116. * Binds the image processing to the shader.
  82117. * @param effect The effect to bind to
  82118. */
  82119. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  82120. if (aspectRatio === void 0) { aspectRatio = 1; }
  82121. // Color Curves
  82122. if (this._colorCurvesEnabled && this.colorCurves) {
  82123. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  82124. }
  82125. // Vignette
  82126. if (this._vignetteEnabled) {
  82127. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  82128. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  82129. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  82130. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  82131. var vignetteScaleX = vignetteScaleY * aspectRatio;
  82132. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  82133. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  82134. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  82135. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  82136. var vignettePower = -2.0 * this.vignetteWeight;
  82137. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  82138. }
  82139. // Exposure
  82140. effect.setFloat("exposureLinear", this.exposure);
  82141. // Contrast
  82142. effect.setFloat("contrast", this.contrast);
  82143. // Color transform settings
  82144. if (this.colorGradingTexture) {
  82145. effect.setTexture("txColorTransform", this.colorGradingTexture);
  82146. var textureSize = this.colorGradingTexture.getSize().height;
  82147. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  82148. 0.5 / textureSize, // textureOffset
  82149. textureSize, // textureSize
  82150. this.colorGradingTexture.level // weight
  82151. );
  82152. }
  82153. };
  82154. /**
  82155. * Clones the current image processing instance.
  82156. * @return The cloned image processing
  82157. */
  82158. ImageProcessingConfiguration.prototype.clone = function () {
  82159. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  82160. };
  82161. /**
  82162. * Serializes the current image processing instance to a json representation.
  82163. * @return a JSON representation
  82164. */
  82165. ImageProcessingConfiguration.prototype.serialize = function () {
  82166. return BABYLON.SerializationHelper.Serialize(this);
  82167. };
  82168. /**
  82169. * Parses the image processing from a json representation.
  82170. * @param source the JSON source to parse
  82171. * @return The parsed image processing
  82172. */
  82173. ImageProcessingConfiguration.Parse = function (source) {
  82174. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  82175. };
  82176. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  82177. /**
  82178. * Used to apply the vignette as a mix with the pixel color.
  82179. */
  82180. get: function () {
  82181. return this._VIGNETTEMODE_MULTIPLY;
  82182. },
  82183. enumerable: true,
  82184. configurable: true
  82185. });
  82186. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  82187. /**
  82188. * Used to apply the vignette as a replacement of the pixel color.
  82189. */
  82190. get: function () {
  82191. return this._VIGNETTEMODE_OPAQUE;
  82192. },
  82193. enumerable: true,
  82194. configurable: true
  82195. });
  82196. /**
  82197. * Default tone mapping applied in BabylonJS.
  82198. */
  82199. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  82200. /**
  82201. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  82202. * to other engines rendering to increase portability.
  82203. */
  82204. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  82205. // Static constants associated to the image processing.
  82206. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  82207. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  82208. __decorate([
  82209. BABYLON.serializeAsColorCurves()
  82210. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  82211. __decorate([
  82212. BABYLON.serialize()
  82213. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  82214. __decorate([
  82215. BABYLON.serializeAsTexture()
  82216. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  82217. __decorate([
  82218. BABYLON.serialize()
  82219. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  82220. __decorate([
  82221. BABYLON.serialize()
  82222. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  82223. __decorate([
  82224. BABYLON.serialize()
  82225. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  82226. __decorate([
  82227. BABYLON.serialize()
  82228. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  82229. __decorate([
  82230. BABYLON.serialize()
  82231. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  82232. __decorate([
  82233. BABYLON.serialize()
  82234. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  82235. __decorate([
  82236. BABYLON.serialize()
  82237. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  82238. __decorate([
  82239. BABYLON.serialize()
  82240. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  82241. __decorate([
  82242. BABYLON.serialize()
  82243. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  82244. __decorate([
  82245. BABYLON.serialize()
  82246. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  82247. __decorate([
  82248. BABYLON.serialize()
  82249. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  82250. __decorate([
  82251. BABYLON.serializeAsColor4()
  82252. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  82253. __decorate([
  82254. BABYLON.serialize()
  82255. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  82256. __decorate([
  82257. BABYLON.serialize()
  82258. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  82259. __decorate([
  82260. BABYLON.serialize()
  82261. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  82262. __decorate([
  82263. BABYLON.serialize()
  82264. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  82265. __decorate([
  82266. BABYLON.serialize()
  82267. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  82268. return ImageProcessingConfiguration;
  82269. }());
  82270. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  82271. })(BABYLON || (BABYLON = {}));
  82272. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  82273. var BABYLON;
  82274. (function (BABYLON) {
  82275. /**
  82276. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  82277. * It can help converting any input color in a desired output one. This can then be used to create effects
  82278. * from sepia, black and white to sixties or futuristic rendering...
  82279. *
  82280. * The only supported format is currently 3dl.
  82281. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  82282. */
  82283. var ColorGradingTexture = /** @class */ (function (_super) {
  82284. __extends(ColorGradingTexture, _super);
  82285. /**
  82286. * Instantiates a ColorGradingTexture from the following parameters.
  82287. *
  82288. * @param url The location of the color gradind data (currently only supporting 3dl)
  82289. * @param scene The scene the texture will be used in
  82290. */
  82291. function ColorGradingTexture(url, scene) {
  82292. var _this = _super.call(this, scene) || this;
  82293. if (!url) {
  82294. return _this;
  82295. }
  82296. _this._engine = scene.getEngine();
  82297. _this._textureMatrix = BABYLON.Matrix.Identity();
  82298. _this.name = url;
  82299. _this.url = url;
  82300. _this.hasAlpha = false;
  82301. _this.isCube = false;
  82302. _this.is3D = _this._engine.webGLVersion > 1;
  82303. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82304. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82305. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82306. _this.anisotropicFilteringLevel = 1;
  82307. _this._texture = _this._getFromCache(url, true);
  82308. if (!_this._texture) {
  82309. if (!scene.useDelayedTextureLoading) {
  82310. _this.loadTexture();
  82311. }
  82312. else {
  82313. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82314. }
  82315. }
  82316. return _this;
  82317. }
  82318. /**
  82319. * Returns the texture matrix used in most of the material.
  82320. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  82321. */
  82322. ColorGradingTexture.prototype.getTextureMatrix = function () {
  82323. return this._textureMatrix;
  82324. };
  82325. /**
  82326. * Occurs when the file being loaded is a .3dl LUT file.
  82327. */
  82328. ColorGradingTexture.prototype.load3dlTexture = function () {
  82329. var engine = this._engine;
  82330. var texture;
  82331. if (engine.webGLVersion === 1) {
  82332. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82333. }
  82334. else {
  82335. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82336. }
  82337. this._texture = texture;
  82338. var callback = function (text) {
  82339. if (typeof text !== "string") {
  82340. return;
  82341. }
  82342. var data = null;
  82343. var tempData = null;
  82344. var line;
  82345. var lines = text.split('\n');
  82346. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  82347. var maxColor = 0;
  82348. for (var i = 0; i < lines.length; i++) {
  82349. line = lines[i];
  82350. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  82351. continue;
  82352. if (line.indexOf('#') === 0)
  82353. continue;
  82354. var words = line.split(" ");
  82355. if (size === 0) {
  82356. // Number of space + one
  82357. size = words.length;
  82358. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  82359. tempData = new Float32Array(size * size * size * 4);
  82360. continue;
  82361. }
  82362. if (size != 0) {
  82363. var r = Math.max(parseInt(words[0]), 0);
  82364. var g = Math.max(parseInt(words[1]), 0);
  82365. var b = Math.max(parseInt(words[2]), 0);
  82366. maxColor = Math.max(r, maxColor);
  82367. maxColor = Math.max(g, maxColor);
  82368. maxColor = Math.max(b, maxColor);
  82369. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  82370. if (tempData) {
  82371. tempData[pixelStorageIndex + 0] = r;
  82372. tempData[pixelStorageIndex + 1] = g;
  82373. tempData[pixelStorageIndex + 2] = b;
  82374. }
  82375. pixelIndexSlice++;
  82376. if (pixelIndexSlice % size == 0) {
  82377. pixelIndexH++;
  82378. pixelIndexSlice = 0;
  82379. if (pixelIndexH % size == 0) {
  82380. pixelIndexW++;
  82381. pixelIndexH = 0;
  82382. }
  82383. }
  82384. }
  82385. }
  82386. if (tempData && data) {
  82387. for (var i = 0; i < tempData.length; i++) {
  82388. if (i > 0 && (i + 1) % 4 === 0) {
  82389. data[i] = 255;
  82390. }
  82391. else {
  82392. var value = tempData[i];
  82393. data[i] = (value / maxColor * 255);
  82394. }
  82395. }
  82396. }
  82397. if (texture.is3D) {
  82398. texture.updateSize(size, size, size);
  82399. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82400. }
  82401. else {
  82402. texture.updateSize(size * size, size);
  82403. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82404. }
  82405. };
  82406. var scene = this.getScene();
  82407. if (scene) {
  82408. scene._loadFile(this.url, callback);
  82409. }
  82410. else {
  82411. this._engine._loadFile(this.url, callback);
  82412. }
  82413. return this._texture;
  82414. };
  82415. /**
  82416. * Starts the loading process of the texture.
  82417. */
  82418. ColorGradingTexture.prototype.loadTexture = function () {
  82419. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  82420. this.load3dlTexture();
  82421. }
  82422. };
  82423. /**
  82424. * Clones the color gradind texture.
  82425. */
  82426. ColorGradingTexture.prototype.clone = function () {
  82427. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  82428. // Base texture
  82429. newTexture.level = this.level;
  82430. return newTexture;
  82431. };
  82432. /**
  82433. * Called during delayed load for textures.
  82434. */
  82435. ColorGradingTexture.prototype.delayLoad = function () {
  82436. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82437. return;
  82438. }
  82439. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82440. this._texture = this._getFromCache(this.url, true);
  82441. if (!this._texture) {
  82442. this.loadTexture();
  82443. }
  82444. };
  82445. /**
  82446. * Parses a color grading texture serialized by Babylon.
  82447. * @param parsedTexture The texture information being parsedTexture
  82448. * @param scene The scene to load the texture in
  82449. * @param rootUrl The root url of the data assets to load
  82450. * @return A color gradind texture
  82451. */
  82452. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82453. var texture = null;
  82454. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82455. texture = new ColorGradingTexture(parsedTexture.name, scene);
  82456. texture.name = parsedTexture.name;
  82457. texture.level = parsedTexture.level;
  82458. }
  82459. return texture;
  82460. };
  82461. /**
  82462. * Serializes the LUT texture to json format.
  82463. */
  82464. ColorGradingTexture.prototype.serialize = function () {
  82465. if (!this.name) {
  82466. return null;
  82467. }
  82468. var serializationObject = {};
  82469. serializationObject.name = this.name;
  82470. serializationObject.level = this.level;
  82471. serializationObject.customType = "BABYLON.ColorGradingTexture";
  82472. return serializationObject;
  82473. };
  82474. /**
  82475. * Empty line regex stored for GC.
  82476. */
  82477. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  82478. return ColorGradingTexture;
  82479. }(BABYLON.BaseTexture));
  82480. BABYLON.ColorGradingTexture = ColorGradingTexture;
  82481. })(BABYLON || (BABYLON = {}));
  82482. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  82483. var BABYLON;
  82484. (function (BABYLON) {
  82485. /**
  82486. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82487. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82488. * 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;
  82489. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82490. */
  82491. var ColorCurves = /** @class */ (function () {
  82492. function ColorCurves() {
  82493. this._dirty = true;
  82494. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  82495. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  82496. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82497. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  82498. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82499. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  82500. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  82501. this._globalHue = 30;
  82502. this._globalDensity = 0;
  82503. this._globalSaturation = 0;
  82504. this._globalExposure = 0;
  82505. this._highlightsHue = 30;
  82506. this._highlightsDensity = 0;
  82507. this._highlightsSaturation = 0;
  82508. this._highlightsExposure = 0;
  82509. this._midtonesHue = 30;
  82510. this._midtonesDensity = 0;
  82511. this._midtonesSaturation = 0;
  82512. this._midtonesExposure = 0;
  82513. this._shadowsHue = 30;
  82514. this._shadowsDensity = 0;
  82515. this._shadowsSaturation = 0;
  82516. this._shadowsExposure = 0;
  82517. }
  82518. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  82519. /**
  82520. * Gets the global Hue value.
  82521. * 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).
  82522. */
  82523. get: function () {
  82524. return this._globalHue;
  82525. },
  82526. /**
  82527. * Sets the global Hue value.
  82528. * 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).
  82529. */
  82530. set: function (value) {
  82531. this._globalHue = value;
  82532. this._dirty = true;
  82533. },
  82534. enumerable: true,
  82535. configurable: true
  82536. });
  82537. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  82538. /**
  82539. * Gets the global Density value.
  82540. * 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.
  82541. * Values less than zero provide a filter of opposite hue.
  82542. */
  82543. get: function () {
  82544. return this._globalDensity;
  82545. },
  82546. /**
  82547. * Sets the global Density value.
  82548. * 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.
  82549. * Values less than zero provide a filter of opposite hue.
  82550. */
  82551. set: function (value) {
  82552. this._globalDensity = value;
  82553. this._dirty = true;
  82554. },
  82555. enumerable: true,
  82556. configurable: true
  82557. });
  82558. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  82559. /**
  82560. * Gets the global Saturation value.
  82561. * 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.
  82562. */
  82563. get: function () {
  82564. return this._globalSaturation;
  82565. },
  82566. /**
  82567. * Sets the global Saturation value.
  82568. * 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.
  82569. */
  82570. set: function (value) {
  82571. this._globalSaturation = value;
  82572. this._dirty = true;
  82573. },
  82574. enumerable: true,
  82575. configurable: true
  82576. });
  82577. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  82578. /**
  82579. * Gets the global Exposure value.
  82580. * 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.
  82581. */
  82582. get: function () {
  82583. return this._globalExposure;
  82584. },
  82585. /**
  82586. * Sets the global Exposure value.
  82587. * 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.
  82588. */
  82589. set: function (value) {
  82590. this._globalExposure = value;
  82591. this._dirty = true;
  82592. },
  82593. enumerable: true,
  82594. configurable: true
  82595. });
  82596. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  82597. /**
  82598. * Gets the highlights Hue value.
  82599. * 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).
  82600. */
  82601. get: function () {
  82602. return this._highlightsHue;
  82603. },
  82604. /**
  82605. * Sets the highlights Hue value.
  82606. * 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).
  82607. */
  82608. set: function (value) {
  82609. this._highlightsHue = value;
  82610. this._dirty = true;
  82611. },
  82612. enumerable: true,
  82613. configurable: true
  82614. });
  82615. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  82616. /**
  82617. * Gets the highlights Density value.
  82618. * 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.
  82619. * Values less than zero provide a filter of opposite hue.
  82620. */
  82621. get: function () {
  82622. return this._highlightsDensity;
  82623. },
  82624. /**
  82625. * Sets the highlights Density value.
  82626. * 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.
  82627. * Values less than zero provide a filter of opposite hue.
  82628. */
  82629. set: function (value) {
  82630. this._highlightsDensity = value;
  82631. this._dirty = true;
  82632. },
  82633. enumerable: true,
  82634. configurable: true
  82635. });
  82636. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  82637. /**
  82638. * Gets the highlights Saturation value.
  82639. * 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.
  82640. */
  82641. get: function () {
  82642. return this._highlightsSaturation;
  82643. },
  82644. /**
  82645. * Sets the highlights Saturation value.
  82646. * 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.
  82647. */
  82648. set: function (value) {
  82649. this._highlightsSaturation = value;
  82650. this._dirty = true;
  82651. },
  82652. enumerable: true,
  82653. configurable: true
  82654. });
  82655. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  82656. /**
  82657. * Gets the highlights Exposure value.
  82658. * 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.
  82659. */
  82660. get: function () {
  82661. return this._highlightsExposure;
  82662. },
  82663. /**
  82664. * Sets the highlights Exposure value.
  82665. * 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.
  82666. */
  82667. set: function (value) {
  82668. this._highlightsExposure = value;
  82669. this._dirty = true;
  82670. },
  82671. enumerable: true,
  82672. configurable: true
  82673. });
  82674. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  82675. /**
  82676. * Gets the midtones Hue value.
  82677. * 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).
  82678. */
  82679. get: function () {
  82680. return this._midtonesHue;
  82681. },
  82682. /**
  82683. * Sets the midtones Hue value.
  82684. * 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).
  82685. */
  82686. set: function (value) {
  82687. this._midtonesHue = value;
  82688. this._dirty = true;
  82689. },
  82690. enumerable: true,
  82691. configurable: true
  82692. });
  82693. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  82694. /**
  82695. * Gets the midtones Density value.
  82696. * 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.
  82697. * Values less than zero provide a filter of opposite hue.
  82698. */
  82699. get: function () {
  82700. return this._midtonesDensity;
  82701. },
  82702. /**
  82703. * Sets the midtones Density value.
  82704. * 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.
  82705. * Values less than zero provide a filter of opposite hue.
  82706. */
  82707. set: function (value) {
  82708. this._midtonesDensity = value;
  82709. this._dirty = true;
  82710. },
  82711. enumerable: true,
  82712. configurable: true
  82713. });
  82714. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  82715. /**
  82716. * Gets the midtones Saturation value.
  82717. * 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.
  82718. */
  82719. get: function () {
  82720. return this._midtonesSaturation;
  82721. },
  82722. /**
  82723. * Sets the midtones Saturation value.
  82724. * 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.
  82725. */
  82726. set: function (value) {
  82727. this._midtonesSaturation = value;
  82728. this._dirty = true;
  82729. },
  82730. enumerable: true,
  82731. configurable: true
  82732. });
  82733. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  82734. /**
  82735. * Gets the midtones Exposure value.
  82736. * 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.
  82737. */
  82738. get: function () {
  82739. return this._midtonesExposure;
  82740. },
  82741. /**
  82742. * Sets the midtones Exposure value.
  82743. * 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.
  82744. */
  82745. set: function (value) {
  82746. this._midtonesExposure = value;
  82747. this._dirty = true;
  82748. },
  82749. enumerable: true,
  82750. configurable: true
  82751. });
  82752. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  82753. /**
  82754. * Gets the shadows Hue value.
  82755. * 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).
  82756. */
  82757. get: function () {
  82758. return this._shadowsHue;
  82759. },
  82760. /**
  82761. * Sets the shadows Hue value.
  82762. * 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).
  82763. */
  82764. set: function (value) {
  82765. this._shadowsHue = value;
  82766. this._dirty = true;
  82767. },
  82768. enumerable: true,
  82769. configurable: true
  82770. });
  82771. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  82772. /**
  82773. * Gets the shadows Density value.
  82774. * 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.
  82775. * Values less than zero provide a filter of opposite hue.
  82776. */
  82777. get: function () {
  82778. return this._shadowsDensity;
  82779. },
  82780. /**
  82781. * Sets the shadows Density value.
  82782. * 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.
  82783. * Values less than zero provide a filter of opposite hue.
  82784. */
  82785. set: function (value) {
  82786. this._shadowsDensity = value;
  82787. this._dirty = true;
  82788. },
  82789. enumerable: true,
  82790. configurable: true
  82791. });
  82792. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  82793. /**
  82794. * Gets the shadows Saturation value.
  82795. * 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.
  82796. */
  82797. get: function () {
  82798. return this._shadowsSaturation;
  82799. },
  82800. /**
  82801. * Sets the shadows Saturation value.
  82802. * 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.
  82803. */
  82804. set: function (value) {
  82805. this._shadowsSaturation = value;
  82806. this._dirty = true;
  82807. },
  82808. enumerable: true,
  82809. configurable: true
  82810. });
  82811. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  82812. /**
  82813. * Gets the shadows Exposure value.
  82814. * 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.
  82815. */
  82816. get: function () {
  82817. return this._shadowsExposure;
  82818. },
  82819. /**
  82820. * Sets the shadows Exposure value.
  82821. * 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.
  82822. */
  82823. set: function (value) {
  82824. this._shadowsExposure = value;
  82825. this._dirty = true;
  82826. },
  82827. enumerable: true,
  82828. configurable: true
  82829. });
  82830. ColorCurves.prototype.getClassName = function () {
  82831. return "ColorCurves";
  82832. };
  82833. /**
  82834. * Binds the color curves to the shader.
  82835. * @param colorCurves The color curve to bind
  82836. * @param effect The effect to bind to
  82837. */
  82838. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  82839. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  82840. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  82841. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  82842. if (colorCurves._dirty) {
  82843. colorCurves._dirty = false;
  82844. // Fill in global info.
  82845. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  82846. // Compute highlights info.
  82847. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  82848. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  82849. // Compute midtones info.
  82850. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  82851. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  82852. // Compute shadows info.
  82853. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  82854. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  82855. // Compute deltas (neutral is midtones).
  82856. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  82857. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  82858. }
  82859. if (effect) {
  82860. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  82861. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  82862. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  82863. }
  82864. };
  82865. /**
  82866. * Prepare the list of uniforms associated with the ColorCurves effects.
  82867. * @param uniformsList The list of uniforms used in the effect
  82868. */
  82869. ColorCurves.PrepareUniforms = function (uniformsList) {
  82870. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  82871. };
  82872. /**
  82873. * Returns color grading data based on a hue, density, saturation and exposure value.
  82874. * @param filterHue The hue of the color filter.
  82875. * @param filterDensity The density of the color filter.
  82876. * @param saturation The saturation.
  82877. * @param exposure The exposure.
  82878. * @param result The result data container.
  82879. */
  82880. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  82881. if (hue == null) {
  82882. return;
  82883. }
  82884. hue = ColorCurves.clamp(hue, 0, 360);
  82885. density = ColorCurves.clamp(density, -100, 100);
  82886. saturation = ColorCurves.clamp(saturation, -100, 100);
  82887. exposure = ColorCurves.clamp(exposure, -100, 100);
  82888. // Remap the slider/config filter density with non-linear mapping and also scale by half
  82889. // so that the maximum filter density is only 50% control. This provides fine control
  82890. // for small values and reasonable range.
  82891. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  82892. density *= 0.5;
  82893. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  82894. if (density < 0) {
  82895. density *= -1;
  82896. hue = (hue + 180) % 360;
  82897. }
  82898. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  82899. result.scaleToRef(2, result);
  82900. result.a = 1 + 0.01 * saturation;
  82901. };
  82902. /**
  82903. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  82904. * @param value The input slider value in range [-100,100].
  82905. * @returns Adjusted value.
  82906. */
  82907. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  82908. value /= 100;
  82909. var x = Math.abs(value);
  82910. x = Math.pow(x, 2);
  82911. if (value < 0) {
  82912. x *= -1;
  82913. }
  82914. x *= 100;
  82915. return x;
  82916. };
  82917. /**
  82918. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  82919. * @param hue The hue (H) input.
  82920. * @param saturation The saturation (S) input.
  82921. * @param brightness The brightness (B) input.
  82922. * @result An RGBA color represented as Vector4.
  82923. */
  82924. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  82925. var h = ColorCurves.clamp(hue, 0, 360);
  82926. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  82927. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  82928. if (s === 0) {
  82929. result.r = v;
  82930. result.g = v;
  82931. result.b = v;
  82932. }
  82933. else {
  82934. // sector 0 to 5
  82935. h /= 60;
  82936. var i = Math.floor(h);
  82937. // fractional part of h
  82938. var f = h - i;
  82939. var p = v * (1 - s);
  82940. var q = v * (1 - s * f);
  82941. var t = v * (1 - s * (1 - f));
  82942. switch (i) {
  82943. case 0:
  82944. result.r = v;
  82945. result.g = t;
  82946. result.b = p;
  82947. break;
  82948. case 1:
  82949. result.r = q;
  82950. result.g = v;
  82951. result.b = p;
  82952. break;
  82953. case 2:
  82954. result.r = p;
  82955. result.g = v;
  82956. result.b = t;
  82957. break;
  82958. case 3:
  82959. result.r = p;
  82960. result.g = q;
  82961. result.b = v;
  82962. break;
  82963. case 4:
  82964. result.r = t;
  82965. result.g = p;
  82966. result.b = v;
  82967. break;
  82968. default: // case 5:
  82969. result.r = v;
  82970. result.g = p;
  82971. result.b = q;
  82972. break;
  82973. }
  82974. }
  82975. result.a = 1;
  82976. };
  82977. /**
  82978. * Returns a value clamped between min and max
  82979. * @param value The value to clamp
  82980. * @param min The minimum of value
  82981. * @param max The maximum of value
  82982. * @returns The clamped value.
  82983. */
  82984. ColorCurves.clamp = function (value, min, max) {
  82985. return Math.min(Math.max(value, min), max);
  82986. };
  82987. /**
  82988. * Clones the current color curve instance.
  82989. * @return The cloned curves
  82990. */
  82991. ColorCurves.prototype.clone = function () {
  82992. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  82993. };
  82994. /**
  82995. * Serializes the current color curve instance to a json representation.
  82996. * @return a JSON representation
  82997. */
  82998. ColorCurves.prototype.serialize = function () {
  82999. return BABYLON.SerializationHelper.Serialize(this);
  83000. };
  83001. /**
  83002. * Parses the color curve from a json representation.
  83003. * @param source the JSON source to parse
  83004. * @return The parsed curves
  83005. */
  83006. ColorCurves.Parse = function (source) {
  83007. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  83008. };
  83009. __decorate([
  83010. BABYLON.serialize()
  83011. ], ColorCurves.prototype, "_globalHue", void 0);
  83012. __decorate([
  83013. BABYLON.serialize()
  83014. ], ColorCurves.prototype, "_globalDensity", void 0);
  83015. __decorate([
  83016. BABYLON.serialize()
  83017. ], ColorCurves.prototype, "_globalSaturation", void 0);
  83018. __decorate([
  83019. BABYLON.serialize()
  83020. ], ColorCurves.prototype, "_globalExposure", void 0);
  83021. __decorate([
  83022. BABYLON.serialize()
  83023. ], ColorCurves.prototype, "_highlightsHue", void 0);
  83024. __decorate([
  83025. BABYLON.serialize()
  83026. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  83027. __decorate([
  83028. BABYLON.serialize()
  83029. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  83030. __decorate([
  83031. BABYLON.serialize()
  83032. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  83033. __decorate([
  83034. BABYLON.serialize()
  83035. ], ColorCurves.prototype, "_midtonesHue", void 0);
  83036. __decorate([
  83037. BABYLON.serialize()
  83038. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  83039. __decorate([
  83040. BABYLON.serialize()
  83041. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  83042. __decorate([
  83043. BABYLON.serialize()
  83044. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  83045. return ColorCurves;
  83046. }());
  83047. BABYLON.ColorCurves = ColorCurves;
  83048. })(BABYLON || (BABYLON = {}));
  83049. //# sourceMappingURL=babylon.colorCurves.js.map
  83050. var BABYLON;
  83051. (function (BABYLON) {
  83052. var RefractionPostProcess = /** @class */ (function (_super) {
  83053. __extends(RefractionPostProcess, _super);
  83054. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  83055. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  83056. _this.color = color;
  83057. _this.depth = depth;
  83058. _this.colorLevel = colorLevel;
  83059. _this._ownRefractionTexture = true;
  83060. _this.onActivateObservable.add(function (cam) {
  83061. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  83062. });
  83063. _this.onApplyObservable.add(function (effect) {
  83064. effect.setColor3("baseColor", _this.color);
  83065. effect.setFloat("depth", _this.depth);
  83066. effect.setFloat("colorLevel", _this.colorLevel);
  83067. effect.setTexture("refractionSampler", _this._refTexture);
  83068. });
  83069. return _this;
  83070. }
  83071. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  83072. /**
  83073. * Gets or sets the refraction texture
  83074. * Please note that you are responsible for disposing the texture if you set it manually
  83075. */
  83076. get: function () {
  83077. return this._refTexture;
  83078. },
  83079. set: function (value) {
  83080. if (this._refTexture && this._ownRefractionTexture) {
  83081. this._refTexture.dispose();
  83082. }
  83083. this._refTexture = value;
  83084. this._ownRefractionTexture = false;
  83085. },
  83086. enumerable: true,
  83087. configurable: true
  83088. });
  83089. // Methods
  83090. RefractionPostProcess.prototype.dispose = function (camera) {
  83091. if (this._refTexture && this._ownRefractionTexture) {
  83092. this._refTexture.dispose();
  83093. this._refTexture = null;
  83094. }
  83095. _super.prototype.dispose.call(this, camera);
  83096. };
  83097. return RefractionPostProcess;
  83098. }(BABYLON.PostProcess));
  83099. BABYLON.RefractionPostProcess = RefractionPostProcess;
  83100. })(BABYLON || (BABYLON = {}));
  83101. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  83102. var BABYLON;
  83103. (function (BABYLON) {
  83104. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  83105. __extends(BlackAndWhitePostProcess, _super);
  83106. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  83107. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  83108. _this.degree = 1;
  83109. _this.onApplyObservable.add(function (effect) {
  83110. effect.setFloat("degree", _this.degree);
  83111. });
  83112. return _this;
  83113. }
  83114. return BlackAndWhitePostProcess;
  83115. }(BABYLON.PostProcess));
  83116. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  83117. })(BABYLON || (BABYLON = {}));
  83118. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  83119. var BABYLON;
  83120. (function (BABYLON) {
  83121. /**
  83122. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  83123. * input texture to perform effects such as edge detection or sharpening
  83124. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83125. */
  83126. var ConvolutionPostProcess = /** @class */ (function (_super) {
  83127. __extends(ConvolutionPostProcess, _super);
  83128. /**
  83129. * Creates a new instance ConvolutionPostProcess
  83130. * @param name The name of the effect.
  83131. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  83132. * @param options The required width/height ratio to downsize to before computing the render pass.
  83133. * @param camera The camera to apply the render pass to.
  83134. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83135. * @param engine The engine which the post process will be applied. (default: current engine)
  83136. * @param reusable If the post process can be reused on the same frame. (default: false)
  83137. * @param textureType Type of textures used when performing the post process. (default: 0)
  83138. */
  83139. function ConvolutionPostProcess(name,
  83140. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  83141. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  83142. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83143. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83144. _this.kernel = kernel;
  83145. _this.onApply = function (effect) {
  83146. effect.setFloat2("screenSize", _this.width, _this.height);
  83147. effect.setArray("kernel", _this.kernel);
  83148. };
  83149. return _this;
  83150. }
  83151. // Statics
  83152. /**
  83153. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83154. */
  83155. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  83156. /**
  83157. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83158. */
  83159. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  83160. /**
  83161. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83162. */
  83163. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  83164. /**
  83165. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83166. */
  83167. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  83168. /**
  83169. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83170. */
  83171. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  83172. /**
  83173. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83174. */
  83175. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  83176. return ConvolutionPostProcess;
  83177. }(BABYLON.PostProcess));
  83178. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  83179. })(BABYLON || (BABYLON = {}));
  83180. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  83181. var BABYLON;
  83182. (function (BABYLON) {
  83183. var FilterPostProcess = /** @class */ (function (_super) {
  83184. __extends(FilterPostProcess, _super);
  83185. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  83186. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  83187. _this.kernelMatrix = kernelMatrix;
  83188. _this.onApply = function (effect) {
  83189. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  83190. };
  83191. return _this;
  83192. }
  83193. return FilterPostProcess;
  83194. }(BABYLON.PostProcess));
  83195. BABYLON.FilterPostProcess = FilterPostProcess;
  83196. })(BABYLON || (BABYLON = {}));
  83197. //# sourceMappingURL=babylon.filterPostProcess.js.map
  83198. var BABYLON;
  83199. (function (BABYLON) {
  83200. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  83201. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  83202. __extends(VolumetricLightScatteringPostProcess, _super);
  83203. /**
  83204. * @constructor
  83205. * @param {string} name - The post-process name
  83206. * @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)
  83207. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  83208. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  83209. * @param {number} samples - The post-process quality, default 100
  83210. * @param {number} samplingMode - The post-process filtering mode
  83211. * @param {BABYLON.Engine} engine - The babylon engine
  83212. * @param {boolean} reusable - If the post-process is reusable
  83213. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  83214. */
  83215. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  83216. if (samples === void 0) { samples = 100; }
  83217. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83218. 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;
  83219. _this._screenCoordinates = BABYLON.Vector2.Zero();
  83220. /**
  83221. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  83222. */
  83223. _this.customMeshPosition = BABYLON.Vector3.Zero();
  83224. /**
  83225. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  83226. */
  83227. _this.useCustomMeshPosition = false;
  83228. /**
  83229. * If the post-process should inverse the light scattering direction
  83230. */
  83231. _this.invert = true;
  83232. /**
  83233. * Array containing the excluded meshes not rendered in the internal pass
  83234. */
  83235. _this.excludedMeshes = new Array();
  83236. /**
  83237. * Controls the overall intensity of the post-process
  83238. */
  83239. _this.exposure = 0.3;
  83240. /**
  83241. * Dissipates each sample's contribution in range [0, 1]
  83242. */
  83243. _this.decay = 0.96815;
  83244. /**
  83245. * Controls the overall intensity of each sample
  83246. */
  83247. _this.weight = 0.58767;
  83248. /**
  83249. * Controls the density of each sample
  83250. */
  83251. _this.density = 0.926;
  83252. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  83253. engine = scene.getEngine();
  83254. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  83255. // Configure mesh
  83256. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  83257. // Configure
  83258. _this._createPass(scene, ratio.passRatio || ratio);
  83259. _this.onActivate = function (camera) {
  83260. if (!_this.isSupported) {
  83261. _this.dispose(camera);
  83262. }
  83263. _this.onActivate = null;
  83264. };
  83265. _this.onApplyObservable.add(function (effect) {
  83266. _this._updateMeshScreenCoordinates(scene);
  83267. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  83268. effect.setFloat("exposure", _this.exposure);
  83269. effect.setFloat("decay", _this.decay);
  83270. effect.setFloat("weight", _this.weight);
  83271. effect.setFloat("density", _this.density);
  83272. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  83273. });
  83274. return _this;
  83275. }
  83276. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  83277. get: function () {
  83278. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83279. return false;
  83280. },
  83281. set: function (useDiffuseColor) {
  83282. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83283. },
  83284. enumerable: true,
  83285. configurable: true
  83286. });
  83287. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  83288. return "VolumetricLightScatteringPostProcess";
  83289. };
  83290. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  83291. var mesh = subMesh.getMesh();
  83292. // Render this.mesh as default
  83293. if (mesh === this.mesh && mesh.material) {
  83294. return mesh.material.isReady(mesh);
  83295. }
  83296. var defines = [];
  83297. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83298. var material = subMesh.getMaterial();
  83299. // Alpha test
  83300. if (material) {
  83301. if (material.needAlphaTesting()) {
  83302. defines.push("#define ALPHATEST");
  83303. }
  83304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83305. attribs.push(BABYLON.VertexBuffer.UVKind);
  83306. defines.push("#define UV1");
  83307. }
  83308. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83309. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83310. defines.push("#define UV2");
  83311. }
  83312. }
  83313. // Bones
  83314. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83315. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83316. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83317. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83318. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83319. }
  83320. else {
  83321. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83322. }
  83323. // Instances
  83324. if (useInstances) {
  83325. defines.push("#define INSTANCES");
  83326. attribs.push("world0");
  83327. attribs.push("world1");
  83328. attribs.push("world2");
  83329. attribs.push("world3");
  83330. }
  83331. // Get correct effect
  83332. var join = defines.join("\n");
  83333. if (this._cachedDefines !== join) {
  83334. this._cachedDefines = join;
  83335. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  83336. }
  83337. return this._volumetricLightScatteringPass.isReady();
  83338. };
  83339. /**
  83340. * Sets the new light position for light scattering effect
  83341. * @param {BABYLON.Vector3} The new custom light position
  83342. */
  83343. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  83344. this.customMeshPosition = position;
  83345. };
  83346. /**
  83347. * Returns the light position for light scattering effect
  83348. * @return {BABYLON.Vector3} The custom light position
  83349. */
  83350. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  83351. return this.customMeshPosition;
  83352. };
  83353. /**
  83354. * Disposes the internal assets and detaches the post-process from the camera
  83355. */
  83356. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  83357. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  83358. if (rttIndex !== -1) {
  83359. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  83360. }
  83361. this._volumetricLightScatteringRTT.dispose();
  83362. _super.prototype.dispose.call(this, camera);
  83363. };
  83364. /**
  83365. * Returns the render target texture used by the post-process
  83366. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  83367. */
  83368. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  83369. return this._volumetricLightScatteringRTT;
  83370. };
  83371. // Private methods
  83372. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  83373. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  83374. return true;
  83375. }
  83376. return false;
  83377. };
  83378. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  83379. var _this = this;
  83380. var engine = scene.getEngine();
  83381. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83382. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83383. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83384. this._volumetricLightScatteringRTT.renderList = null;
  83385. this._volumetricLightScatteringRTT.renderParticles = false;
  83386. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  83387. var camera = this.getCamera();
  83388. if (camera) {
  83389. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83390. }
  83391. else {
  83392. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83393. }
  83394. // Custom render function for submeshes
  83395. var renderSubMesh = function (subMesh) {
  83396. var mesh = subMesh.getRenderingMesh();
  83397. if (_this._meshExcluded(mesh)) {
  83398. return;
  83399. }
  83400. var material = subMesh.getMaterial();
  83401. if (!material) {
  83402. return;
  83403. }
  83404. var scene = mesh.getScene();
  83405. var engine = scene.getEngine();
  83406. // Culling
  83407. engine.setState(material.backFaceCulling);
  83408. // Managing instances
  83409. var batch = mesh._getInstancesRenderList(subMesh._id);
  83410. if (batch.mustReturn) {
  83411. return;
  83412. }
  83413. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83414. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  83415. var effect = _this._volumetricLightScatteringPass;
  83416. if (mesh === _this.mesh) {
  83417. if (subMesh.effect) {
  83418. effect = subMesh.effect;
  83419. }
  83420. else {
  83421. effect = material.getEffect();
  83422. }
  83423. }
  83424. engine.enableEffect(effect);
  83425. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  83426. if (mesh === _this.mesh) {
  83427. material.bind(mesh.getWorldMatrix(), mesh);
  83428. }
  83429. else {
  83430. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  83431. // Alpha test
  83432. if (material && material.needAlphaTesting()) {
  83433. var alphaTexture = material.getAlphaTestTexture();
  83434. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  83435. if (alphaTexture) {
  83436. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83437. }
  83438. }
  83439. // Bones
  83440. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83441. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83442. }
  83443. }
  83444. // Draw
  83445. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  83446. }
  83447. };
  83448. // Render target texture callbacks
  83449. var savedSceneClearColor;
  83450. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  83451. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  83452. savedSceneClearColor = scene.clearColor;
  83453. scene.clearColor = sceneClearColor;
  83454. });
  83455. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  83456. scene.clearColor = savedSceneClearColor;
  83457. });
  83458. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83459. var engine = scene.getEngine();
  83460. var index;
  83461. if (depthOnlySubMeshes.length) {
  83462. engine.setColorWrite(false);
  83463. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83464. renderSubMesh(depthOnlySubMeshes.data[index]);
  83465. }
  83466. engine.setColorWrite(true);
  83467. }
  83468. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83469. renderSubMesh(opaqueSubMeshes.data[index]);
  83470. }
  83471. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83472. renderSubMesh(alphaTestSubMeshes.data[index]);
  83473. }
  83474. if (transparentSubMeshes.length) {
  83475. // Sort sub meshes
  83476. for (index = 0; index < transparentSubMeshes.length; index++) {
  83477. var submesh = transparentSubMeshes.data[index];
  83478. var boundingInfo = submesh.getBoundingInfo();
  83479. if (boundingInfo && scene.activeCamera) {
  83480. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  83481. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  83482. }
  83483. }
  83484. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  83485. sortedArray.sort(function (a, b) {
  83486. // Alpha index first
  83487. if (a._alphaIndex > b._alphaIndex) {
  83488. return 1;
  83489. }
  83490. if (a._alphaIndex < b._alphaIndex) {
  83491. return -1;
  83492. }
  83493. // Then distance to camera
  83494. if (a._distanceToCamera < b._distanceToCamera) {
  83495. return 1;
  83496. }
  83497. if (a._distanceToCamera > b._distanceToCamera) {
  83498. return -1;
  83499. }
  83500. return 0;
  83501. });
  83502. // Render sub meshes
  83503. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  83504. for (index = 0; index < sortedArray.length; index++) {
  83505. renderSubMesh(sortedArray[index]);
  83506. }
  83507. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83508. }
  83509. };
  83510. };
  83511. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  83512. var transform = scene.getTransformMatrix();
  83513. var meshPosition;
  83514. if (this.useCustomMeshPosition) {
  83515. meshPosition = this.customMeshPosition;
  83516. }
  83517. else if (this.attachedNode) {
  83518. meshPosition = this.attachedNode.position;
  83519. }
  83520. else {
  83521. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  83522. }
  83523. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  83524. this._screenCoordinates.x = pos.x / this._viewPort.width;
  83525. this._screenCoordinates.y = pos.y / this._viewPort.height;
  83526. if (this.invert)
  83527. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  83528. };
  83529. // Static methods
  83530. /**
  83531. * Creates a default mesh for the Volumeric Light Scattering post-process
  83532. * @param {string} The mesh name
  83533. * @param {BABYLON.Scene} The scene where to create the mesh
  83534. * @return {BABYLON.Mesh} the default mesh
  83535. */
  83536. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  83537. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  83538. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  83539. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  83540. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  83541. mesh.material = material;
  83542. return mesh;
  83543. };
  83544. __decorate([
  83545. BABYLON.serializeAsVector3()
  83546. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  83547. __decorate([
  83548. BABYLON.serialize()
  83549. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  83550. __decorate([
  83551. BABYLON.serialize()
  83552. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  83553. __decorate([
  83554. BABYLON.serializeAsMeshReference()
  83555. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  83556. __decorate([
  83557. BABYLON.serialize()
  83558. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  83559. __decorate([
  83560. BABYLON.serialize()
  83561. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  83562. __decorate([
  83563. BABYLON.serialize()
  83564. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  83565. __decorate([
  83566. BABYLON.serialize()
  83567. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  83568. __decorate([
  83569. BABYLON.serialize()
  83570. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  83571. return VolumetricLightScatteringPostProcess;
  83572. }(BABYLON.PostProcess));
  83573. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  83574. })(BABYLON || (BABYLON = {}));
  83575. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  83576. //
  83577. // This post-process allows the modification of rendered colors by using
  83578. // a 'look-up table' (LUT). This effect is also called Color Grading.
  83579. //
  83580. // The object needs to be provided an url to a texture containing the color
  83581. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  83582. // Use an image editing software to tweak the LUT to match your needs.
  83583. //
  83584. // For an example of a color LUT, see here:
  83585. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  83586. // For explanations on color grading, see here:
  83587. // http://udn.epicgames.com/Three/ColorGrading.html
  83588. //
  83589. var BABYLON;
  83590. (function (BABYLON) {
  83591. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  83592. __extends(ColorCorrectionPostProcess, _super);
  83593. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  83594. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  83595. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83596. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  83597. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83598. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83599. _this.onApply = function (effect) {
  83600. effect.setTexture("colorTable", _this._colorTableTexture);
  83601. };
  83602. return _this;
  83603. }
  83604. return ColorCorrectionPostProcess;
  83605. }(BABYLON.PostProcess));
  83606. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  83607. })(BABYLON || (BABYLON = {}));
  83608. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  83609. var BABYLON;
  83610. (function (BABYLON) {
  83611. /** Defines operator used for tonemapping */
  83612. var TonemappingOperator;
  83613. (function (TonemappingOperator) {
  83614. /** Hable */
  83615. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  83616. /** Reinhard */
  83617. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  83618. /** HejiDawson */
  83619. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  83620. /** Photographic */
  83621. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  83622. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  83623. ;
  83624. /**
  83625. * Defines a post process to apply tone mapping
  83626. */
  83627. var TonemapPostProcess = /** @class */ (function (_super) {
  83628. __extends(TonemapPostProcess, _super);
  83629. /**
  83630. * Creates a new TonemapPostProcess
  83631. * @param name defines the name of the postprocess
  83632. * @param _operator defines the operator to use
  83633. * @param exposureAdjustment defines the required exposure adjustement
  83634. * @param camera defines the camera to use (can be null)
  83635. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  83636. * @param engine defines the hosting engine (can be ignore if camera is set)
  83637. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  83638. */
  83639. function TonemapPostProcess(name, _operator,
  83640. /** Defines the required exposure adjustement */
  83641. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  83642. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83643. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83644. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  83645. _this._operator = _operator;
  83646. _this.exposureAdjustment = exposureAdjustment;
  83647. var defines = "#define ";
  83648. if (_this._operator === TonemappingOperator.Hable)
  83649. defines += "HABLE_TONEMAPPING";
  83650. else if (_this._operator === TonemappingOperator.Reinhard)
  83651. defines += "REINHARD_TONEMAPPING";
  83652. else if (_this._operator === TonemappingOperator.HejiDawson)
  83653. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  83654. else if (_this._operator === TonemappingOperator.Photographic)
  83655. defines += "PHOTOGRAPHIC_TONEMAPPING";
  83656. //sadly a second call to create the effect.
  83657. _this.updateEffect(defines);
  83658. _this.onApply = function (effect) {
  83659. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  83660. };
  83661. return _this;
  83662. }
  83663. return TonemapPostProcess;
  83664. }(BABYLON.PostProcess));
  83665. BABYLON.TonemapPostProcess = TonemapPostProcess;
  83666. })(BABYLON || (BABYLON = {}));
  83667. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  83668. var BABYLON;
  83669. (function (BABYLON) {
  83670. var DisplayPassPostProcess = /** @class */ (function (_super) {
  83671. __extends(DisplayPassPostProcess, _super);
  83672. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  83673. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  83674. }
  83675. return DisplayPassPostProcess;
  83676. }(BABYLON.PostProcess));
  83677. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  83678. })(BABYLON || (BABYLON = {}));
  83679. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  83680. var BABYLON;
  83681. (function (BABYLON) {
  83682. var HighlightsPostProcess = /** @class */ (function (_super) {
  83683. __extends(HighlightsPostProcess, _super);
  83684. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83685. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83686. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83687. }
  83688. return HighlightsPostProcess;
  83689. }(BABYLON.PostProcess));
  83690. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  83691. })(BABYLON || (BABYLON = {}));
  83692. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  83693. var BABYLON;
  83694. (function (BABYLON) {
  83695. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  83696. __extends(ImageProcessingPostProcess, _super);
  83697. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  83698. if (camera === void 0) { camera = null; }
  83699. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83700. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  83701. _this._fromLinearSpace = true;
  83702. /**
  83703. * Defines cache preventing GC.
  83704. */
  83705. _this._defines = {
  83706. IMAGEPROCESSING: false,
  83707. VIGNETTE: false,
  83708. VIGNETTEBLENDMODEMULTIPLY: false,
  83709. VIGNETTEBLENDMODEOPAQUE: false,
  83710. TONEMAPPING: false,
  83711. TONEMAPPING_ACES: false,
  83712. CONTRAST: false,
  83713. COLORCURVES: false,
  83714. COLORGRADING: false,
  83715. COLORGRADING3D: false,
  83716. FROMLINEARSPACE: false,
  83717. SAMPLER3DGREENDEPTH: false,
  83718. SAMPLER3DBGRMAP: false,
  83719. IMAGEPROCESSINGPOSTPROCESS: false,
  83720. EXPOSURE: false,
  83721. };
  83722. // Setup the configuration as forced by the constructor. This would then not force the
  83723. // scene materials output in linear space and let untouched the default forward pass.
  83724. if (imageProcessingConfiguration) {
  83725. imageProcessingConfiguration.applyByPostProcess = true;
  83726. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  83727. // This will cause the shader to be compiled
  83728. _this.fromLinearSpace = false;
  83729. }
  83730. // Setup the default processing configuration to the scene.
  83731. else {
  83732. _this._attachImageProcessingConfiguration(null, true);
  83733. _this.imageProcessingConfiguration.applyByPostProcess = true;
  83734. }
  83735. _this.onApply = function (effect) {
  83736. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  83737. };
  83738. return _this;
  83739. }
  83740. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  83741. /**
  83742. * Gets the image processing configuration used either in this material.
  83743. */
  83744. get: function () {
  83745. return this._imageProcessingConfiguration;
  83746. },
  83747. /**
  83748. * Sets the Default image processing configuration used either in the this material.
  83749. *
  83750. * If sets to null, the scene one is in use.
  83751. */
  83752. set: function (value) {
  83753. this._attachImageProcessingConfiguration(value);
  83754. },
  83755. enumerable: true,
  83756. configurable: true
  83757. });
  83758. /**
  83759. * Attaches a new image processing configuration to the PBR Material.
  83760. * @param configuration
  83761. */
  83762. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  83763. var _this = this;
  83764. if (doNotBuild === void 0) { doNotBuild = false; }
  83765. if (configuration === this._imageProcessingConfiguration) {
  83766. return;
  83767. }
  83768. // Detaches observer.
  83769. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83770. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83771. }
  83772. // Pick the scene configuration if needed.
  83773. if (!configuration) {
  83774. var scene = null;
  83775. var engine = this.getEngine();
  83776. var camera = this.getCamera();
  83777. if (camera) {
  83778. scene = camera.getScene();
  83779. }
  83780. else if (engine && engine.scenes) {
  83781. var scenes = engine.scenes;
  83782. scene = scenes[scenes.length - 1];
  83783. }
  83784. else {
  83785. scene = BABYLON.Engine.LastCreatedScene;
  83786. }
  83787. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  83788. }
  83789. else {
  83790. this._imageProcessingConfiguration = configuration;
  83791. }
  83792. // Attaches observer.
  83793. if (this._imageProcessingConfiguration) {
  83794. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83795. _this._updateParameters();
  83796. });
  83797. }
  83798. // Ensure the effect will be rebuilt.
  83799. if (!doNotBuild) {
  83800. this._updateParameters();
  83801. }
  83802. };
  83803. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  83804. /**
  83805. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83806. */
  83807. get: function () {
  83808. return this.imageProcessingConfiguration.colorCurves;
  83809. },
  83810. /**
  83811. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83812. */
  83813. set: function (value) {
  83814. this.imageProcessingConfiguration.colorCurves = value;
  83815. },
  83816. enumerable: true,
  83817. configurable: true
  83818. });
  83819. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  83820. /**
  83821. * Gets wether the color curves effect is enabled.
  83822. */
  83823. get: function () {
  83824. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83825. },
  83826. /**
  83827. * Sets wether the color curves effect is enabled.
  83828. */
  83829. set: function (value) {
  83830. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83831. },
  83832. enumerable: true,
  83833. configurable: true
  83834. });
  83835. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  83836. /**
  83837. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83838. */
  83839. get: function () {
  83840. return this.imageProcessingConfiguration.colorGradingTexture;
  83841. },
  83842. /**
  83843. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83844. */
  83845. set: function (value) {
  83846. this.imageProcessingConfiguration.colorGradingTexture = value;
  83847. },
  83848. enumerable: true,
  83849. configurable: true
  83850. });
  83851. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  83852. /**
  83853. * Gets wether the color grading effect is enabled.
  83854. */
  83855. get: function () {
  83856. return this.imageProcessingConfiguration.colorGradingEnabled;
  83857. },
  83858. /**
  83859. * Gets wether the color grading effect is enabled.
  83860. */
  83861. set: function (value) {
  83862. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83863. },
  83864. enumerable: true,
  83865. configurable: true
  83866. });
  83867. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  83868. /**
  83869. * Gets exposure used in the effect.
  83870. */
  83871. get: function () {
  83872. return this.imageProcessingConfiguration.exposure;
  83873. },
  83874. /**
  83875. * Sets exposure used in the effect.
  83876. */
  83877. set: function (value) {
  83878. this.imageProcessingConfiguration.exposure = value;
  83879. },
  83880. enumerable: true,
  83881. configurable: true
  83882. });
  83883. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  83884. /**
  83885. * Gets wether tonemapping is enabled or not.
  83886. */
  83887. get: function () {
  83888. return this._imageProcessingConfiguration.toneMappingEnabled;
  83889. },
  83890. /**
  83891. * Sets wether tonemapping is enabled or not
  83892. */
  83893. set: function (value) {
  83894. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83895. },
  83896. enumerable: true,
  83897. configurable: true
  83898. });
  83899. ;
  83900. ;
  83901. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  83902. /**
  83903. * Gets contrast used in the effect.
  83904. */
  83905. get: function () {
  83906. return this.imageProcessingConfiguration.contrast;
  83907. },
  83908. /**
  83909. * Sets contrast used in the effect.
  83910. */
  83911. set: function (value) {
  83912. this.imageProcessingConfiguration.contrast = value;
  83913. },
  83914. enumerable: true,
  83915. configurable: true
  83916. });
  83917. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  83918. /**
  83919. * Gets Vignette stretch size.
  83920. */
  83921. get: function () {
  83922. return this.imageProcessingConfiguration.vignetteStretch;
  83923. },
  83924. /**
  83925. * Sets Vignette stretch size.
  83926. */
  83927. set: function (value) {
  83928. this.imageProcessingConfiguration.vignetteStretch = value;
  83929. },
  83930. enumerable: true,
  83931. configurable: true
  83932. });
  83933. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  83934. /**
  83935. * Gets Vignette centre X Offset.
  83936. */
  83937. get: function () {
  83938. return this.imageProcessingConfiguration.vignetteCentreX;
  83939. },
  83940. /**
  83941. * Sets Vignette centre X Offset.
  83942. */
  83943. set: function (value) {
  83944. this.imageProcessingConfiguration.vignetteCentreX = value;
  83945. },
  83946. enumerable: true,
  83947. configurable: true
  83948. });
  83949. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  83950. /**
  83951. * Gets Vignette centre Y Offset.
  83952. */
  83953. get: function () {
  83954. return this.imageProcessingConfiguration.vignetteCentreY;
  83955. },
  83956. /**
  83957. * Sets Vignette centre Y Offset.
  83958. */
  83959. set: function (value) {
  83960. this.imageProcessingConfiguration.vignetteCentreY = value;
  83961. },
  83962. enumerable: true,
  83963. configurable: true
  83964. });
  83965. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  83966. /**
  83967. * Gets Vignette weight or intensity of the vignette effect.
  83968. */
  83969. get: function () {
  83970. return this.imageProcessingConfiguration.vignetteWeight;
  83971. },
  83972. /**
  83973. * Sets Vignette weight or intensity of the vignette effect.
  83974. */
  83975. set: function (value) {
  83976. this.imageProcessingConfiguration.vignetteWeight = value;
  83977. },
  83978. enumerable: true,
  83979. configurable: true
  83980. });
  83981. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  83982. /**
  83983. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83984. * if vignetteEnabled is set to true.
  83985. */
  83986. get: function () {
  83987. return this.imageProcessingConfiguration.vignetteColor;
  83988. },
  83989. /**
  83990. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83991. * if vignetteEnabled is set to true.
  83992. */
  83993. set: function (value) {
  83994. this.imageProcessingConfiguration.vignetteColor = value;
  83995. },
  83996. enumerable: true,
  83997. configurable: true
  83998. });
  83999. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  84000. /**
  84001. * Gets Camera field of view used by the Vignette effect.
  84002. */
  84003. get: function () {
  84004. return this.imageProcessingConfiguration.vignetteCameraFov;
  84005. },
  84006. /**
  84007. * Sets Camera field of view used by the Vignette effect.
  84008. */
  84009. set: function (value) {
  84010. this.imageProcessingConfiguration.vignetteCameraFov = value;
  84011. },
  84012. enumerable: true,
  84013. configurable: true
  84014. });
  84015. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  84016. /**
  84017. * Gets the vignette blend mode allowing different kind of effect.
  84018. */
  84019. get: function () {
  84020. return this.imageProcessingConfiguration.vignetteBlendMode;
  84021. },
  84022. /**
  84023. * Sets the vignette blend mode allowing different kind of effect.
  84024. */
  84025. set: function (value) {
  84026. this.imageProcessingConfiguration.vignetteBlendMode = value;
  84027. },
  84028. enumerable: true,
  84029. configurable: true
  84030. });
  84031. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  84032. /**
  84033. * Gets wether the vignette effect is enabled.
  84034. */
  84035. get: function () {
  84036. return this.imageProcessingConfiguration.vignetteEnabled;
  84037. },
  84038. /**
  84039. * Sets wether the vignette effect is enabled.
  84040. */
  84041. set: function (value) {
  84042. this.imageProcessingConfiguration.vignetteEnabled = value;
  84043. },
  84044. enumerable: true,
  84045. configurable: true
  84046. });
  84047. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  84048. /**
  84049. * Gets wether the input of the processing is in Gamma or Linear Space.
  84050. */
  84051. get: function () {
  84052. return this._fromLinearSpace;
  84053. },
  84054. /**
  84055. * Sets wether the input of the processing is in Gamma or Linear Space.
  84056. */
  84057. set: function (value) {
  84058. if (this._fromLinearSpace === value) {
  84059. return;
  84060. }
  84061. this._fromLinearSpace = value;
  84062. this._updateParameters();
  84063. },
  84064. enumerable: true,
  84065. configurable: true
  84066. });
  84067. ImageProcessingPostProcess.prototype.getClassName = function () {
  84068. return "ImageProcessingPostProcess";
  84069. };
  84070. ImageProcessingPostProcess.prototype._updateParameters = function () {
  84071. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  84072. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  84073. var defines = "";
  84074. for (var define in this._defines) {
  84075. if (this._defines[define]) {
  84076. defines += "#define " + define + ";\r\n";
  84077. }
  84078. }
  84079. var samplers = ["textureSampler"];
  84080. var uniforms = ["scale"];
  84081. if (BABYLON.ImageProcessingConfiguration) {
  84082. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  84083. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  84084. }
  84085. this.updateEffect(defines, uniforms, samplers);
  84086. };
  84087. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  84088. _super.prototype.dispose.call(this, camera);
  84089. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84090. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84091. }
  84092. if (this._imageProcessingConfiguration) {
  84093. this.imageProcessingConfiguration.applyByPostProcess = false;
  84094. }
  84095. };
  84096. __decorate([
  84097. BABYLON.serialize()
  84098. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  84099. return ImageProcessingPostProcess;
  84100. }(BABYLON.PostProcess));
  84101. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  84102. })(BABYLON || (BABYLON = {}));
  84103. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  84104. var BABYLON;
  84105. (function (BABYLON) {
  84106. /**
  84107. * Class used to store bone information
  84108. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84109. */
  84110. var Bone = /** @class */ (function (_super) {
  84111. __extends(Bone, _super);
  84112. /**
  84113. * Create a new bone
  84114. * @param name defines the bone name
  84115. * @param skeleton defines the parent skeleton
  84116. * @param parentBone defines the parent (can be null if the bone is the root)
  84117. * @param localMatrix defines the local matrix
  84118. * @param restPose defines the rest pose matrix
  84119. * @param baseMatrix defines the base matrix
  84120. * @param index defines index of the bone in the hiearchy
  84121. */
  84122. function Bone(
  84123. /**
  84124. * defines the bone name
  84125. */
  84126. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  84127. if (parentBone === void 0) { parentBone = null; }
  84128. if (localMatrix === void 0) { localMatrix = null; }
  84129. if (restPose === void 0) { restPose = null; }
  84130. if (baseMatrix === void 0) { baseMatrix = null; }
  84131. if (index === void 0) { index = null; }
  84132. var _this = _super.call(this, name, skeleton.getScene()) || this;
  84133. _this.name = name;
  84134. /**
  84135. * Gets the list of child bones
  84136. */
  84137. _this.children = new Array();
  84138. /** Gets the animations associated with this bone */
  84139. _this.animations = new Array();
  84140. /**
  84141. * @hidden Internal only
  84142. * Set this value to map this bone to a different index in the transform matrices
  84143. * Set this value to -1 to exclude the bone from the transform matrices
  84144. */
  84145. _this._index = null;
  84146. _this._absoluteTransform = new BABYLON.Matrix();
  84147. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  84148. _this._scalingDeterminant = 1;
  84149. _this._worldTransform = new BABYLON.Matrix();
  84150. _this._needToDecompose = true;
  84151. _this._needToCompose = false;
  84152. _this._skeleton = skeleton;
  84153. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  84154. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  84155. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  84156. _this._index = index;
  84157. skeleton.bones.push(_this);
  84158. _this.setParent(parentBone, false);
  84159. if (baseMatrix || localMatrix) {
  84160. _this._updateDifferenceMatrix();
  84161. }
  84162. return _this;
  84163. }
  84164. Object.defineProperty(Bone.prototype, "_matrix", {
  84165. /** @hidden */
  84166. get: function () {
  84167. this._compose();
  84168. return this._localMatrix;
  84169. },
  84170. /** @hidden */
  84171. set: function (value) {
  84172. this._localMatrix.copyFrom(value);
  84173. this._needToDecompose = true;
  84174. },
  84175. enumerable: true,
  84176. configurable: true
  84177. });
  84178. // Members
  84179. /**
  84180. * Gets the parent skeleton
  84181. * @returns a skeleton
  84182. */
  84183. Bone.prototype.getSkeleton = function () {
  84184. return this._skeleton;
  84185. };
  84186. /**
  84187. * Gets parent bone
  84188. * @returns a bone or null if the bone is the root of the bone hierarchy
  84189. */
  84190. Bone.prototype.getParent = function () {
  84191. return this._parent;
  84192. };
  84193. /**
  84194. * Sets the parent bone
  84195. * @param parent defines the parent (can be null if the bone is the root)
  84196. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84197. */
  84198. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  84199. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84200. if (this._parent === parent) {
  84201. return;
  84202. }
  84203. if (this._parent) {
  84204. var index = this._parent.children.indexOf(this);
  84205. if (index !== -1) {
  84206. this._parent.children.splice(index, 1);
  84207. }
  84208. }
  84209. this._parent = parent;
  84210. if (this._parent) {
  84211. this._parent.children.push(this);
  84212. }
  84213. if (updateDifferenceMatrix) {
  84214. this._updateDifferenceMatrix();
  84215. }
  84216. this.markAsDirty();
  84217. };
  84218. /**
  84219. * Gets the local matrix
  84220. * @returns a matrix
  84221. */
  84222. Bone.prototype.getLocalMatrix = function () {
  84223. this._compose();
  84224. return this._localMatrix;
  84225. };
  84226. /**
  84227. * Gets the base matrix (initial matrix which remains unchanged)
  84228. * @returns a matrix
  84229. */
  84230. Bone.prototype.getBaseMatrix = function () {
  84231. return this._baseMatrix;
  84232. };
  84233. /**
  84234. * Gets the rest pose matrix
  84235. * @returns a matrix
  84236. */
  84237. Bone.prototype.getRestPose = function () {
  84238. return this._restPose;
  84239. };
  84240. /**
  84241. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  84242. */
  84243. Bone.prototype.getWorldMatrix = function () {
  84244. return this._worldTransform;
  84245. };
  84246. /**
  84247. * Sets the local matrix to rest pose matrix
  84248. */
  84249. Bone.prototype.returnToRest = function () {
  84250. this.updateMatrix(this._restPose.clone());
  84251. };
  84252. /**
  84253. * Gets the inverse of the absolute transform matrix.
  84254. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  84255. * @returns a matrix
  84256. */
  84257. Bone.prototype.getInvertedAbsoluteTransform = function () {
  84258. return this._invertedAbsoluteTransform;
  84259. };
  84260. /**
  84261. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  84262. * @returns a matrix
  84263. */
  84264. Bone.prototype.getAbsoluteTransform = function () {
  84265. return this._absoluteTransform;
  84266. };
  84267. Object.defineProperty(Bone.prototype, "position", {
  84268. // Properties (matches AbstractMesh properties)
  84269. /** Gets or sets current position (in local space) */
  84270. get: function () {
  84271. this._decompose();
  84272. return this._localPosition;
  84273. },
  84274. set: function (newPosition) {
  84275. this._decompose();
  84276. this._localPosition.copyFrom(newPosition);
  84277. this._markAsDirtyAndCompose();
  84278. },
  84279. enumerable: true,
  84280. configurable: true
  84281. });
  84282. Object.defineProperty(Bone.prototype, "rotation", {
  84283. /** Gets or sets current rotation (in local space) */
  84284. get: function () {
  84285. return this.getRotation();
  84286. },
  84287. set: function (newRotation) {
  84288. this.setRotation(newRotation);
  84289. },
  84290. enumerable: true,
  84291. configurable: true
  84292. });
  84293. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  84294. /** Gets or sets current rotation quaternion (in local space) */
  84295. get: function () {
  84296. this._decompose();
  84297. return this._localRotation;
  84298. },
  84299. set: function (newRotation) {
  84300. this.setRotationQuaternion(newRotation);
  84301. },
  84302. enumerable: true,
  84303. configurable: true
  84304. });
  84305. Object.defineProperty(Bone.prototype, "scaling", {
  84306. /** Gets or sets current scaling (in local space) */
  84307. get: function () {
  84308. return this.getScale();
  84309. },
  84310. set: function (newScaling) {
  84311. this.setScale(newScaling);
  84312. },
  84313. enumerable: true,
  84314. configurable: true
  84315. });
  84316. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  84317. /**
  84318. * Gets the animation properties override
  84319. */
  84320. get: function () {
  84321. return this._skeleton.animationPropertiesOverride;
  84322. },
  84323. enumerable: true,
  84324. configurable: true
  84325. });
  84326. // Methods
  84327. Bone.prototype._decompose = function () {
  84328. if (!this._needToDecompose) {
  84329. return;
  84330. }
  84331. this._needToDecompose = false;
  84332. if (!this._localScaling) {
  84333. this._localScaling = BABYLON.Vector3.Zero();
  84334. this._localRotation = BABYLON.Quaternion.Zero();
  84335. this._localPosition = BABYLON.Vector3.Zero();
  84336. }
  84337. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  84338. };
  84339. Bone.prototype._compose = function () {
  84340. if (!this._needToCompose) {
  84341. return;
  84342. }
  84343. this._needToCompose = false;
  84344. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  84345. };
  84346. /**
  84347. * Update the base and local matrices
  84348. * @param matrix defines the new base or local matrix
  84349. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84350. * @param updateLocalMatrix defines if the local matrix should be updated
  84351. */
  84352. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  84353. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84354. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  84355. this._baseMatrix.copyFrom(matrix);
  84356. if (updateDifferenceMatrix) {
  84357. this._updateDifferenceMatrix();
  84358. }
  84359. if (updateLocalMatrix) {
  84360. this._localMatrix.copyFrom(matrix);
  84361. this._markAsDirtyAndDecompose();
  84362. }
  84363. else {
  84364. this.markAsDirty();
  84365. }
  84366. };
  84367. /** @hidden */
  84368. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  84369. if (updateChildren === void 0) { updateChildren = true; }
  84370. if (!rootMatrix) {
  84371. rootMatrix = this._baseMatrix;
  84372. }
  84373. if (this._parent) {
  84374. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84375. }
  84376. else {
  84377. this._absoluteTransform.copyFrom(rootMatrix);
  84378. }
  84379. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  84380. if (updateChildren) {
  84381. for (var index = 0; index < this.children.length; index++) {
  84382. this.children[index]._updateDifferenceMatrix();
  84383. }
  84384. }
  84385. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  84386. };
  84387. /**
  84388. * Flag the bone as dirty (Forcing it to update everything)
  84389. */
  84390. Bone.prototype.markAsDirty = function () {
  84391. this._currentRenderId++;
  84392. this._childRenderId++;
  84393. this._skeleton._markAsDirty();
  84394. };
  84395. Bone.prototype._markAsDirtyAndCompose = function () {
  84396. this.markAsDirty();
  84397. this._needToCompose = true;
  84398. };
  84399. Bone.prototype._markAsDirtyAndDecompose = function () {
  84400. this.markAsDirty();
  84401. this._needToDecompose = true;
  84402. };
  84403. /**
  84404. * Copy an animation range from another bone
  84405. * @param source defines the source bone
  84406. * @param rangeName defines the range name to copy
  84407. * @param frameOffset defines the frame offset
  84408. * @param rescaleAsRequired defines if rescaling must be applied if required
  84409. * @param skelDimensionsRatio defines the scaling ratio
  84410. * @returns true if operation was successful
  84411. */
  84412. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  84413. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84414. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  84415. // all animation may be coming from a library skeleton, so may need to create animation
  84416. if (this.animations.length === 0) {
  84417. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  84418. this.animations[0].setKeys([]);
  84419. }
  84420. // get animation info / verify there is such a range from the source bone
  84421. var sourceRange = source.animations[0].getRange(rangeName);
  84422. if (!sourceRange) {
  84423. return false;
  84424. }
  84425. var from = sourceRange.from;
  84426. var to = sourceRange.to;
  84427. var sourceKeys = source.animations[0].getKeys();
  84428. // rescaling prep
  84429. var sourceBoneLength = source.length;
  84430. var sourceParent = source.getParent();
  84431. var parent = this.getParent();
  84432. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  84433. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  84434. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  84435. var destKeys = this.animations[0].getKeys();
  84436. // loop vars declaration
  84437. var orig;
  84438. var origTranslation;
  84439. var mat;
  84440. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  84441. orig = sourceKeys[key];
  84442. if (orig.frame >= from && orig.frame <= to) {
  84443. if (rescaleAsRequired) {
  84444. mat = orig.value.clone();
  84445. // scale based on parent ratio, when bone has parent
  84446. if (parentScalingReqd) {
  84447. origTranslation = mat.getTranslation();
  84448. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  84449. // scale based on skeleton dimension ratio when root bone, and value is passed
  84450. }
  84451. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  84452. origTranslation = mat.getTranslation();
  84453. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  84454. // use original when root bone, and no data for skelDimensionsRatio
  84455. }
  84456. else {
  84457. mat = orig.value;
  84458. }
  84459. }
  84460. else {
  84461. mat = orig.value;
  84462. }
  84463. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  84464. }
  84465. }
  84466. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  84467. return true;
  84468. };
  84469. /**
  84470. * Translate the bone in local or world space
  84471. * @param vec The amount to translate the bone
  84472. * @param space The space that the translation is in
  84473. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84474. */
  84475. Bone.prototype.translate = function (vec, space, mesh) {
  84476. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84477. var lm = this.getLocalMatrix();
  84478. if (space == BABYLON.Space.LOCAL) {
  84479. lm.m[12] += vec.x;
  84480. lm.m[13] += vec.y;
  84481. lm.m[14] += vec.z;
  84482. }
  84483. else {
  84484. var wm = null;
  84485. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84486. if (mesh) {
  84487. wm = mesh.getWorldMatrix();
  84488. }
  84489. this._skeleton.computeAbsoluteTransforms();
  84490. var tmat = Bone._tmpMats[0];
  84491. var tvec = Bone._tmpVecs[0];
  84492. if (this._parent) {
  84493. if (mesh && wm) {
  84494. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84495. tmat.multiplyToRef(wm, tmat);
  84496. }
  84497. else {
  84498. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84499. }
  84500. }
  84501. tmat.m[12] = 0;
  84502. tmat.m[13] = 0;
  84503. tmat.m[14] = 0;
  84504. tmat.invert();
  84505. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  84506. lm.m[12] += tvec.x;
  84507. lm.m[13] += tvec.y;
  84508. lm.m[14] += tvec.z;
  84509. }
  84510. this._markAsDirtyAndDecompose();
  84511. };
  84512. /**
  84513. * Set the postion of the bone in local or world space
  84514. * @param position The position to set the bone
  84515. * @param space The space that the position is in
  84516. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84517. */
  84518. Bone.prototype.setPosition = function (position, space, mesh) {
  84519. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84520. var lm = this.getLocalMatrix();
  84521. if (space == BABYLON.Space.LOCAL) {
  84522. lm.m[12] = position.x;
  84523. lm.m[13] = position.y;
  84524. lm.m[14] = position.z;
  84525. }
  84526. else {
  84527. var wm = null;
  84528. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84529. if (mesh) {
  84530. wm = mesh.getWorldMatrix();
  84531. }
  84532. this._skeleton.computeAbsoluteTransforms();
  84533. var tmat = Bone._tmpMats[0];
  84534. var vec = Bone._tmpVecs[0];
  84535. if (this._parent) {
  84536. if (mesh && wm) {
  84537. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84538. tmat.multiplyToRef(wm, tmat);
  84539. }
  84540. else {
  84541. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84542. }
  84543. }
  84544. tmat.invert();
  84545. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  84546. lm.m[12] = vec.x;
  84547. lm.m[13] = vec.y;
  84548. lm.m[14] = vec.z;
  84549. }
  84550. this._markAsDirtyAndDecompose();
  84551. };
  84552. /**
  84553. * Set the absolute position of the bone (world space)
  84554. * @param position The position to set the bone
  84555. * @param mesh The mesh that this bone is attached to
  84556. */
  84557. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  84558. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  84559. };
  84560. /**
  84561. * Scale the bone on the x, y and z axes (in local space)
  84562. * @param x The amount to scale the bone on the x axis
  84563. * @param y The amount to scale the bone on the y axis
  84564. * @param z The amount to scale the bone on the z axis
  84565. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  84566. */
  84567. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  84568. if (scaleChildren === void 0) { scaleChildren = false; }
  84569. var locMat = this.getLocalMatrix();
  84570. // Apply new scaling on top of current local matrix
  84571. var scaleMat = Bone._tmpMats[0];
  84572. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  84573. scaleMat.multiplyToRef(locMat, locMat);
  84574. // Invert scaling matrix and apply the inverse to all children
  84575. scaleMat.invert();
  84576. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  84577. var child = _a[_i];
  84578. var cm = child.getLocalMatrix();
  84579. cm.multiplyToRef(scaleMat, cm);
  84580. cm.m[12] *= x;
  84581. cm.m[13] *= y;
  84582. cm.m[14] *= z;
  84583. child._markAsDirtyAndDecompose();
  84584. }
  84585. this._markAsDirtyAndDecompose();
  84586. if (scaleChildren) {
  84587. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  84588. var child = _c[_b];
  84589. child.scale(x, y, z, scaleChildren);
  84590. }
  84591. }
  84592. };
  84593. /**
  84594. * Set the bone scaling in local space
  84595. * @param scale defines the scaling vector
  84596. */
  84597. Bone.prototype.setScale = function (scale) {
  84598. this._decompose();
  84599. this._localScaling.copyFrom(scale);
  84600. this._markAsDirtyAndCompose();
  84601. };
  84602. /**
  84603. * Gets the current scaling in local space
  84604. * @returns the current scaling vector
  84605. */
  84606. Bone.prototype.getScale = function () {
  84607. this._decompose();
  84608. return this._localScaling;
  84609. };
  84610. /**
  84611. * Gets the current scaling in local space and stores it in a target vector
  84612. * @param result defines the target vector
  84613. */
  84614. Bone.prototype.getScaleToRef = function (result) {
  84615. this._decompose();
  84616. result.copyFrom(this._localScaling);
  84617. };
  84618. /**
  84619. * Set the yaw, pitch, and roll of the bone in local or world space
  84620. * @param yaw The rotation of the bone on the y axis
  84621. * @param pitch The rotation of the bone on the x axis
  84622. * @param roll The rotation of the bone on the z axis
  84623. * @param space The space that the axes of rotation are in
  84624. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84625. */
  84626. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  84627. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84628. if (space === BABYLON.Space.LOCAL) {
  84629. var quat = Bone._tmpQuat;
  84630. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  84631. this.setRotationQuaternion(quat, space, mesh);
  84632. return;
  84633. }
  84634. var rotMatInv = Bone._tmpMats[0];
  84635. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84636. return;
  84637. }
  84638. var rotMat = Bone._tmpMats[1];
  84639. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  84640. rotMatInv.multiplyToRef(rotMat, rotMat);
  84641. this._rotateWithMatrix(rotMat, space, mesh);
  84642. };
  84643. /**
  84644. * Add a rotation to the bone on an axis in local or world space
  84645. * @param axis The axis to rotate the bone on
  84646. * @param amount The amount to rotate the bone
  84647. * @param space The space that the axis is in
  84648. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84649. */
  84650. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  84651. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84652. var rmat = Bone._tmpMats[0];
  84653. rmat.m[12] = 0;
  84654. rmat.m[13] = 0;
  84655. rmat.m[14] = 0;
  84656. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  84657. this._rotateWithMatrix(rmat, space, mesh);
  84658. };
  84659. /**
  84660. * Set the rotation of the bone to a particular axis angle in local or world space
  84661. * @param axis The axis to rotate the bone on
  84662. * @param angle The angle that the bone should be rotated to
  84663. * @param space The space that the axis is in
  84664. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84665. */
  84666. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  84667. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84668. if (space === BABYLON.Space.LOCAL) {
  84669. var quat = Bone._tmpQuat;
  84670. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  84671. this.setRotationQuaternion(quat, space, mesh);
  84672. return;
  84673. }
  84674. var rotMatInv = Bone._tmpMats[0];
  84675. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84676. return;
  84677. }
  84678. var rotMat = Bone._tmpMats[1];
  84679. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  84680. rotMatInv.multiplyToRef(rotMat, rotMat);
  84681. this._rotateWithMatrix(rotMat, space, mesh);
  84682. };
  84683. /**
  84684. * Set the euler rotation of the bone in local of world space
  84685. * @param rotation The euler rotation that the bone should be set to
  84686. * @param space The space that the rotation is in
  84687. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84688. */
  84689. Bone.prototype.setRotation = function (rotation, space, mesh) {
  84690. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84691. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  84692. };
  84693. /**
  84694. * Set the quaternion rotation of the bone in local of world space
  84695. * @param quat The quaternion rotation that the bone should be set to
  84696. * @param space The space that the rotation is in
  84697. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84698. */
  84699. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  84700. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84701. if (space === BABYLON.Space.LOCAL) {
  84702. this._decompose();
  84703. this._localRotation.copyFrom(quat);
  84704. this._markAsDirtyAndCompose();
  84705. return;
  84706. }
  84707. var rotMatInv = Bone._tmpMats[0];
  84708. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84709. return;
  84710. }
  84711. var rotMat = Bone._tmpMats[1];
  84712. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  84713. rotMatInv.multiplyToRef(rotMat, rotMat);
  84714. this._rotateWithMatrix(rotMat, space, mesh);
  84715. };
  84716. /**
  84717. * Set the rotation matrix of the bone in local of world space
  84718. * @param rotMat The rotation matrix that the bone should be set to
  84719. * @param space The space that the rotation is in
  84720. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84721. */
  84722. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  84723. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84724. if (space === BABYLON.Space.LOCAL) {
  84725. var quat = Bone._tmpQuat;
  84726. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  84727. this.setRotationQuaternion(quat, space, mesh);
  84728. return;
  84729. }
  84730. var rotMatInv = Bone._tmpMats[0];
  84731. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84732. return;
  84733. }
  84734. var rotMat2 = Bone._tmpMats[1];
  84735. rotMat2.copyFrom(rotMat);
  84736. rotMatInv.multiplyToRef(rotMat, rotMat2);
  84737. this._rotateWithMatrix(rotMat2, space, mesh);
  84738. };
  84739. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  84740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84741. var lmat = this.getLocalMatrix();
  84742. var lx = lmat.m[12];
  84743. var ly = lmat.m[13];
  84744. var lz = lmat.m[14];
  84745. var parent = this.getParent();
  84746. var parentScale = Bone._tmpMats[3];
  84747. var parentScaleInv = Bone._tmpMats[4];
  84748. if (parent && space == BABYLON.Space.WORLD) {
  84749. if (mesh) {
  84750. parentScale.copyFrom(mesh.getWorldMatrix());
  84751. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  84752. }
  84753. else {
  84754. parentScale.copyFrom(parent.getAbsoluteTransform());
  84755. }
  84756. parentScaleInv.copyFrom(parentScale);
  84757. parentScaleInv.invert();
  84758. lmat.multiplyToRef(parentScale, lmat);
  84759. lmat.multiplyToRef(rmat, lmat);
  84760. lmat.multiplyToRef(parentScaleInv, lmat);
  84761. }
  84762. else {
  84763. if (space == BABYLON.Space.WORLD && mesh) {
  84764. parentScale.copyFrom(mesh.getWorldMatrix());
  84765. parentScaleInv.copyFrom(parentScale);
  84766. parentScaleInv.invert();
  84767. lmat.multiplyToRef(parentScale, lmat);
  84768. lmat.multiplyToRef(rmat, lmat);
  84769. lmat.multiplyToRef(parentScaleInv, lmat);
  84770. }
  84771. else {
  84772. lmat.multiplyToRef(rmat, lmat);
  84773. }
  84774. }
  84775. lmat.m[12] = lx;
  84776. lmat.m[13] = ly;
  84777. lmat.m[14] = lz;
  84778. this.computeAbsoluteTransforms();
  84779. this._markAsDirtyAndDecompose();
  84780. };
  84781. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  84782. var scaleMatrix = Bone._tmpMats[2];
  84783. rotMatInv.copyFrom(this.getAbsoluteTransform());
  84784. if (mesh) {
  84785. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  84786. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  84787. }
  84788. rotMatInv.invert();
  84789. if (isNaN(rotMatInv.m[0])) {
  84790. // Matrix failed to invert.
  84791. // This can happen if scale is zero for example.
  84792. return false;
  84793. }
  84794. scaleMatrix.m[0] *= this._scalingDeterminant;
  84795. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  84796. return true;
  84797. };
  84798. /**
  84799. * Get the position of the bone in local or world space
  84800. * @param space The space that the returned position is in
  84801. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84802. * @returns The position of the bone
  84803. */
  84804. Bone.prototype.getPosition = function (space, mesh) {
  84805. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84806. if (mesh === void 0) { mesh = null; }
  84807. var pos = BABYLON.Vector3.Zero();
  84808. this.getPositionToRef(space, mesh, pos);
  84809. return pos;
  84810. };
  84811. /**
  84812. * Copy the position of the bone to a vector3 in local or world space
  84813. * @param space The space that the returned position is in
  84814. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84815. * @param result The vector3 to copy the position to
  84816. */
  84817. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  84818. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84819. if (space == BABYLON.Space.LOCAL) {
  84820. var lm = this.getLocalMatrix();
  84821. result.x = lm.m[12];
  84822. result.y = lm.m[13];
  84823. result.z = lm.m[14];
  84824. }
  84825. else {
  84826. var wm = null;
  84827. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84828. if (mesh) {
  84829. wm = mesh.getWorldMatrix();
  84830. }
  84831. this._skeleton.computeAbsoluteTransforms();
  84832. var tmat = Bone._tmpMats[0];
  84833. if (mesh && wm) {
  84834. tmat.copyFrom(this.getAbsoluteTransform());
  84835. tmat.multiplyToRef(wm, tmat);
  84836. }
  84837. else {
  84838. tmat = this.getAbsoluteTransform();
  84839. }
  84840. result.x = tmat.m[12];
  84841. result.y = tmat.m[13];
  84842. result.z = tmat.m[14];
  84843. }
  84844. };
  84845. /**
  84846. * Get the absolute position of the bone (world space)
  84847. * @param mesh The mesh that this bone is attached to
  84848. * @returns The absolute position of the bone
  84849. */
  84850. Bone.prototype.getAbsolutePosition = function (mesh) {
  84851. if (mesh === void 0) { mesh = null; }
  84852. var pos = BABYLON.Vector3.Zero();
  84853. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  84854. return pos;
  84855. };
  84856. /**
  84857. * Copy the absolute position of the bone (world space) to the result param
  84858. * @param mesh The mesh that this bone is attached to
  84859. * @param result The vector3 to copy the absolute position to
  84860. */
  84861. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  84862. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  84863. };
  84864. /**
  84865. * Compute the absolute transforms of this bone and its children
  84866. */
  84867. Bone.prototype.computeAbsoluteTransforms = function () {
  84868. this._compose();
  84869. if (this._parent) {
  84870. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84871. }
  84872. else {
  84873. this._absoluteTransform.copyFrom(this._localMatrix);
  84874. var poseMatrix = this._skeleton.getPoseMatrix();
  84875. if (poseMatrix) {
  84876. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  84877. }
  84878. }
  84879. var children = this.children;
  84880. var len = children.length;
  84881. for (var i = 0; i < len; i++) {
  84882. children[i].computeAbsoluteTransforms();
  84883. }
  84884. };
  84885. /**
  84886. * Get the world direction from an axis that is in the local space of the bone
  84887. * @param localAxis The local direction that is used to compute the world direction
  84888. * @param mesh The mesh that this bone is attached to
  84889. * @returns The world direction
  84890. */
  84891. Bone.prototype.getDirection = function (localAxis, mesh) {
  84892. if (mesh === void 0) { mesh = null; }
  84893. var result = BABYLON.Vector3.Zero();
  84894. this.getDirectionToRef(localAxis, mesh, result);
  84895. return result;
  84896. };
  84897. /**
  84898. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  84899. * @param localAxis The local direction that is used to compute the world direction
  84900. * @param mesh The mesh that this bone is attached to
  84901. * @param result The vector3 that the world direction will be copied to
  84902. */
  84903. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  84904. if (mesh === void 0) { mesh = null; }
  84905. var wm = null;
  84906. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84907. if (mesh) {
  84908. wm = mesh.getWorldMatrix();
  84909. }
  84910. this._skeleton.computeAbsoluteTransforms();
  84911. var mat = Bone._tmpMats[0];
  84912. mat.copyFrom(this.getAbsoluteTransform());
  84913. if (mesh && wm) {
  84914. mat.multiplyToRef(wm, mat);
  84915. }
  84916. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  84917. result.normalize();
  84918. };
  84919. /**
  84920. * Get the euler rotation of the bone in local or world space
  84921. * @param space The space that the rotation should be in
  84922. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84923. * @returns The euler rotation
  84924. */
  84925. Bone.prototype.getRotation = function (space, mesh) {
  84926. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84927. if (mesh === void 0) { mesh = null; }
  84928. var result = BABYLON.Vector3.Zero();
  84929. this.getRotationToRef(space, mesh, result);
  84930. return result;
  84931. };
  84932. /**
  84933. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  84934. * @param space The space that the rotation should be in
  84935. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84936. * @param result The vector3 that the rotation should be copied to
  84937. */
  84938. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  84939. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84940. if (mesh === void 0) { mesh = null; }
  84941. var quat = Bone._tmpQuat;
  84942. this.getRotationQuaternionToRef(space, mesh, quat);
  84943. quat.toEulerAnglesToRef(result);
  84944. };
  84945. /**
  84946. * Get the quaternion rotation of the bone in either local or world space
  84947. * @param space The space that the rotation should be in
  84948. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84949. * @returns The quaternion rotation
  84950. */
  84951. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  84952. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84953. if (mesh === void 0) { mesh = null; }
  84954. var result = BABYLON.Quaternion.Identity();
  84955. this.getRotationQuaternionToRef(space, mesh, result);
  84956. return result;
  84957. };
  84958. /**
  84959. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  84960. * @param space The space that the rotation should be in
  84961. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84962. * @param result The quaternion that the rotation should be copied to
  84963. */
  84964. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  84965. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84966. if (mesh === void 0) { mesh = null; }
  84967. if (space == BABYLON.Space.LOCAL) {
  84968. this._decompose();
  84969. result.copyFrom(this._localRotation);
  84970. }
  84971. else {
  84972. var mat = Bone._tmpMats[0];
  84973. var amat = this.getAbsoluteTransform();
  84974. if (mesh) {
  84975. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84976. }
  84977. else {
  84978. mat.copyFrom(amat);
  84979. }
  84980. mat.m[0] *= this._scalingDeterminant;
  84981. mat.m[1] *= this._scalingDeterminant;
  84982. mat.m[2] *= this._scalingDeterminant;
  84983. mat.decompose(undefined, result, undefined);
  84984. }
  84985. };
  84986. /**
  84987. * Get the rotation matrix of the bone in local or world space
  84988. * @param space The space that the rotation should be in
  84989. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84990. * @returns The rotation matrix
  84991. */
  84992. Bone.prototype.getRotationMatrix = function (space, mesh) {
  84993. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84994. var result = BABYLON.Matrix.Identity();
  84995. this.getRotationMatrixToRef(space, mesh, result);
  84996. return result;
  84997. };
  84998. /**
  84999. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  85000. * @param space The space that the rotation should be in
  85001. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85002. * @param result The quaternion that the rotation should be copied to
  85003. */
  85004. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  85005. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85006. if (space == BABYLON.Space.LOCAL) {
  85007. this.getLocalMatrix().getRotationMatrixToRef(result);
  85008. }
  85009. else {
  85010. var mat = Bone._tmpMats[0];
  85011. var amat = this.getAbsoluteTransform();
  85012. if (mesh) {
  85013. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85014. }
  85015. else {
  85016. mat.copyFrom(amat);
  85017. }
  85018. mat.m[0] *= this._scalingDeterminant;
  85019. mat.m[1] *= this._scalingDeterminant;
  85020. mat.m[2] *= this._scalingDeterminant;
  85021. mat.getRotationMatrixToRef(result);
  85022. }
  85023. };
  85024. /**
  85025. * Get the world position of a point that is in the local space of the bone
  85026. * @param position The local position
  85027. * @param mesh The mesh that this bone is attached to
  85028. * @returns The world position
  85029. */
  85030. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  85031. if (mesh === void 0) { mesh = null; }
  85032. var result = BABYLON.Vector3.Zero();
  85033. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  85034. return result;
  85035. };
  85036. /**
  85037. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  85038. * @param position The local position
  85039. * @param mesh The mesh that this bone is attached to
  85040. * @param result The vector3 that the world position should be copied to
  85041. */
  85042. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  85043. if (mesh === void 0) { mesh = null; }
  85044. var wm = null;
  85045. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85046. if (mesh) {
  85047. wm = mesh.getWorldMatrix();
  85048. }
  85049. this._skeleton.computeAbsoluteTransforms();
  85050. var tmat = Bone._tmpMats[0];
  85051. if (mesh && wm) {
  85052. tmat.copyFrom(this.getAbsoluteTransform());
  85053. tmat.multiplyToRef(wm, tmat);
  85054. }
  85055. else {
  85056. tmat = this.getAbsoluteTransform();
  85057. }
  85058. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85059. };
  85060. /**
  85061. * Get the local position of a point that is in world space
  85062. * @param position The world position
  85063. * @param mesh The mesh that this bone is attached to
  85064. * @returns The local position
  85065. */
  85066. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  85067. if (mesh === void 0) { mesh = null; }
  85068. var result = BABYLON.Vector3.Zero();
  85069. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  85070. return result;
  85071. };
  85072. /**
  85073. * Get the local position of a point that is in world space and copy it to the result param
  85074. * @param position The world position
  85075. * @param mesh The mesh that this bone is attached to
  85076. * @param result The vector3 that the local position should be copied to
  85077. */
  85078. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  85079. if (mesh === void 0) { mesh = null; }
  85080. var wm = null;
  85081. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85082. if (mesh) {
  85083. wm = mesh.getWorldMatrix();
  85084. }
  85085. this._skeleton.computeAbsoluteTransforms();
  85086. var tmat = Bone._tmpMats[0];
  85087. tmat.copyFrom(this.getAbsoluteTransform());
  85088. if (mesh && wm) {
  85089. tmat.multiplyToRef(wm, tmat);
  85090. }
  85091. tmat.invert();
  85092. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85093. };
  85094. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85095. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  85096. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85097. return Bone;
  85098. }(BABYLON.Node));
  85099. BABYLON.Bone = Bone;
  85100. })(BABYLON || (BABYLON = {}));
  85101. //# sourceMappingURL=babylon.bone.js.map
  85102. var BABYLON;
  85103. (function (BABYLON) {
  85104. /**
  85105. * Class used to apply inverse kinematics to bones
  85106. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  85107. */
  85108. var BoneIKController = /** @class */ (function () {
  85109. /**
  85110. * Creates a new BoneIKController
  85111. * @param mesh defines the mesh to control
  85112. * @param bone defines the bone to control
  85113. * @param options defines options to set up the controller
  85114. */
  85115. function BoneIKController(mesh, bone, options) {
  85116. /**
  85117. * Gets or sets the target position
  85118. */
  85119. this.targetPosition = BABYLON.Vector3.Zero();
  85120. /**
  85121. * Gets or sets the pole target position
  85122. */
  85123. this.poleTargetPosition = BABYLON.Vector3.Zero();
  85124. /**
  85125. * Gets or sets the pole target local offset
  85126. */
  85127. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  85128. /**
  85129. * Gets or sets the pole angle
  85130. */
  85131. this.poleAngle = 0;
  85132. /**
  85133. * 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)
  85134. */
  85135. this.slerpAmount = 1;
  85136. this._bone1Quat = BABYLON.Quaternion.Identity();
  85137. this._bone1Mat = BABYLON.Matrix.Identity();
  85138. this._bone2Ang = Math.PI;
  85139. this._maxAngle = Math.PI;
  85140. this._rightHandedSystem = false;
  85141. this._bendAxis = BABYLON.Vector3.Right();
  85142. this._slerping = false;
  85143. this._adjustRoll = 0;
  85144. this._bone2 = bone;
  85145. this._bone1 = bone.getParent();
  85146. if (!this._bone1) {
  85147. return;
  85148. }
  85149. this.mesh = mesh;
  85150. var bonePos = bone.getPosition();
  85151. if (bone.getAbsoluteTransform().determinant() > 0) {
  85152. this._rightHandedSystem = true;
  85153. this._bendAxis.x = 0;
  85154. this._bendAxis.y = 0;
  85155. this._bendAxis.z = -1;
  85156. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  85157. this._adjustRoll = Math.PI * .5;
  85158. this._bendAxis.z = 1;
  85159. }
  85160. }
  85161. if (this._bone1.length) {
  85162. var boneScale1 = this._bone1.getScale();
  85163. var boneScale2 = this._bone2.getScale();
  85164. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  85165. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  85166. }
  85167. else if (this._bone1.children[0]) {
  85168. mesh.computeWorldMatrix(true);
  85169. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  85170. var pos2 = this._bone2.getAbsolutePosition(mesh);
  85171. var pos3 = this._bone1.getAbsolutePosition(mesh);
  85172. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  85173. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  85174. }
  85175. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  85176. this.maxAngle = Math.PI;
  85177. if (options) {
  85178. if (options.targetMesh) {
  85179. this.targetMesh = options.targetMesh;
  85180. this.targetMesh.computeWorldMatrix(true);
  85181. }
  85182. if (options.poleTargetMesh) {
  85183. this.poleTargetMesh = options.poleTargetMesh;
  85184. this.poleTargetMesh.computeWorldMatrix(true);
  85185. }
  85186. else if (options.poleTargetBone) {
  85187. this.poleTargetBone = options.poleTargetBone;
  85188. }
  85189. else if (this._bone1.getParent()) {
  85190. this.poleTargetBone = this._bone1.getParent();
  85191. }
  85192. if (options.poleTargetLocalOffset) {
  85193. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  85194. }
  85195. if (options.poleAngle) {
  85196. this.poleAngle = options.poleAngle;
  85197. }
  85198. if (options.bendAxis) {
  85199. this._bendAxis.copyFrom(options.bendAxis);
  85200. }
  85201. if (options.maxAngle) {
  85202. this.maxAngle = options.maxAngle;
  85203. }
  85204. if (options.slerpAmount) {
  85205. this.slerpAmount = options.slerpAmount;
  85206. }
  85207. }
  85208. }
  85209. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  85210. /**
  85211. * Gets or sets maximum allowed angle
  85212. */
  85213. get: function () {
  85214. return this._maxAngle;
  85215. },
  85216. set: function (value) {
  85217. this._setMaxAngle(value);
  85218. },
  85219. enumerable: true,
  85220. configurable: true
  85221. });
  85222. BoneIKController.prototype._setMaxAngle = function (ang) {
  85223. if (ang < 0) {
  85224. ang = 0;
  85225. }
  85226. if (ang > Math.PI || ang == undefined) {
  85227. ang = Math.PI;
  85228. }
  85229. this._maxAngle = ang;
  85230. var a = this._bone1Length;
  85231. var b = this._bone2Length;
  85232. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  85233. };
  85234. /**
  85235. * Force the controller to update the bones
  85236. */
  85237. BoneIKController.prototype.update = function () {
  85238. var bone1 = this._bone1;
  85239. if (!bone1) {
  85240. return;
  85241. }
  85242. var target = this.targetPosition;
  85243. var poleTarget = this.poleTargetPosition;
  85244. var mat1 = BoneIKController._tmpMats[0];
  85245. var mat2 = BoneIKController._tmpMats[1];
  85246. if (this.targetMesh) {
  85247. target.copyFrom(this.targetMesh.getAbsolutePosition());
  85248. }
  85249. if (this.poleTargetBone) {
  85250. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  85251. }
  85252. else if (this.poleTargetMesh) {
  85253. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  85254. }
  85255. var bonePos = BoneIKController._tmpVecs[0];
  85256. var zaxis = BoneIKController._tmpVecs[1];
  85257. var xaxis = BoneIKController._tmpVecs[2];
  85258. var yaxis = BoneIKController._tmpVecs[3];
  85259. var upAxis = BoneIKController._tmpVecs[4];
  85260. var _tmpQuat = BoneIKController._tmpQuat;
  85261. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  85262. poleTarget.subtractToRef(bonePos, upAxis);
  85263. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  85264. upAxis.y = 1;
  85265. }
  85266. else {
  85267. upAxis.normalize();
  85268. }
  85269. target.subtractToRef(bonePos, yaxis);
  85270. yaxis.normalize();
  85271. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  85272. zaxis.normalize();
  85273. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  85274. xaxis.normalize();
  85275. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  85276. var a = this._bone1Length;
  85277. var b = this._bone2Length;
  85278. var c = BABYLON.Vector3.Distance(bonePos, target);
  85279. if (this._maxReach > 0) {
  85280. c = Math.min(this._maxReach, c);
  85281. }
  85282. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  85283. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  85284. if (acosa > 1) {
  85285. acosa = 1;
  85286. }
  85287. if (acosb > 1) {
  85288. acosb = 1;
  85289. }
  85290. if (acosa < -1) {
  85291. acosa = -1;
  85292. }
  85293. if (acosb < -1) {
  85294. acosb = -1;
  85295. }
  85296. var angA = Math.acos(acosa);
  85297. var angB = Math.acos(acosb);
  85298. var angC = -angA - angB;
  85299. if (this._rightHandedSystem) {
  85300. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  85301. mat2.multiplyToRef(mat1, mat1);
  85302. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  85303. mat2.multiplyToRef(mat1, mat1);
  85304. }
  85305. else {
  85306. var _tmpVec = BoneIKController._tmpVecs[5];
  85307. _tmpVec.copyFrom(this._bendAxis);
  85308. _tmpVec.x *= -1;
  85309. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  85310. mat2.multiplyToRef(mat1, mat1);
  85311. }
  85312. if (this.poleAngle) {
  85313. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  85314. mat1.multiplyToRef(mat2, mat1);
  85315. }
  85316. if (this._bone1) {
  85317. if (this.slerpAmount < 1) {
  85318. if (!this._slerping) {
  85319. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  85320. }
  85321. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  85322. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  85323. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  85324. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  85325. this._slerping = true;
  85326. }
  85327. else {
  85328. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  85329. this._bone1Mat.copyFrom(mat1);
  85330. this._slerping = false;
  85331. }
  85332. }
  85333. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  85334. this._bone2Ang = angC;
  85335. };
  85336. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85337. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  85338. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85339. return BoneIKController;
  85340. }());
  85341. BABYLON.BoneIKController = BoneIKController;
  85342. })(BABYLON || (BABYLON = {}));
  85343. //# sourceMappingURL=babylon.boneIKController.js.map
  85344. var BABYLON;
  85345. (function (BABYLON) {
  85346. /**
  85347. * Class used to make a bone look toward a point in space
  85348. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  85349. */
  85350. var BoneLookController = /** @class */ (function () {
  85351. /**
  85352. * Create a BoneLookController
  85353. * @param mesh the mesh that the bone belongs to
  85354. * @param bone the bone that will be looking to the target
  85355. * @param target the target Vector3 to look at
  85356. * @param settings optional settings:
  85357. * * maxYaw: the maximum angle the bone will yaw to
  85358. * * minYaw: the minimum angle the bone will yaw to
  85359. * * maxPitch: the maximum angle the bone will pitch to
  85360. * * minPitch: the minimum angle the bone will yaw to
  85361. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  85362. * * upAxis: the up axis of the coordinate system
  85363. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  85364. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  85365. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  85366. * * adjustYaw: used to make an adjustment to the yaw of the bone
  85367. * * adjustPitch: used to make an adjustment to the pitch of the bone
  85368. * * adjustRoll: used to make an adjustment to the roll of the bone
  85369. **/
  85370. function BoneLookController(mesh, bone, target, options) {
  85371. /**
  85372. * The up axis of the coordinate system that is used when the bone is rotated
  85373. */
  85374. this.upAxis = BABYLON.Vector3.Up();
  85375. /**
  85376. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  85377. */
  85378. this.upAxisSpace = BABYLON.Space.LOCAL;
  85379. /**
  85380. * Used to make an adjustment to the yaw of the bone
  85381. */
  85382. this.adjustYaw = 0;
  85383. /**
  85384. * Used to make an adjustment to the pitch of the bone
  85385. */
  85386. this.adjustPitch = 0;
  85387. /**
  85388. * Used to make an adjustment to the roll of the bone
  85389. */
  85390. this.adjustRoll = 0;
  85391. /**
  85392. * 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)
  85393. */
  85394. this.slerpAmount = 1;
  85395. this._boneQuat = BABYLON.Quaternion.Identity();
  85396. this._slerping = false;
  85397. this._firstFrameSkipped = false;
  85398. this._fowardAxis = BABYLON.Vector3.Forward();
  85399. this.mesh = mesh;
  85400. this.bone = bone;
  85401. this.target = target;
  85402. if (options) {
  85403. if (options.adjustYaw) {
  85404. this.adjustYaw = options.adjustYaw;
  85405. }
  85406. if (options.adjustPitch) {
  85407. this.adjustPitch = options.adjustPitch;
  85408. }
  85409. if (options.adjustRoll) {
  85410. this.adjustRoll = options.adjustRoll;
  85411. }
  85412. if (options.maxYaw != null) {
  85413. this.maxYaw = options.maxYaw;
  85414. }
  85415. else {
  85416. this.maxYaw = Math.PI;
  85417. }
  85418. if (options.minYaw != null) {
  85419. this.minYaw = options.minYaw;
  85420. }
  85421. else {
  85422. this.minYaw = -Math.PI;
  85423. }
  85424. if (options.maxPitch != null) {
  85425. this.maxPitch = options.maxPitch;
  85426. }
  85427. else {
  85428. this.maxPitch = Math.PI;
  85429. }
  85430. if (options.minPitch != null) {
  85431. this.minPitch = options.minPitch;
  85432. }
  85433. else {
  85434. this.minPitch = -Math.PI;
  85435. }
  85436. if (options.slerpAmount != null) {
  85437. this.slerpAmount = options.slerpAmount;
  85438. }
  85439. if (options.upAxis != null) {
  85440. this.upAxis = options.upAxis;
  85441. }
  85442. if (options.upAxisSpace != null) {
  85443. this.upAxisSpace = options.upAxisSpace;
  85444. }
  85445. if (options.yawAxis != null || options.pitchAxis != null) {
  85446. var newYawAxis = BABYLON.Axis.Y;
  85447. var newPitchAxis = BABYLON.Axis.X;
  85448. if (options.yawAxis != null) {
  85449. newYawAxis = options.yawAxis.clone();
  85450. newYawAxis.normalize();
  85451. }
  85452. if (options.pitchAxis != null) {
  85453. newPitchAxis = options.pitchAxis.clone();
  85454. newPitchAxis.normalize();
  85455. }
  85456. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  85457. this._transformYawPitch = BABYLON.Matrix.Identity();
  85458. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  85459. this._transformYawPitchInv = this._transformYawPitch.clone();
  85460. this._transformYawPitch.invert();
  85461. }
  85462. }
  85463. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  85464. this.upAxisSpace = BABYLON.Space.LOCAL;
  85465. }
  85466. }
  85467. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  85468. /**
  85469. * Gets or sets the minimum yaw angle that the bone can look to
  85470. */
  85471. get: function () {
  85472. return this._minYaw;
  85473. },
  85474. set: function (value) {
  85475. this._minYaw = value;
  85476. this._minYawSin = Math.sin(value);
  85477. this._minYawCos = Math.cos(value);
  85478. if (this._maxYaw != null) {
  85479. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85480. this._yawRange = this._maxYaw - this._minYaw;
  85481. }
  85482. },
  85483. enumerable: true,
  85484. configurable: true
  85485. });
  85486. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  85487. /**
  85488. * Gets or sets the maximum yaw angle that the bone can look to
  85489. */
  85490. get: function () {
  85491. return this._maxYaw;
  85492. },
  85493. set: function (value) {
  85494. this._maxYaw = value;
  85495. this._maxYawSin = Math.sin(value);
  85496. this._maxYawCos = Math.cos(value);
  85497. if (this._minYaw != null) {
  85498. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85499. this._yawRange = this._maxYaw - this._minYaw;
  85500. }
  85501. },
  85502. enumerable: true,
  85503. configurable: true
  85504. });
  85505. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  85506. /**
  85507. * Gets or sets the minimum pitch angle that the bone can look to
  85508. */
  85509. get: function () {
  85510. return this._minPitch;
  85511. },
  85512. set: function (value) {
  85513. this._minPitch = value;
  85514. this._minPitchTan = Math.tan(value);
  85515. },
  85516. enumerable: true,
  85517. configurable: true
  85518. });
  85519. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  85520. /**
  85521. * Gets or sets the maximum pitch angle that the bone can look to
  85522. */
  85523. get: function () {
  85524. return this._maxPitch;
  85525. },
  85526. set: function (value) {
  85527. this._maxPitch = value;
  85528. this._maxPitchTan = Math.tan(value);
  85529. },
  85530. enumerable: true,
  85531. configurable: true
  85532. });
  85533. /**
  85534. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  85535. */
  85536. BoneLookController.prototype.update = function () {
  85537. //skip the first frame when slerping so that the mesh rotation is correct
  85538. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  85539. this._firstFrameSkipped = true;
  85540. return;
  85541. }
  85542. var bone = this.bone;
  85543. var bonePos = BoneLookController._tmpVecs[0];
  85544. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  85545. var target = this.target;
  85546. var _tmpMat1 = BoneLookController._tmpMats[0];
  85547. var _tmpMat2 = BoneLookController._tmpMats[1];
  85548. var mesh = this.mesh;
  85549. var parentBone = bone.getParent();
  85550. var upAxis = BoneLookController._tmpVecs[1];
  85551. upAxis.copyFrom(this.upAxis);
  85552. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  85553. if (this._transformYawPitch) {
  85554. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  85555. }
  85556. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  85557. }
  85558. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  85559. mesh.getDirectionToRef(upAxis, upAxis);
  85560. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  85561. upAxis.normalize();
  85562. }
  85563. }
  85564. var checkYaw = false;
  85565. var checkPitch = false;
  85566. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  85567. checkYaw = true;
  85568. }
  85569. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  85570. checkPitch = true;
  85571. }
  85572. if (checkYaw || checkPitch) {
  85573. var spaceMat = BoneLookController._tmpMats[2];
  85574. var spaceMatInv = BoneLookController._tmpMats[3];
  85575. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  85576. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  85577. }
  85578. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  85579. spaceMat.copyFrom(mesh.getWorldMatrix());
  85580. }
  85581. else {
  85582. var forwardAxis = BoneLookController._tmpVecs[2];
  85583. forwardAxis.copyFrom(this._fowardAxis);
  85584. if (this._transformYawPitch) {
  85585. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  85586. }
  85587. if (parentBone) {
  85588. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  85589. }
  85590. else {
  85591. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  85592. }
  85593. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  85594. rightAxis.normalize();
  85595. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  85596. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  85597. }
  85598. spaceMat.invertToRef(spaceMatInv);
  85599. var xzlen = null;
  85600. if (checkPitch) {
  85601. var localTarget = BoneLookController._tmpVecs[3];
  85602. target.subtractToRef(bonePos, localTarget);
  85603. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85604. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85605. var pitch = Math.atan2(localTarget.y, xzlen);
  85606. var newPitch = pitch;
  85607. if (pitch > this._maxPitch) {
  85608. localTarget.y = this._maxPitchTan * xzlen;
  85609. newPitch = this._maxPitch;
  85610. }
  85611. else if (pitch < this._minPitch) {
  85612. localTarget.y = this._minPitchTan * xzlen;
  85613. newPitch = this._minPitch;
  85614. }
  85615. if (pitch != newPitch) {
  85616. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85617. localTarget.addInPlace(bonePos);
  85618. target = localTarget;
  85619. }
  85620. }
  85621. if (checkYaw) {
  85622. var localTarget = BoneLookController._tmpVecs[4];
  85623. target.subtractToRef(bonePos, localTarget);
  85624. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85625. var yaw = Math.atan2(localTarget.x, localTarget.z);
  85626. var newYaw = yaw;
  85627. if (yaw > this._maxYaw || yaw < this._minYaw) {
  85628. if (xzlen == null) {
  85629. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85630. }
  85631. if (this._yawRange > Math.PI) {
  85632. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  85633. localTarget.z = this._maxYawCos * xzlen;
  85634. localTarget.x = this._maxYawSin * xzlen;
  85635. newYaw = this._maxYaw;
  85636. }
  85637. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  85638. localTarget.z = this._minYawCos * xzlen;
  85639. localTarget.x = this._minYawSin * xzlen;
  85640. newYaw = this._minYaw;
  85641. }
  85642. }
  85643. else {
  85644. if (yaw > this._maxYaw) {
  85645. localTarget.z = this._maxYawCos * xzlen;
  85646. localTarget.x = this._maxYawSin * xzlen;
  85647. newYaw = this._maxYaw;
  85648. }
  85649. else if (yaw < this._minYaw) {
  85650. localTarget.z = this._minYawCos * xzlen;
  85651. localTarget.x = this._minYawSin * xzlen;
  85652. newYaw = this._minYaw;
  85653. }
  85654. }
  85655. }
  85656. if (this._slerping && this._yawRange > Math.PI) {
  85657. //are we going to be crossing into the min/max region?
  85658. var boneFwd = BoneLookController._tmpVecs[8];
  85659. boneFwd.copyFrom(BABYLON.Axis.Z);
  85660. if (this._transformYawPitch) {
  85661. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  85662. }
  85663. var boneRotMat = BoneLookController._tmpMats[4];
  85664. this._boneQuat.toRotationMatrix(boneRotMat);
  85665. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  85666. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  85667. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  85668. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  85669. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  85670. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  85671. if (angBtwTar > angBtwMidYaw) {
  85672. if (xzlen == null) {
  85673. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85674. }
  85675. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  85676. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  85677. if (angBtwMin < angBtwMax) {
  85678. newYaw = boneYaw + Math.PI * .75;
  85679. localTarget.z = Math.cos(newYaw) * xzlen;
  85680. localTarget.x = Math.sin(newYaw) * xzlen;
  85681. }
  85682. else {
  85683. newYaw = boneYaw - Math.PI * .75;
  85684. localTarget.z = Math.cos(newYaw) * xzlen;
  85685. localTarget.x = Math.sin(newYaw) * xzlen;
  85686. }
  85687. }
  85688. }
  85689. if (yaw != newYaw) {
  85690. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85691. localTarget.addInPlace(bonePos);
  85692. target = localTarget;
  85693. }
  85694. }
  85695. }
  85696. var zaxis = BoneLookController._tmpVecs[5];
  85697. var xaxis = BoneLookController._tmpVecs[6];
  85698. var yaxis = BoneLookController._tmpVecs[7];
  85699. var _tmpQuat = BoneLookController._tmpQuat;
  85700. target.subtractToRef(bonePos, zaxis);
  85701. zaxis.normalize();
  85702. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  85703. xaxis.normalize();
  85704. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  85705. yaxis.normalize();
  85706. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  85707. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  85708. return;
  85709. }
  85710. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  85711. return;
  85712. }
  85713. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  85714. return;
  85715. }
  85716. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  85717. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  85718. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  85719. }
  85720. if (this.slerpAmount < 1) {
  85721. if (!this._slerping) {
  85722. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  85723. }
  85724. if (this._transformYawPitch) {
  85725. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85726. }
  85727. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  85728. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  85729. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  85730. this._slerping = true;
  85731. }
  85732. else {
  85733. if (this._transformYawPitch) {
  85734. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85735. }
  85736. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  85737. this._slerping = false;
  85738. }
  85739. };
  85740. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  85741. var angDiff = ang2 - ang1;
  85742. angDiff %= Math.PI * 2;
  85743. if (angDiff > Math.PI) {
  85744. angDiff -= Math.PI * 2;
  85745. }
  85746. else if (angDiff < -Math.PI) {
  85747. angDiff += Math.PI * 2;
  85748. }
  85749. return angDiff;
  85750. };
  85751. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  85752. ang1 %= (2 * Math.PI);
  85753. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85754. ang2 %= (2 * Math.PI);
  85755. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85756. var ab = 0;
  85757. if (ang1 < ang2) {
  85758. ab = ang2 - ang1;
  85759. }
  85760. else {
  85761. ab = ang1 - ang2;
  85762. }
  85763. if (ab > Math.PI) {
  85764. ab = Math.PI * 2 - ab;
  85765. }
  85766. return ab;
  85767. };
  85768. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  85769. ang %= (2 * Math.PI);
  85770. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  85771. ang1 %= (2 * Math.PI);
  85772. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85773. ang2 %= (2 * Math.PI);
  85774. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85775. if (ang1 < ang2) {
  85776. if (ang > ang1 && ang < ang2) {
  85777. return true;
  85778. }
  85779. }
  85780. else {
  85781. if (ang > ang2 && ang < ang1) {
  85782. return true;
  85783. }
  85784. }
  85785. return false;
  85786. };
  85787. 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()];
  85788. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  85789. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85790. return BoneLookController;
  85791. }());
  85792. BABYLON.BoneLookController = BoneLookController;
  85793. })(BABYLON || (BABYLON = {}));
  85794. //# sourceMappingURL=babylon.boneLookController.js.map
  85795. var BABYLON;
  85796. (function (BABYLON) {
  85797. /**
  85798. * Class used to handle skinning animations
  85799. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  85800. */
  85801. var Skeleton = /** @class */ (function () {
  85802. /**
  85803. * Creates a new skeleton
  85804. * @param name defines the skeleton name
  85805. * @param id defines the skeleton Id
  85806. * @param scene defines the hosting scene
  85807. */
  85808. function Skeleton(
  85809. /** defines the skeleton name */
  85810. name,
  85811. /** defines the skeleton Id */
  85812. id, scene) {
  85813. this.name = name;
  85814. this.id = id;
  85815. /**
  85816. * Gets the list of child bones
  85817. */
  85818. this.bones = new Array();
  85819. /**
  85820. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  85821. */
  85822. this.needInitialSkinMatrix = false;
  85823. this._isDirty = true;
  85824. this._meshesWithPoseMatrix = new Array();
  85825. this._identity = BABYLON.Matrix.Identity();
  85826. this._ranges = {};
  85827. this._lastAbsoluteTransformsUpdateId = -1;
  85828. /**
  85829. * Specifies if the skeleton should be serialized
  85830. */
  85831. this.doNotSerialize = false;
  85832. this._animationPropertiesOverride = null;
  85833. // Events
  85834. /**
  85835. * An observable triggered before computing the skeleton's matrices
  85836. */
  85837. this.onBeforeComputeObservable = new BABYLON.Observable();
  85838. this.bones = [];
  85839. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85840. scene.skeletons.push(this);
  85841. //make sure it will recalculate the matrix next time prepare is called.
  85842. this._isDirty = true;
  85843. }
  85844. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  85845. /**
  85846. * Gets or sets the animation properties override
  85847. */
  85848. get: function () {
  85849. if (!this._animationPropertiesOverride) {
  85850. return this._scene.animationPropertiesOverride;
  85851. }
  85852. return this._animationPropertiesOverride;
  85853. },
  85854. set: function (value) {
  85855. this._animationPropertiesOverride = value;
  85856. },
  85857. enumerable: true,
  85858. configurable: true
  85859. });
  85860. // Members
  85861. /**
  85862. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  85863. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  85864. * @returns a Float32Array containing matrices data
  85865. */
  85866. Skeleton.prototype.getTransformMatrices = function (mesh) {
  85867. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  85868. return mesh._bonesTransformMatrices;
  85869. }
  85870. if (!this._transformMatrices) {
  85871. this.prepare();
  85872. }
  85873. return this._transformMatrices;
  85874. };
  85875. /**
  85876. * Gets the current hosting scene
  85877. * @returns a scene object
  85878. */
  85879. Skeleton.prototype.getScene = function () {
  85880. return this._scene;
  85881. };
  85882. // Methods
  85883. /**
  85884. * Gets a string representing the current skeleton data
  85885. * @param fullDetails defines a boolean indicating if we want a verbose version
  85886. * @returns a string representing the current skeleton data
  85887. */
  85888. Skeleton.prototype.toString = function (fullDetails) {
  85889. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  85890. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  85891. if (fullDetails) {
  85892. ret += ", Ranges: {";
  85893. var first = true;
  85894. for (var name_1 in this._ranges) {
  85895. if (first) {
  85896. ret += ", ";
  85897. first = false;
  85898. }
  85899. ret += name_1;
  85900. }
  85901. ret += "}";
  85902. }
  85903. return ret;
  85904. };
  85905. /**
  85906. * Get bone's index searching by name
  85907. * @param name defines bone's name to search for
  85908. * @return the indice of the bone. Returns -1 if not found
  85909. */
  85910. Skeleton.prototype.getBoneIndexByName = function (name) {
  85911. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  85912. if (this.bones[boneIndex].name === name) {
  85913. return boneIndex;
  85914. }
  85915. }
  85916. return -1;
  85917. };
  85918. /**
  85919. * Creater a new animation range
  85920. * @param name defines the name of the range
  85921. * @param from defines the start key
  85922. * @param to defines the end key
  85923. */
  85924. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  85925. // check name not already in use
  85926. if (!this._ranges[name]) {
  85927. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  85928. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85929. if (this.bones[i].animations[0]) {
  85930. this.bones[i].animations[0].createRange(name, from, to);
  85931. }
  85932. }
  85933. }
  85934. };
  85935. /**
  85936. * Delete a specific animation range
  85937. * @param name defines the name of the range
  85938. * @param deleteFrames defines if frames must be removed as well
  85939. */
  85940. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  85941. if (deleteFrames === void 0) { deleteFrames = true; }
  85942. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85943. if (this.bones[i].animations[0]) {
  85944. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  85945. }
  85946. }
  85947. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  85948. };
  85949. /**
  85950. * Gets a specific animation range
  85951. * @param name defines the name of the range to look for
  85952. * @returns the requested animation range or null if not found
  85953. */
  85954. Skeleton.prototype.getAnimationRange = function (name) {
  85955. return this._ranges[name];
  85956. };
  85957. /**
  85958. * Gets the list of all animation ranges defined on this skeleton
  85959. * @returns an array
  85960. */
  85961. Skeleton.prototype.getAnimationRanges = function () {
  85962. var animationRanges = [];
  85963. var name;
  85964. var i = 0;
  85965. for (name in this._ranges) {
  85966. animationRanges[i] = this._ranges[name];
  85967. i++;
  85968. }
  85969. return animationRanges;
  85970. };
  85971. /**
  85972. * Copy animation range from a source skeleton.
  85973. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  85974. * @param source defines the source skeleton
  85975. * @param name defines the name of the range to copy
  85976. * @param rescaleAsRequired defines if rescaling must be applied if required
  85977. * @returns true if operation was successful
  85978. */
  85979. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  85980. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  85981. if (this._ranges[name] || !source.getAnimationRange(name)) {
  85982. return false;
  85983. }
  85984. var ret = true;
  85985. var frameOffset = this._getHighestAnimationFrame() + 1;
  85986. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  85987. var boneDict = {};
  85988. var sourceBones = source.bones;
  85989. var nBones;
  85990. var i;
  85991. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  85992. boneDict[sourceBones[i].name] = sourceBones[i];
  85993. }
  85994. if (this.bones.length !== sourceBones.length) {
  85995. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  85996. ret = false;
  85997. }
  85998. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  85999. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  86000. var boneName = this.bones[i].name;
  86001. var sourceBone = boneDict[boneName];
  86002. if (sourceBone) {
  86003. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  86004. }
  86005. else {
  86006. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  86007. ret = false;
  86008. }
  86009. }
  86010. // do not call createAnimationRange(), since it also is done to bones, which was already done
  86011. var range = source.getAnimationRange(name);
  86012. if (range) {
  86013. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  86014. }
  86015. return ret;
  86016. };
  86017. /**
  86018. * Forces the skeleton to go to rest pose
  86019. */
  86020. Skeleton.prototype.returnToRest = function () {
  86021. for (var index = 0; index < this.bones.length; index++) {
  86022. this.bones[index].returnToRest();
  86023. }
  86024. };
  86025. Skeleton.prototype._getHighestAnimationFrame = function () {
  86026. var ret = 0;
  86027. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86028. if (this.bones[i].animations[0]) {
  86029. var highest = this.bones[i].animations[0].getHighestFrame();
  86030. if (ret < highest) {
  86031. ret = highest;
  86032. }
  86033. }
  86034. }
  86035. return ret;
  86036. };
  86037. /**
  86038. * Begin a specific animation range
  86039. * @param name defines the name of the range to start
  86040. * @param loop defines if looping must be turned on (false by default)
  86041. * @param speedRatio defines the speed ratio to apply (1 by default)
  86042. * @param onAnimationEnd defines a callback which will be called when animation will end
  86043. * @returns a new animatable
  86044. */
  86045. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  86046. var range = this.getAnimationRange(name);
  86047. if (!range) {
  86048. return null;
  86049. }
  86050. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  86051. };
  86052. /** @hidden */
  86053. Skeleton.prototype._markAsDirty = function () {
  86054. this._isDirty = true;
  86055. };
  86056. /** @hidden */
  86057. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  86058. this._meshesWithPoseMatrix.push(mesh);
  86059. };
  86060. /** @hidden */
  86061. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  86062. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  86063. if (index > -1) {
  86064. this._meshesWithPoseMatrix.splice(index, 1);
  86065. }
  86066. };
  86067. /** @hidden */
  86068. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  86069. this.onBeforeComputeObservable.notifyObservers(this);
  86070. for (var index = 0; index < this.bones.length; index++) {
  86071. var bone = this.bones[index];
  86072. var parentBone = bone.getParent();
  86073. if (parentBone) {
  86074. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  86075. }
  86076. else {
  86077. if (initialSkinMatrix) {
  86078. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  86079. }
  86080. else {
  86081. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  86082. }
  86083. }
  86084. if (bone._index !== -1) {
  86085. var mappedIndex = bone._index === null ? index : bone._index;
  86086. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  86087. }
  86088. }
  86089. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  86090. };
  86091. /**
  86092. * Build all resources required to render a skeleton
  86093. */
  86094. Skeleton.prototype.prepare = function () {
  86095. if (!this._isDirty) {
  86096. return;
  86097. }
  86098. if (this.needInitialSkinMatrix) {
  86099. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  86100. var mesh = this._meshesWithPoseMatrix[index];
  86101. var poseMatrix = mesh.getPoseMatrix();
  86102. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  86103. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86104. }
  86105. if (this._synchronizedWithMesh !== mesh) {
  86106. this._synchronizedWithMesh = mesh;
  86107. // Prepare bones
  86108. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  86109. var bone = this.bones[boneIndex];
  86110. if (!bone.getParent()) {
  86111. var matrix = bone.getBaseMatrix();
  86112. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  86113. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  86114. }
  86115. }
  86116. }
  86117. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  86118. }
  86119. }
  86120. else {
  86121. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  86122. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86123. }
  86124. this._computeTransformMatrices(this._transformMatrices, null);
  86125. }
  86126. this._isDirty = false;
  86127. this._scene._activeBones.addCount(this.bones.length, false);
  86128. };
  86129. /**
  86130. * Gets the list of animatables currently running for this skeleton
  86131. * @returns an array of animatables
  86132. */
  86133. Skeleton.prototype.getAnimatables = function () {
  86134. if (!this._animatables || this._animatables.length !== this.bones.length) {
  86135. this._animatables = [];
  86136. for (var index = 0; index < this.bones.length; index++) {
  86137. this._animatables.push(this.bones[index]);
  86138. }
  86139. }
  86140. return this._animatables;
  86141. };
  86142. /**
  86143. * Clone the current skeleton
  86144. * @param name defines the name of the new skeleton
  86145. * @param id defines the id of the enw skeleton
  86146. * @returns the new skeleton
  86147. */
  86148. Skeleton.prototype.clone = function (name, id) {
  86149. var result = new Skeleton(name, id || name, this._scene);
  86150. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86151. for (var index = 0; index < this.bones.length; index++) {
  86152. var source = this.bones[index];
  86153. var parentBone = null;
  86154. var parent_1 = source.getParent();
  86155. if (parent_1) {
  86156. var parentIndex = this.bones.indexOf(parent_1);
  86157. parentBone = result.bones[parentIndex];
  86158. }
  86159. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  86160. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  86161. }
  86162. if (this._ranges) {
  86163. result._ranges = {};
  86164. for (var rangeName in this._ranges) {
  86165. var range = this._ranges[rangeName];
  86166. if (range) {
  86167. result._ranges[rangeName] = range.clone();
  86168. }
  86169. }
  86170. }
  86171. this._isDirty = true;
  86172. return result;
  86173. };
  86174. /**
  86175. * Enable animation blending for this skeleton
  86176. * @param blendingSpeed defines the blending speed to apply
  86177. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  86178. */
  86179. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  86180. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  86181. this.bones.forEach(function (bone) {
  86182. bone.animations.forEach(function (animation) {
  86183. animation.enableBlending = true;
  86184. animation.blendingSpeed = blendingSpeed;
  86185. });
  86186. });
  86187. };
  86188. /**
  86189. * Releases all resources associated with the current skeleton
  86190. */
  86191. Skeleton.prototype.dispose = function () {
  86192. this._meshesWithPoseMatrix = [];
  86193. // Animations
  86194. this.getScene().stopAnimation(this);
  86195. // Remove from scene
  86196. this.getScene().removeSkeleton(this);
  86197. };
  86198. /**
  86199. * Serialize the skeleton in a JSON object
  86200. * @returns a JSON object
  86201. */
  86202. Skeleton.prototype.serialize = function () {
  86203. var serializationObject = {};
  86204. serializationObject.name = this.name;
  86205. serializationObject.id = this.id;
  86206. if (this.dimensionsAtRest) {
  86207. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  86208. }
  86209. serializationObject.bones = [];
  86210. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86211. for (var index = 0; index < this.bones.length; index++) {
  86212. var bone = this.bones[index];
  86213. var parent_2 = bone.getParent();
  86214. var serializedBone = {
  86215. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  86216. name: bone.name,
  86217. matrix: bone.getBaseMatrix().toArray(),
  86218. rest: bone.getRestPose().toArray()
  86219. };
  86220. serializationObject.bones.push(serializedBone);
  86221. if (bone.length) {
  86222. serializedBone.length = bone.length;
  86223. }
  86224. if (bone.metadata) {
  86225. serializedBone.metadata = bone.metadata;
  86226. }
  86227. if (bone.animations && bone.animations.length > 0) {
  86228. serializedBone.animation = bone.animations[0].serialize();
  86229. }
  86230. serializationObject.ranges = [];
  86231. for (var name in this._ranges) {
  86232. var source = this._ranges[name];
  86233. if (!source) {
  86234. continue;
  86235. }
  86236. var range = {};
  86237. range.name = name;
  86238. range.from = source.from;
  86239. range.to = source.to;
  86240. serializationObject.ranges.push(range);
  86241. }
  86242. }
  86243. return serializationObject;
  86244. };
  86245. /**
  86246. * Creates a new skeleton from serialized data
  86247. * @param parsedSkeleton defines the serialized data
  86248. * @param scene defines the hosting scene
  86249. * @returns a new skeleton
  86250. */
  86251. Skeleton.Parse = function (parsedSkeleton, scene) {
  86252. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  86253. if (parsedSkeleton.dimensionsAtRest) {
  86254. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  86255. }
  86256. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  86257. var index;
  86258. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  86259. var parsedBone = parsedSkeleton.bones[index];
  86260. var parentBone = null;
  86261. if (parsedBone.parentBoneIndex > -1) {
  86262. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  86263. }
  86264. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  86265. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  86266. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  86267. bone.id = parsedBone.id;
  86268. }
  86269. if (parsedBone.length) {
  86270. bone.length = parsedBone.length;
  86271. }
  86272. if (parsedBone.metadata) {
  86273. bone.metadata = parsedBone.metadata;
  86274. }
  86275. if (parsedBone.animation) {
  86276. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  86277. }
  86278. }
  86279. // placed after bones, so createAnimationRange can cascade down
  86280. if (parsedSkeleton.ranges) {
  86281. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  86282. var data = parsedSkeleton.ranges[index];
  86283. skeleton.createAnimationRange(data.name, data.from, data.to);
  86284. }
  86285. }
  86286. return skeleton;
  86287. };
  86288. /**
  86289. * Compute all node absolute transforms
  86290. * @param forceUpdate defines if computation must be done even if cache is up to date
  86291. */
  86292. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  86293. if (forceUpdate === void 0) { forceUpdate = false; }
  86294. var renderId = this._scene.getRenderId();
  86295. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  86296. this.bones[0].computeAbsoluteTransforms();
  86297. this._lastAbsoluteTransformsUpdateId = renderId;
  86298. }
  86299. };
  86300. /**
  86301. * Gets the root pose matrix
  86302. * @returns a matrix
  86303. */
  86304. Skeleton.prototype.getPoseMatrix = function () {
  86305. var poseMatrix = null;
  86306. if (this._meshesWithPoseMatrix.length > 0) {
  86307. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  86308. }
  86309. return poseMatrix;
  86310. };
  86311. /**
  86312. * Sorts bones per internal index
  86313. */
  86314. Skeleton.prototype.sortBones = function () {
  86315. var bones = new Array();
  86316. var visited = new Array(this.bones.length);
  86317. for (var index = 0; index < this.bones.length; index++) {
  86318. this._sortBones(index, bones, visited);
  86319. }
  86320. this.bones = bones;
  86321. };
  86322. Skeleton.prototype._sortBones = function (index, bones, visited) {
  86323. if (visited[index]) {
  86324. return;
  86325. }
  86326. visited[index] = true;
  86327. var bone = this.bones[index];
  86328. if (bone._index === undefined) {
  86329. bone._index = index;
  86330. }
  86331. var parentBone = bone.getParent();
  86332. if (parentBone) {
  86333. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  86334. }
  86335. bones.push(bone);
  86336. };
  86337. return Skeleton;
  86338. }());
  86339. BABYLON.Skeleton = Skeleton;
  86340. })(BABYLON || (BABYLON = {}));
  86341. //# sourceMappingURL=babylon.skeleton.js.map
  86342. var BABYLON;
  86343. (function (BABYLON) {
  86344. ;
  86345. /**
  86346. * This groups tools to convert HDR texture to native colors array.
  86347. */
  86348. var HDRTools = /** @class */ (function () {
  86349. function HDRTools() {
  86350. }
  86351. HDRTools.Ldexp = function (mantissa, exponent) {
  86352. if (exponent > 1023) {
  86353. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  86354. }
  86355. if (exponent < -1074) {
  86356. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  86357. }
  86358. return mantissa * Math.pow(2, exponent);
  86359. };
  86360. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  86361. if (exponent > 0) { /*nonzero pixel*/
  86362. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  86363. float32array[index + 0] = red * exponent;
  86364. float32array[index + 1] = green * exponent;
  86365. float32array[index + 2] = blue * exponent;
  86366. }
  86367. else {
  86368. float32array[index + 0] = 0;
  86369. float32array[index + 1] = 0;
  86370. float32array[index + 2] = 0;
  86371. }
  86372. };
  86373. HDRTools.readStringLine = function (uint8array, startIndex) {
  86374. var line = "";
  86375. var character = "";
  86376. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  86377. character = String.fromCharCode(uint8array[i]);
  86378. if (character == "\n") {
  86379. break;
  86380. }
  86381. line += character;
  86382. }
  86383. return line;
  86384. };
  86385. /**
  86386. * Reads header information from an RGBE texture stored in a native array.
  86387. * More information on this format are available here:
  86388. * https://en.wikipedia.org/wiki/RGBE_image_format
  86389. *
  86390. * @param uint8array The binary file stored in native array.
  86391. * @return The header information.
  86392. */
  86393. HDRTools.RGBE_ReadHeader = function (uint8array) {
  86394. var height = 0;
  86395. var width = 0;
  86396. var line = this.readStringLine(uint8array, 0);
  86397. if (line[0] != '#' || line[1] != '?') {
  86398. throw "Bad HDR Format.";
  86399. }
  86400. var endOfHeader = false;
  86401. var findFormat = false;
  86402. var lineIndex = 0;
  86403. do {
  86404. lineIndex += (line.length + 1);
  86405. line = this.readStringLine(uint8array, lineIndex);
  86406. if (line == "FORMAT=32-bit_rle_rgbe") {
  86407. findFormat = true;
  86408. }
  86409. else if (line.length == 0) {
  86410. endOfHeader = true;
  86411. }
  86412. } while (!endOfHeader);
  86413. if (!findFormat) {
  86414. throw "HDR Bad header format, unsupported FORMAT";
  86415. }
  86416. lineIndex += (line.length + 1);
  86417. line = this.readStringLine(uint8array, lineIndex);
  86418. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  86419. var match = sizeRegexp.exec(line);
  86420. // TODO. Support +Y and -X if needed.
  86421. if (!match || match.length < 3) {
  86422. throw "HDR Bad header format, no size";
  86423. }
  86424. width = parseInt(match[2]);
  86425. height = parseInt(match[1]);
  86426. if (width < 8 || width > 0x7fff) {
  86427. throw "HDR Bad header format, unsupported size";
  86428. }
  86429. lineIndex += (line.length + 1);
  86430. return {
  86431. height: height,
  86432. width: width,
  86433. dataPosition: lineIndex
  86434. };
  86435. };
  86436. /**
  86437. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  86438. * This RGBE texture needs to store the information as a panorama.
  86439. *
  86440. * More information on this format are available here:
  86441. * https://en.wikipedia.org/wiki/RGBE_image_format
  86442. *
  86443. * @param buffer The binary file stored in an array buffer.
  86444. * @param size The expected size of the extracted cubemap.
  86445. * @return The Cube Map information.
  86446. */
  86447. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  86448. var uint8array = new Uint8Array(buffer);
  86449. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  86450. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86451. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  86452. return cubeMapData;
  86453. };
  86454. /**
  86455. * Returns the pixels data extracted from an RGBE texture.
  86456. * This pixels will be stored left to right up to down in the R G B order in one array.
  86457. *
  86458. * More information on this format are available here:
  86459. * https://en.wikipedia.org/wiki/RGBE_image_format
  86460. *
  86461. * @param uint8array The binary file stored in an array buffer.
  86462. * @param hdrInfo The header information of the file.
  86463. * @return The pixels data in RGB right to left up to down order.
  86464. */
  86465. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  86466. // Keep for multi format supports.
  86467. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86468. };
  86469. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  86470. var num_scanlines = hdrInfo.height;
  86471. var scanline_width = hdrInfo.width;
  86472. var a, b, c, d, count;
  86473. var dataIndex = hdrInfo.dataPosition;
  86474. var index = 0, endIndex = 0, i = 0;
  86475. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  86476. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  86477. // 3 channels of 4 bytes per pixel in float.
  86478. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  86479. var resultArray = new Float32Array(resultBuffer);
  86480. // read in each successive scanline
  86481. while (num_scanlines > 0) {
  86482. a = uint8array[dataIndex++];
  86483. b = uint8array[dataIndex++];
  86484. c = uint8array[dataIndex++];
  86485. d = uint8array[dataIndex++];
  86486. if (a != 2 || b != 2 || (c & 0x80)) {
  86487. // this file is not run length encoded
  86488. throw "HDR Bad header format, not RLE";
  86489. }
  86490. if (((c << 8) | d) != scanline_width) {
  86491. throw "HDR Bad header format, wrong scan line width";
  86492. }
  86493. index = 0;
  86494. // read each of the four channels for the scanline into the buffer
  86495. for (i = 0; i < 4; i++) {
  86496. endIndex = (i + 1) * scanline_width;
  86497. while (index < endIndex) {
  86498. a = uint8array[dataIndex++];
  86499. b = uint8array[dataIndex++];
  86500. if (a > 128) {
  86501. // a run of the same value
  86502. count = a - 128;
  86503. if ((count == 0) || (count > endIndex - index)) {
  86504. throw "HDR Bad Format, bad scanline data (run)";
  86505. }
  86506. while (count-- > 0) {
  86507. scanLineArray[index++] = b;
  86508. }
  86509. }
  86510. else {
  86511. // a non-run
  86512. count = a;
  86513. if ((count == 0) || (count > endIndex - index)) {
  86514. throw "HDR Bad Format, bad scanline data (non-run)";
  86515. }
  86516. scanLineArray[index++] = b;
  86517. if (--count > 0) {
  86518. for (var j = 0; j < count; j++) {
  86519. scanLineArray[index++] = uint8array[dataIndex++];
  86520. }
  86521. }
  86522. }
  86523. }
  86524. }
  86525. // now convert data from buffer into floats
  86526. for (i = 0; i < scanline_width; i++) {
  86527. a = scanLineArray[i];
  86528. b = scanLineArray[i + scanline_width];
  86529. c = scanLineArray[i + 2 * scanline_width];
  86530. d = scanLineArray[i + 3 * scanline_width];
  86531. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  86532. }
  86533. num_scanlines--;
  86534. }
  86535. return resultArray;
  86536. };
  86537. return HDRTools;
  86538. }());
  86539. BABYLON.HDRTools = HDRTools;
  86540. })(BABYLON || (BABYLON = {}));
  86541. //# sourceMappingURL=babylon.hdr.js.map
  86542. var BABYLON;
  86543. (function (BABYLON) {
  86544. /**
  86545. * This represents a texture coming from an HDR input.
  86546. *
  86547. * The only supported format is currently panorama picture stored in RGBE format.
  86548. * Example of such files can be found on HDRLib: http://hdrlib.com/
  86549. */
  86550. var HDRCubeTexture = /** @class */ (function (_super) {
  86551. __extends(HDRCubeTexture, _super);
  86552. /**
  86553. * Instantiates an HDRTexture from the following parameters.
  86554. *
  86555. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  86556. * @param scene The scene the texture will be used in
  86557. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  86558. * @param noMipmap Forces to not generate the mipmap if true
  86559. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  86560. * @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)
  86561. * @param reserved Reserved flag for internal use.
  86562. */
  86563. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  86564. if (noMipmap === void 0) { noMipmap = false; }
  86565. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86566. if (gammaSpace === void 0) { gammaSpace = false; }
  86567. if (reserved === void 0) { reserved = false; }
  86568. if (onLoad === void 0) { onLoad = null; }
  86569. if (onError === void 0) { onError = null; }
  86570. var _this = _super.call(this, scene) || this;
  86571. _this._generateHarmonics = true;
  86572. _this._onLoad = null;
  86573. _this._onError = null;
  86574. /**
  86575. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  86576. */
  86577. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  86578. _this._isBlocking = true;
  86579. _this._rotationY = 0;
  86580. /**
  86581. * Gets or sets the center of the bounding box associated with the cube texture
  86582. * It must define where the camera used to render the texture was set
  86583. */
  86584. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  86585. if (!url) {
  86586. return _this;
  86587. }
  86588. _this.name = url;
  86589. _this.url = url;
  86590. _this.hasAlpha = false;
  86591. _this.isCube = true;
  86592. _this._textureMatrix = BABYLON.Matrix.Identity();
  86593. _this._onLoad = onLoad;
  86594. _this._onError = onError;
  86595. _this.gammaSpace = gammaSpace;
  86596. _this._noMipmap = noMipmap;
  86597. _this._size = size;
  86598. _this._texture = _this._getFromCache(url, _this._noMipmap);
  86599. if (!_this._texture) {
  86600. if (!scene.useDelayedTextureLoading) {
  86601. _this.loadTexture();
  86602. }
  86603. else {
  86604. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86605. }
  86606. }
  86607. return _this;
  86608. }
  86609. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  86610. /**
  86611. * Gets wether or not the texture is blocking during loading.
  86612. */
  86613. get: function () {
  86614. return this._isBlocking;
  86615. },
  86616. /**
  86617. * Sets wether or not the texture is blocking during loading.
  86618. */
  86619. set: function (value) {
  86620. this._isBlocking = value;
  86621. },
  86622. enumerable: true,
  86623. configurable: true
  86624. });
  86625. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  86626. /**
  86627. * Gets texture matrix rotation angle around Y axis radians.
  86628. */
  86629. get: function () {
  86630. return this._rotationY;
  86631. },
  86632. /**
  86633. * Sets texture matrix rotation angle around Y axis in radians.
  86634. */
  86635. set: function (value) {
  86636. this._rotationY = value;
  86637. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  86638. },
  86639. enumerable: true,
  86640. configurable: true
  86641. });
  86642. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  86643. get: function () {
  86644. return this._boundingBoxSize;
  86645. },
  86646. /**
  86647. * Gets or sets the size of the bounding box associated with the cube texture
  86648. * When defined, the cubemap will switch to local mode
  86649. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  86650. * @example https://www.babylonjs-playground.com/#RNASML
  86651. */
  86652. set: function (value) {
  86653. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  86654. return;
  86655. }
  86656. this._boundingBoxSize = value;
  86657. var scene = this.getScene();
  86658. if (scene) {
  86659. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  86660. }
  86661. },
  86662. enumerable: true,
  86663. configurable: true
  86664. });
  86665. /**
  86666. * Occurs when the file is raw .hdr file.
  86667. */
  86668. HDRCubeTexture.prototype.loadTexture = function () {
  86669. var _this = this;
  86670. var callback = function (buffer) {
  86671. _this.lodGenerationOffset = 0.0;
  86672. _this.lodGenerationScale = 0.8;
  86673. var scene = _this.getScene();
  86674. if (!scene) {
  86675. return null;
  86676. }
  86677. // Extract the raw linear data.
  86678. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  86679. // Generate harmonics if needed.
  86680. if (_this._generateHarmonics) {
  86681. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  86682. _this.sphericalPolynomial = sphericalPolynomial;
  86683. }
  86684. var results = [];
  86685. var byteArray = null;
  86686. // Push each faces.
  86687. for (var j = 0; j < 6; j++) {
  86688. // Create uintarray fallback.
  86689. if (!scene.getEngine().getCaps().textureFloat) {
  86690. // 3 channels of 1 bytes per pixel in bytes.
  86691. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  86692. byteArray = new Uint8Array(byteBuffer);
  86693. }
  86694. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  86695. // If special cases.
  86696. if (_this.gammaSpace || byteArray) {
  86697. for (var i = 0; i < _this._size * _this._size; i++) {
  86698. // Put in gamma space if requested.
  86699. if (_this.gammaSpace) {
  86700. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  86701. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  86702. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  86703. }
  86704. // Convert to int texture for fallback.
  86705. if (byteArray) {
  86706. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  86707. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  86708. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  86709. // May use luminance instead if the result is not accurate.
  86710. var max = Math.max(Math.max(r, g), b);
  86711. if (max > 255) {
  86712. var scale = 255 / max;
  86713. r *= scale;
  86714. g *= scale;
  86715. b *= scale;
  86716. }
  86717. byteArray[(i * 3) + 0] = r;
  86718. byteArray[(i * 3) + 1] = g;
  86719. byteArray[(i * 3) + 2] = b;
  86720. }
  86721. }
  86722. }
  86723. if (byteArray) {
  86724. results.push(byteArray);
  86725. }
  86726. else {
  86727. results.push(dataFace);
  86728. }
  86729. }
  86730. return results;
  86731. };
  86732. var scene = this.getScene();
  86733. if (scene) {
  86734. 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);
  86735. }
  86736. };
  86737. HDRCubeTexture.prototype.clone = function () {
  86738. var scene = this.getScene();
  86739. if (!scene) {
  86740. return this;
  86741. }
  86742. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  86743. // Base texture
  86744. newTexture.level = this.level;
  86745. newTexture.wrapU = this.wrapU;
  86746. newTexture.wrapV = this.wrapV;
  86747. newTexture.coordinatesIndex = this.coordinatesIndex;
  86748. newTexture.coordinatesMode = this.coordinatesMode;
  86749. return newTexture;
  86750. };
  86751. // Methods
  86752. HDRCubeTexture.prototype.delayLoad = function () {
  86753. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86754. return;
  86755. }
  86756. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86757. this._texture = this._getFromCache(this.url, this._noMipmap);
  86758. if (!this._texture) {
  86759. this.loadTexture();
  86760. }
  86761. };
  86762. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  86763. return this._textureMatrix;
  86764. };
  86765. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  86766. this._textureMatrix = value;
  86767. };
  86768. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  86769. var texture = null;
  86770. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  86771. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  86772. texture.name = parsedTexture.name;
  86773. texture.hasAlpha = parsedTexture.hasAlpha;
  86774. texture.level = parsedTexture.level;
  86775. texture.coordinatesMode = parsedTexture.coordinatesMode;
  86776. texture.isBlocking = parsedTexture.isBlocking;
  86777. }
  86778. if (texture) {
  86779. if (parsedTexture.boundingBoxPosition) {
  86780. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  86781. }
  86782. if (parsedTexture.boundingBoxSize) {
  86783. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  86784. }
  86785. if (parsedTexture.rotationY) {
  86786. texture.rotationY = parsedTexture.rotationY;
  86787. }
  86788. }
  86789. return texture;
  86790. };
  86791. HDRCubeTexture.prototype.serialize = function () {
  86792. if (!this.name) {
  86793. return null;
  86794. }
  86795. var serializationObject = {};
  86796. serializationObject.name = this.name;
  86797. serializationObject.hasAlpha = this.hasAlpha;
  86798. serializationObject.isCube = true;
  86799. serializationObject.level = this.level;
  86800. serializationObject.size = this._size;
  86801. serializationObject.coordinatesMode = this.coordinatesMode;
  86802. serializationObject.useInGammaSpace = this.gammaSpace;
  86803. serializationObject.generateHarmonics = this._generateHarmonics;
  86804. serializationObject.customType = "BABYLON.HDRCubeTexture";
  86805. serializationObject.noMipmap = this._noMipmap;
  86806. serializationObject.isBlocking = this._isBlocking;
  86807. serializationObject.rotationY = this._rotationY;
  86808. return serializationObject;
  86809. };
  86810. HDRCubeTexture._facesMapping = [
  86811. "right",
  86812. "left",
  86813. "up",
  86814. "down",
  86815. "front",
  86816. "back"
  86817. ];
  86818. return HDRCubeTexture;
  86819. }(BABYLON.BaseTexture));
  86820. BABYLON.HDRCubeTexture = HDRCubeTexture;
  86821. })(BABYLON || (BABYLON = {}));
  86822. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  86823. var BABYLON;
  86824. (function (BABYLON) {
  86825. /**
  86826. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  86827. */
  86828. var PanoramaToCubeMapTools = /** @class */ (function () {
  86829. function PanoramaToCubeMapTools() {
  86830. }
  86831. /**
  86832. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  86833. *
  86834. * @param float32Array The source data.
  86835. * @param inputWidth The width of the input panorama.
  86836. * @param inputhHeight The height of the input panorama.
  86837. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  86838. * @return The cubemap data
  86839. */
  86840. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  86841. if (!float32Array) {
  86842. throw "ConvertPanoramaToCubemap: input cannot be null";
  86843. }
  86844. if (float32Array.length != inputWidth * inputHeight * 3) {
  86845. throw "ConvertPanoramaToCubemap: input size is wrong";
  86846. }
  86847. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  86848. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  86849. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  86850. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  86851. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  86852. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  86853. return {
  86854. front: textureFront,
  86855. back: textureBack,
  86856. left: textureLeft,
  86857. right: textureRight,
  86858. up: textureUp,
  86859. down: textureDown,
  86860. size: size,
  86861. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86862. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  86863. gammaSpace: false,
  86864. };
  86865. };
  86866. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  86867. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  86868. var textureArray = new Float32Array(buffer);
  86869. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  86870. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  86871. var dy = 1 / texSize;
  86872. var fy = 0;
  86873. for (var y = 0; y < texSize; y++) {
  86874. var xv1 = faceData[0];
  86875. var xv2 = faceData[2];
  86876. for (var x = 0; x < texSize; x++) {
  86877. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  86878. v.normalize();
  86879. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  86880. // 3 channels per pixels
  86881. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  86882. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  86883. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  86884. xv1 = xv1.add(rotDX1);
  86885. xv2 = xv2.add(rotDX2);
  86886. }
  86887. fy += dy;
  86888. }
  86889. return textureArray;
  86890. };
  86891. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  86892. var theta = Math.atan2(vDir.z, vDir.x);
  86893. var phi = Math.acos(vDir.y);
  86894. while (theta < -Math.PI)
  86895. theta += 2 * Math.PI;
  86896. while (theta > Math.PI)
  86897. theta -= 2 * Math.PI;
  86898. var dx = theta / Math.PI;
  86899. var dy = phi / Math.PI;
  86900. // recenter.
  86901. dx = dx * 0.5 + 0.5;
  86902. var px = Math.round(dx * inputWidth);
  86903. if (px < 0)
  86904. px = 0;
  86905. else if (px >= inputWidth)
  86906. px = inputWidth - 1;
  86907. var py = Math.round(dy * inputHeight);
  86908. if (py < 0)
  86909. py = 0;
  86910. else if (py >= inputHeight)
  86911. py = inputHeight - 1;
  86912. var inputY = (inputHeight - py - 1);
  86913. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  86914. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  86915. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  86916. return {
  86917. r: r,
  86918. g: g,
  86919. b: b
  86920. };
  86921. };
  86922. PanoramaToCubeMapTools.FACE_FRONT = [
  86923. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86924. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86925. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86926. new BABYLON.Vector3(1.0, 1.0, -1.0)
  86927. ];
  86928. PanoramaToCubeMapTools.FACE_BACK = [
  86929. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86930. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86931. new BABYLON.Vector3(1.0, 1.0, 1.0),
  86932. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  86933. ];
  86934. PanoramaToCubeMapTools.FACE_RIGHT = [
  86935. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86936. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86937. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86938. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86939. ];
  86940. PanoramaToCubeMapTools.FACE_LEFT = [
  86941. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86942. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86943. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86944. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  86945. ];
  86946. PanoramaToCubeMapTools.FACE_DOWN = [
  86947. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86948. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86949. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86950. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86951. ];
  86952. PanoramaToCubeMapTools.FACE_UP = [
  86953. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86954. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86955. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86956. new BABYLON.Vector3(1.0, -1.0, -1.0)
  86957. ];
  86958. return PanoramaToCubeMapTools;
  86959. }());
  86960. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  86961. })(BABYLON || (BABYLON = {}));
  86962. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  86963. var BABYLON;
  86964. (function (BABYLON) {
  86965. var IndexedVector2 = /** @class */ (function (_super) {
  86966. __extends(IndexedVector2, _super);
  86967. function IndexedVector2(original, index) {
  86968. var _this = _super.call(this, original.x, original.y) || this;
  86969. _this.index = index;
  86970. return _this;
  86971. }
  86972. return IndexedVector2;
  86973. }(BABYLON.Vector2));
  86974. var PolygonPoints = /** @class */ (function () {
  86975. function PolygonPoints() {
  86976. this.elements = new Array();
  86977. }
  86978. PolygonPoints.prototype.add = function (originalPoints) {
  86979. var _this = this;
  86980. var result = new Array();
  86981. originalPoints.forEach(function (point) {
  86982. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  86983. var newPoint = new IndexedVector2(point, _this.elements.length);
  86984. result.push(newPoint);
  86985. _this.elements.push(newPoint);
  86986. }
  86987. });
  86988. return result;
  86989. };
  86990. PolygonPoints.prototype.computeBounds = function () {
  86991. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86992. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86993. this.elements.forEach(function (point) {
  86994. // x
  86995. if (point.x < lmin.x) {
  86996. lmin.x = point.x;
  86997. }
  86998. else if (point.x > lmax.x) {
  86999. lmax.x = point.x;
  87000. }
  87001. // y
  87002. if (point.y < lmin.y) {
  87003. lmin.y = point.y;
  87004. }
  87005. else if (point.y > lmax.y) {
  87006. lmax.y = point.y;
  87007. }
  87008. });
  87009. return {
  87010. min: lmin,
  87011. max: lmax,
  87012. width: lmax.x - lmin.x,
  87013. height: lmax.y - lmin.y
  87014. };
  87015. };
  87016. return PolygonPoints;
  87017. }());
  87018. var Polygon = /** @class */ (function () {
  87019. function Polygon() {
  87020. }
  87021. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  87022. return [
  87023. new BABYLON.Vector2(xmin, ymin),
  87024. new BABYLON.Vector2(xmax, ymin),
  87025. new BABYLON.Vector2(xmax, ymax),
  87026. new BABYLON.Vector2(xmin, ymax)
  87027. ];
  87028. };
  87029. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  87030. if (cx === void 0) { cx = 0; }
  87031. if (cy === void 0) { cy = 0; }
  87032. if (numberOfSides === void 0) { numberOfSides = 32; }
  87033. var result = new Array();
  87034. var angle = 0;
  87035. var increment = (Math.PI * 2) / numberOfSides;
  87036. for (var i = 0; i < numberOfSides; i++) {
  87037. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  87038. angle -= increment;
  87039. }
  87040. return result;
  87041. };
  87042. Polygon.Parse = function (input) {
  87043. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  87044. var i, result = [];
  87045. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  87046. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  87047. }
  87048. return result;
  87049. };
  87050. Polygon.StartingAt = function (x, y) {
  87051. return BABYLON.Path2.StartingAt(x, y);
  87052. };
  87053. return Polygon;
  87054. }());
  87055. BABYLON.Polygon = Polygon;
  87056. var PolygonMeshBuilder = /** @class */ (function () {
  87057. function PolygonMeshBuilder(name, contours, scene) {
  87058. this._points = new PolygonPoints();
  87059. this._outlinepoints = new PolygonPoints();
  87060. this._holes = new Array();
  87061. this._epoints = new Array();
  87062. this._eholes = new Array();
  87063. this._name = name;
  87064. this._scene = scene;
  87065. var points;
  87066. if (contours instanceof BABYLON.Path2) {
  87067. points = contours.getPoints();
  87068. }
  87069. else {
  87070. points = contours;
  87071. }
  87072. this._addToepoint(points);
  87073. this._points.add(points);
  87074. this._outlinepoints.add(points);
  87075. if (typeof earcut === 'undefined') {
  87076. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  87077. }
  87078. }
  87079. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  87080. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  87081. var p = points_1[_i];
  87082. this._epoints.push(p.x, p.y);
  87083. }
  87084. };
  87085. PolygonMeshBuilder.prototype.addHole = function (hole) {
  87086. this._points.add(hole);
  87087. var holepoints = new PolygonPoints();
  87088. holepoints.add(hole);
  87089. this._holes.push(holepoints);
  87090. this._eholes.push(this._epoints.length / 2);
  87091. this._addToepoint(hole);
  87092. return this;
  87093. };
  87094. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  87095. var _this = this;
  87096. if (updatable === void 0) { updatable = false; }
  87097. if (depth === void 0) { depth = 0; }
  87098. var result = new BABYLON.Mesh(this._name, this._scene);
  87099. var normals = new Array();
  87100. var positions = new Array();
  87101. var uvs = new Array();
  87102. var bounds = this._points.computeBounds();
  87103. this._points.elements.forEach(function (p) {
  87104. normals.push(0, 1.0, 0);
  87105. positions.push(p.x, 0, p.y);
  87106. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  87107. });
  87108. var indices = new Array();
  87109. var res = earcut(this._epoints, this._eholes, 2);
  87110. for (var i = 0; i < res.length; i++) {
  87111. indices.push(res[i]);
  87112. }
  87113. if (depth > 0) {
  87114. var positionscount = (positions.length / 3); //get the current pointcount
  87115. this._points.elements.forEach(function (p) {
  87116. normals.push(0, -1.0, 0);
  87117. positions.push(p.x, -depth, p.y);
  87118. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  87119. });
  87120. var totalCount = indices.length;
  87121. for (var i = 0; i < totalCount; i += 3) {
  87122. var i0 = indices[i + 0];
  87123. var i1 = indices[i + 1];
  87124. var i2 = indices[i + 2];
  87125. indices.push(i2 + positionscount);
  87126. indices.push(i1 + positionscount);
  87127. indices.push(i0 + positionscount);
  87128. }
  87129. //Add the sides
  87130. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  87131. this._holes.forEach(function (hole) {
  87132. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  87133. });
  87134. }
  87135. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  87136. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  87137. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  87138. result.setIndices(indices);
  87139. return result;
  87140. };
  87141. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  87142. var StartIndex = positions.length / 3;
  87143. var ulength = 0;
  87144. for (var i = 0; i < points.elements.length; i++) {
  87145. var p = points.elements[i];
  87146. var p1;
  87147. if ((i + 1) > points.elements.length - 1) {
  87148. p1 = points.elements[0];
  87149. }
  87150. else {
  87151. p1 = points.elements[i + 1];
  87152. }
  87153. positions.push(p.x, 0, p.y);
  87154. positions.push(p.x, -depth, p.y);
  87155. positions.push(p1.x, 0, p1.y);
  87156. positions.push(p1.x, -depth, p1.y);
  87157. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  87158. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  87159. var v3 = v2.subtract(v1);
  87160. var v4 = new BABYLON.Vector3(0, 1, 0);
  87161. var vn = BABYLON.Vector3.Cross(v3, v4);
  87162. vn = vn.normalize();
  87163. uvs.push(ulength / bounds.width, 0);
  87164. uvs.push(ulength / bounds.width, 1);
  87165. ulength += v3.length();
  87166. uvs.push((ulength / bounds.width), 0);
  87167. uvs.push((ulength / bounds.width), 1);
  87168. if (!flip) {
  87169. normals.push(-vn.x, -vn.y, -vn.z);
  87170. normals.push(-vn.x, -vn.y, -vn.z);
  87171. normals.push(-vn.x, -vn.y, -vn.z);
  87172. normals.push(-vn.x, -vn.y, -vn.z);
  87173. indices.push(StartIndex);
  87174. indices.push(StartIndex + 1);
  87175. indices.push(StartIndex + 2);
  87176. indices.push(StartIndex + 1);
  87177. indices.push(StartIndex + 3);
  87178. indices.push(StartIndex + 2);
  87179. }
  87180. else {
  87181. normals.push(vn.x, vn.y, vn.z);
  87182. normals.push(vn.x, vn.y, vn.z);
  87183. normals.push(vn.x, vn.y, vn.z);
  87184. normals.push(vn.x, vn.y, vn.z);
  87185. indices.push(StartIndex);
  87186. indices.push(StartIndex + 2);
  87187. indices.push(StartIndex + 1);
  87188. indices.push(StartIndex + 1);
  87189. indices.push(StartIndex + 2);
  87190. indices.push(StartIndex + 3);
  87191. }
  87192. StartIndex += 4;
  87193. }
  87194. ;
  87195. };
  87196. return PolygonMeshBuilder;
  87197. }());
  87198. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  87199. })(BABYLON || (BABYLON = {}));
  87200. //# sourceMappingURL=babylon.polygonMesh.js.map
  87201. var BABYLON;
  87202. (function (BABYLON) {
  87203. // Unique ID when we import meshes from Babylon to CSG
  87204. var currentCSGMeshId = 0;
  87205. // # class Vertex
  87206. // Represents a vertex of a polygon. Use your own vertex class instead of this
  87207. // one to provide additional features like texture coordinates and vertex
  87208. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  87209. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  87210. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  87211. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  87212. // is not used anywhere else.
  87213. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  87214. var Vertex = /** @class */ (function () {
  87215. function Vertex(pos, normal, uv) {
  87216. this.pos = pos;
  87217. this.normal = normal;
  87218. this.uv = uv;
  87219. }
  87220. Vertex.prototype.clone = function () {
  87221. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  87222. };
  87223. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  87224. // orientation of a polygon is flipped.
  87225. Vertex.prototype.flip = function () {
  87226. this.normal = this.normal.scale(-1);
  87227. };
  87228. // Create a new vertex between this vertex and `other` by linearly
  87229. // interpolating all properties using a parameter of `t`. Subclasses should
  87230. // override this to interpolate additional properties.
  87231. Vertex.prototype.interpolate = function (other, t) {
  87232. 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));
  87233. };
  87234. return Vertex;
  87235. }());
  87236. // # class Plane
  87237. // Represents a plane in 3D space.
  87238. var Plane = /** @class */ (function () {
  87239. function Plane(normal, w) {
  87240. this.normal = normal;
  87241. this.w = w;
  87242. }
  87243. Plane.FromPoints = function (a, b, c) {
  87244. var v0 = c.subtract(a);
  87245. var v1 = b.subtract(a);
  87246. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  87247. return null;
  87248. }
  87249. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  87250. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  87251. };
  87252. Plane.prototype.clone = function () {
  87253. return new Plane(this.normal.clone(), this.w);
  87254. };
  87255. Plane.prototype.flip = function () {
  87256. this.normal.scaleInPlace(-1);
  87257. this.w = -this.w;
  87258. };
  87259. // Split `polygon` by this plane if needed, then put the polygon or polygon
  87260. // fragments in the appropriate lists. Coplanar polygons go into either
  87261. // `coplanarFront` or `coplanarBack` depending on their orientation with
  87262. // respect to this plane. Polygons in front or in back of this plane go into
  87263. // either `front` or `back`.
  87264. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  87265. var COPLANAR = 0;
  87266. var FRONT = 1;
  87267. var BACK = 2;
  87268. var SPANNING = 3;
  87269. // Classify each point as well as the entire polygon into one of the above
  87270. // four classes.
  87271. var polygonType = 0;
  87272. var types = [];
  87273. var i;
  87274. var t;
  87275. for (i = 0; i < polygon.vertices.length; i++) {
  87276. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  87277. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  87278. polygonType |= type;
  87279. types.push(type);
  87280. }
  87281. // Put the polygon in the correct list, splitting it when necessary.
  87282. switch (polygonType) {
  87283. case COPLANAR:
  87284. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  87285. break;
  87286. case FRONT:
  87287. front.push(polygon);
  87288. break;
  87289. case BACK:
  87290. back.push(polygon);
  87291. break;
  87292. case SPANNING:
  87293. var f = [], b = [];
  87294. for (i = 0; i < polygon.vertices.length; i++) {
  87295. var j = (i + 1) % polygon.vertices.length;
  87296. var ti = types[i], tj = types[j];
  87297. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  87298. if (ti !== BACK)
  87299. f.push(vi);
  87300. if (ti !== FRONT)
  87301. b.push(ti !== BACK ? vi.clone() : vi);
  87302. if ((ti | tj) === SPANNING) {
  87303. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  87304. var v = vi.interpolate(vj, t);
  87305. f.push(v);
  87306. b.push(v.clone());
  87307. }
  87308. }
  87309. var poly;
  87310. if (f.length >= 3) {
  87311. poly = new Polygon(f, polygon.shared);
  87312. if (poly.plane)
  87313. front.push(poly);
  87314. }
  87315. if (b.length >= 3) {
  87316. poly = new Polygon(b, polygon.shared);
  87317. if (poly.plane)
  87318. back.push(poly);
  87319. }
  87320. break;
  87321. }
  87322. };
  87323. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  87324. // point is on the plane.
  87325. Plane.EPSILON = 1e-5;
  87326. return Plane;
  87327. }());
  87328. // # class Polygon
  87329. // Represents a convex polygon. The vertices used to initialize a polygon must
  87330. // be coplanar and form a convex loop.
  87331. //
  87332. // Each convex polygon has a `shared` property, which is shared between all
  87333. // polygons that are clones of each other or were split from the same polygon.
  87334. // This can be used to define per-polygon properties (such as surface color).
  87335. var Polygon = /** @class */ (function () {
  87336. function Polygon(vertices, shared) {
  87337. this.vertices = vertices;
  87338. this.shared = shared;
  87339. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  87340. }
  87341. Polygon.prototype.clone = function () {
  87342. var vertices = this.vertices.map(function (v) { return v.clone(); });
  87343. return new Polygon(vertices, this.shared);
  87344. };
  87345. Polygon.prototype.flip = function () {
  87346. this.vertices.reverse().map(function (v) { v.flip(); });
  87347. this.plane.flip();
  87348. };
  87349. return Polygon;
  87350. }());
  87351. // # class Node
  87352. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  87353. // by picking a polygon to split along. That polygon (and all other coplanar
  87354. // polygons) are added directly to that node and the other polygons are added to
  87355. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  87356. // no distinction between internal and leaf nodes.
  87357. var Node = /** @class */ (function () {
  87358. function Node(polygons) {
  87359. this.plane = null;
  87360. this.front = null;
  87361. this.back = null;
  87362. this.polygons = new Array();
  87363. if (polygons) {
  87364. this.build(polygons);
  87365. }
  87366. }
  87367. Node.prototype.clone = function () {
  87368. var node = new Node();
  87369. node.plane = this.plane && this.plane.clone();
  87370. node.front = this.front && this.front.clone();
  87371. node.back = this.back && this.back.clone();
  87372. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  87373. return node;
  87374. };
  87375. // Convert solid space to empty space and empty space to solid space.
  87376. Node.prototype.invert = function () {
  87377. for (var i = 0; i < this.polygons.length; i++) {
  87378. this.polygons[i].flip();
  87379. }
  87380. if (this.plane) {
  87381. this.plane.flip();
  87382. }
  87383. if (this.front) {
  87384. this.front.invert();
  87385. }
  87386. if (this.back) {
  87387. this.back.invert();
  87388. }
  87389. var temp = this.front;
  87390. this.front = this.back;
  87391. this.back = temp;
  87392. };
  87393. // Recursively remove all polygons in `polygons` that are inside this BSP
  87394. // tree.
  87395. Node.prototype.clipPolygons = function (polygons) {
  87396. if (!this.plane)
  87397. return polygons.slice();
  87398. var front = new Array(), back = new Array();
  87399. for (var i = 0; i < polygons.length; i++) {
  87400. this.plane.splitPolygon(polygons[i], front, back, front, back);
  87401. }
  87402. if (this.front) {
  87403. front = this.front.clipPolygons(front);
  87404. }
  87405. if (this.back) {
  87406. back = this.back.clipPolygons(back);
  87407. }
  87408. else {
  87409. back = [];
  87410. }
  87411. return front.concat(back);
  87412. };
  87413. // Remove all polygons in this BSP tree that are inside the other BSP tree
  87414. // `bsp`.
  87415. Node.prototype.clipTo = function (bsp) {
  87416. this.polygons = bsp.clipPolygons(this.polygons);
  87417. if (this.front)
  87418. this.front.clipTo(bsp);
  87419. if (this.back)
  87420. this.back.clipTo(bsp);
  87421. };
  87422. // Return a list of all polygons in this BSP tree.
  87423. Node.prototype.allPolygons = function () {
  87424. var polygons = this.polygons.slice();
  87425. if (this.front)
  87426. polygons = polygons.concat(this.front.allPolygons());
  87427. if (this.back)
  87428. polygons = polygons.concat(this.back.allPolygons());
  87429. return polygons;
  87430. };
  87431. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  87432. // new polygons are filtered down to the bottom of the tree and become new
  87433. // nodes there. Each set of polygons is partitioned using the first polygon
  87434. // (no heuristic is used to pick a good split).
  87435. Node.prototype.build = function (polygons) {
  87436. if (!polygons.length)
  87437. return;
  87438. if (!this.plane)
  87439. this.plane = polygons[0].plane.clone();
  87440. var front = new Array(), back = new Array();
  87441. for (var i = 0; i < polygons.length; i++) {
  87442. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  87443. }
  87444. if (front.length) {
  87445. if (!this.front)
  87446. this.front = new Node();
  87447. this.front.build(front);
  87448. }
  87449. if (back.length) {
  87450. if (!this.back)
  87451. this.back = new Node();
  87452. this.back.build(back);
  87453. }
  87454. };
  87455. return Node;
  87456. }());
  87457. var CSG = /** @class */ (function () {
  87458. function CSG() {
  87459. this.polygons = new Array();
  87460. }
  87461. // Convert BABYLON.Mesh to BABYLON.CSG
  87462. CSG.FromMesh = function (mesh) {
  87463. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  87464. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  87465. if (mesh instanceof BABYLON.Mesh) {
  87466. mesh.computeWorldMatrix(true);
  87467. matrix = mesh.getWorldMatrix();
  87468. meshPosition = mesh.position.clone();
  87469. meshRotation = mesh.rotation.clone();
  87470. if (mesh.rotationQuaternion) {
  87471. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  87472. }
  87473. meshScaling = mesh.scaling.clone();
  87474. }
  87475. else {
  87476. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  87477. }
  87478. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87479. var subMeshes = mesh.subMeshes;
  87480. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  87481. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  87482. vertices = [];
  87483. for (var j = 0; j < 3; j++) {
  87484. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  87485. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  87486. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  87487. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  87488. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  87489. vertex = new Vertex(position, normal, uv);
  87490. vertices.push(vertex);
  87491. }
  87492. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  87493. // To handle the case of degenerated triangle
  87494. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  87495. if (polygon.plane)
  87496. polygons.push(polygon);
  87497. }
  87498. }
  87499. var csg = CSG.FromPolygons(polygons);
  87500. csg.matrix = matrix;
  87501. csg.position = meshPosition;
  87502. csg.rotation = meshRotation;
  87503. csg.scaling = meshScaling;
  87504. csg.rotationQuaternion = meshRotationQuaternion;
  87505. currentCSGMeshId++;
  87506. return csg;
  87507. };
  87508. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  87509. CSG.FromPolygons = function (polygons) {
  87510. var csg = new CSG();
  87511. csg.polygons = polygons;
  87512. return csg;
  87513. };
  87514. CSG.prototype.clone = function () {
  87515. var csg = new CSG();
  87516. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  87517. csg.copyTransformAttributes(this);
  87518. return csg;
  87519. };
  87520. CSG.prototype.union = function (csg) {
  87521. var a = new Node(this.clone().polygons);
  87522. var b = new Node(csg.clone().polygons);
  87523. a.clipTo(b);
  87524. b.clipTo(a);
  87525. b.invert();
  87526. b.clipTo(a);
  87527. b.invert();
  87528. a.build(b.allPolygons());
  87529. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87530. };
  87531. CSG.prototype.unionInPlace = function (csg) {
  87532. var a = new Node(this.polygons);
  87533. var b = new Node(csg.polygons);
  87534. a.clipTo(b);
  87535. b.clipTo(a);
  87536. b.invert();
  87537. b.clipTo(a);
  87538. b.invert();
  87539. a.build(b.allPolygons());
  87540. this.polygons = a.allPolygons();
  87541. };
  87542. CSG.prototype.subtract = function (csg) {
  87543. var a = new Node(this.clone().polygons);
  87544. var b = new Node(csg.clone().polygons);
  87545. a.invert();
  87546. a.clipTo(b);
  87547. b.clipTo(a);
  87548. b.invert();
  87549. b.clipTo(a);
  87550. b.invert();
  87551. a.build(b.allPolygons());
  87552. a.invert();
  87553. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87554. };
  87555. CSG.prototype.subtractInPlace = function (csg) {
  87556. var a = new Node(this.polygons);
  87557. var b = new Node(csg.polygons);
  87558. a.invert();
  87559. a.clipTo(b);
  87560. b.clipTo(a);
  87561. b.invert();
  87562. b.clipTo(a);
  87563. b.invert();
  87564. a.build(b.allPolygons());
  87565. a.invert();
  87566. this.polygons = a.allPolygons();
  87567. };
  87568. CSG.prototype.intersect = function (csg) {
  87569. var a = new Node(this.clone().polygons);
  87570. var b = new Node(csg.clone().polygons);
  87571. a.invert();
  87572. b.clipTo(a);
  87573. b.invert();
  87574. a.clipTo(b);
  87575. b.clipTo(a);
  87576. a.build(b.allPolygons());
  87577. a.invert();
  87578. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87579. };
  87580. CSG.prototype.intersectInPlace = function (csg) {
  87581. var a = new Node(this.polygons);
  87582. var b = new Node(csg.polygons);
  87583. a.invert();
  87584. b.clipTo(a);
  87585. b.invert();
  87586. a.clipTo(b);
  87587. b.clipTo(a);
  87588. a.build(b.allPolygons());
  87589. a.invert();
  87590. this.polygons = a.allPolygons();
  87591. };
  87592. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  87593. // not modified.
  87594. CSG.prototype.inverse = function () {
  87595. var csg = this.clone();
  87596. csg.inverseInPlace();
  87597. return csg;
  87598. };
  87599. CSG.prototype.inverseInPlace = function () {
  87600. this.polygons.map(function (p) { p.flip(); });
  87601. };
  87602. // This is used to keep meshes transformations so they can be restored
  87603. // when we build back a Babylon Mesh
  87604. // NB : All CSG operations are performed in world coordinates
  87605. CSG.prototype.copyTransformAttributes = function (csg) {
  87606. this.matrix = csg.matrix;
  87607. this.position = csg.position;
  87608. this.rotation = csg.rotation;
  87609. this.scaling = csg.scaling;
  87610. this.rotationQuaternion = csg.rotationQuaternion;
  87611. return this;
  87612. };
  87613. // Build Raw mesh from CSG
  87614. // Coordinates here are in world space
  87615. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  87616. var matrix = this.matrix.clone();
  87617. matrix.invert();
  87618. 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;
  87619. if (keepSubMeshes) {
  87620. // Sort Polygons, since subMeshes are indices range
  87621. polygons.sort(function (a, b) {
  87622. if (a.shared.meshId === b.shared.meshId) {
  87623. return a.shared.subMeshId - b.shared.subMeshId;
  87624. }
  87625. else {
  87626. return a.shared.meshId - b.shared.meshId;
  87627. }
  87628. });
  87629. }
  87630. for (var i = 0, il = polygons.length; i < il; i++) {
  87631. polygon = polygons[i];
  87632. // Building SubMeshes
  87633. if (!subMesh_dict[polygon.shared.meshId]) {
  87634. subMesh_dict[polygon.shared.meshId] = {};
  87635. }
  87636. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  87637. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  87638. indexStart: +Infinity,
  87639. indexEnd: -Infinity,
  87640. materialIndex: polygon.shared.materialIndex
  87641. };
  87642. }
  87643. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  87644. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  87645. polygonIndices[0] = 0;
  87646. polygonIndices[1] = j - 1;
  87647. polygonIndices[2] = j;
  87648. for (var k = 0; k < 3; k++) {
  87649. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  87650. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  87651. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  87652. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  87653. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  87654. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  87655. // Check if 2 points can be merged
  87656. if (!(typeof vertex_idx !== 'undefined' &&
  87657. normals[vertex_idx * 3] === localNormal.x &&
  87658. normals[vertex_idx * 3 + 1] === localNormal.y &&
  87659. normals[vertex_idx * 3 + 2] === localNormal.z &&
  87660. uvs[vertex_idx * 2] === uv.x &&
  87661. uvs[vertex_idx * 2 + 1] === uv.y)) {
  87662. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  87663. uvs.push(uv.x, uv.y);
  87664. normals.push(normal.x, normal.y, normal.z);
  87665. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  87666. }
  87667. indices.push(vertex_idx);
  87668. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  87669. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  87670. currentIndex++;
  87671. }
  87672. }
  87673. }
  87674. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  87675. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  87676. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  87677. mesh.setIndices(indices, null);
  87678. if (keepSubMeshes) {
  87679. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  87680. var materialIndexOffset = 0, materialMaxIndex;
  87681. mesh.subMeshes = new Array();
  87682. for (var m in subMesh_dict) {
  87683. materialMaxIndex = -1;
  87684. for (var sm in subMesh_dict[m]) {
  87685. subMesh_obj = subMesh_dict[m][sm];
  87686. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  87687. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  87688. }
  87689. materialIndexOffset += ++materialMaxIndex;
  87690. }
  87691. }
  87692. return mesh;
  87693. };
  87694. // Build Mesh from CSG taking material and transforms into account
  87695. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  87696. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  87697. mesh.material = material;
  87698. mesh.position.copyFrom(this.position);
  87699. mesh.rotation.copyFrom(this.rotation);
  87700. if (this.rotationQuaternion) {
  87701. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  87702. }
  87703. mesh.scaling.copyFrom(this.scaling);
  87704. mesh.computeWorldMatrix(true);
  87705. return mesh;
  87706. };
  87707. return CSG;
  87708. }());
  87709. BABYLON.CSG = CSG;
  87710. })(BABYLON || (BABYLON = {}));
  87711. //# sourceMappingURL=babylon.csg.js.map
  87712. var BABYLON;
  87713. (function (BABYLON) {
  87714. var LensFlare = /** @class */ (function () {
  87715. function LensFlare(size, position, color, imgUrl, system) {
  87716. this.size = size;
  87717. this.position = position;
  87718. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87719. this.color = color || new BABYLON.Color3(1, 1, 1);
  87720. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  87721. this._system = system;
  87722. system.lensFlares.push(this);
  87723. }
  87724. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  87725. return new LensFlare(size, position, color, imgUrl, system);
  87726. };
  87727. LensFlare.prototype.dispose = function () {
  87728. if (this.texture) {
  87729. this.texture.dispose();
  87730. }
  87731. // Remove from scene
  87732. var index = this._system.lensFlares.indexOf(this);
  87733. this._system.lensFlares.splice(index, 1);
  87734. };
  87735. ;
  87736. return LensFlare;
  87737. }());
  87738. BABYLON.LensFlare = LensFlare;
  87739. })(BABYLON || (BABYLON = {}));
  87740. //# sourceMappingURL=babylon.lensFlare.js.map
  87741. var BABYLON;
  87742. (function (BABYLON) {
  87743. // Adds the parser to the scene parsers.
  87744. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  87745. // Lens flares
  87746. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  87747. if (!container.lensFlareSystems) {
  87748. container.lensFlareSystems = new Array();
  87749. }
  87750. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  87751. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  87752. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  87753. container.lensFlareSystems.push(lf);
  87754. }
  87755. }
  87756. });
  87757. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  87758. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87759. if (this.lensFlareSystems[index].name === name) {
  87760. return this.lensFlareSystems[index];
  87761. }
  87762. }
  87763. return null;
  87764. };
  87765. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  87766. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87767. if (this.lensFlareSystems[index].id === id) {
  87768. return this.lensFlareSystems[index];
  87769. }
  87770. }
  87771. return null;
  87772. };
  87773. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  87774. var index = this.lensFlareSystems.indexOf(toRemove);
  87775. if (index !== -1) {
  87776. this.lensFlareSystems.splice(index, 1);
  87777. }
  87778. return index;
  87779. };
  87780. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  87781. this.lensFlareSystems.push(newLensFlareSystem);
  87782. };
  87783. /**
  87784. * Defines the lens flare scene component responsible to manage any lens flares
  87785. * in a given scene.
  87786. */
  87787. var LensFlareSystemSceneComponent = /** @class */ (function () {
  87788. /**
  87789. * Creates a new instance of the component for the given scene
  87790. * @param scene Defines the scene to register the component in
  87791. */
  87792. function LensFlareSystemSceneComponent(scene) {
  87793. /**
  87794. * The component name helpfull to identify the component in the list of scene components.
  87795. */
  87796. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  87797. this.scene = scene;
  87798. scene.lensFlareSystems = new Array();
  87799. }
  87800. /**
  87801. * Registers the component in a given scene
  87802. */
  87803. LensFlareSystemSceneComponent.prototype.register = function () {
  87804. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  87805. };
  87806. /**
  87807. * Rebuilds the elements related to this component in case of
  87808. * context lost for instance.
  87809. */
  87810. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  87811. // Nothing to do for lens flare
  87812. };
  87813. /**
  87814. * Adds all the element from the container to the scene
  87815. * @param container the container holding the elements
  87816. */
  87817. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  87818. var _this = this;
  87819. if (!container.lensFlareSystems) {
  87820. return;
  87821. }
  87822. container.lensFlareSystems.forEach(function (o) {
  87823. _this.scene.addLensFlareSystem(o);
  87824. });
  87825. };
  87826. /**
  87827. * Removes all the elements in the container from the scene
  87828. * @param container contains the elements to remove
  87829. */
  87830. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  87831. var _this = this;
  87832. if (!container.lensFlareSystems) {
  87833. return;
  87834. }
  87835. container.lensFlareSystems.forEach(function (o) {
  87836. _this.scene.removeLensFlareSystem(o);
  87837. });
  87838. };
  87839. /**
  87840. * Serializes the component data to the specified json object
  87841. * @param serializationObject The object to serialize to
  87842. */
  87843. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  87844. // Lens flares
  87845. serializationObject.lensFlareSystems = [];
  87846. var lensFlareSystems = this.scene.lensFlareSystems;
  87847. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  87848. var lensFlareSystem = lensFlareSystems_1[_i];
  87849. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  87850. }
  87851. };
  87852. /**
  87853. * Disposes the component and the associated ressources.
  87854. */
  87855. LensFlareSystemSceneComponent.prototype.dispose = function () {
  87856. var lensFlareSystems = this.scene.lensFlareSystems;
  87857. while (lensFlareSystems.length) {
  87858. lensFlareSystems[0].dispose();
  87859. }
  87860. };
  87861. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  87862. // Lens flares
  87863. if (this.scene.lensFlaresEnabled) {
  87864. var lensFlareSystems = this.scene.lensFlareSystems;
  87865. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87866. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  87867. var lensFlareSystem = lensFlareSystems_2[_i];
  87868. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  87869. lensFlareSystem.render();
  87870. }
  87871. }
  87872. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87873. }
  87874. };
  87875. return LensFlareSystemSceneComponent;
  87876. }());
  87877. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  87878. })(BABYLON || (BABYLON = {}));
  87879. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  87880. var BABYLON;
  87881. (function (BABYLON) {
  87882. var LensFlareSystem = /** @class */ (function () {
  87883. function LensFlareSystem(name, emitter, scene) {
  87884. this.name = name;
  87885. this.lensFlares = new Array();
  87886. this.borderLimit = 300;
  87887. this.viewportBorder = 0;
  87888. this.layerMask = 0x0FFFFFFF;
  87889. this._vertexBuffers = {};
  87890. this._isEnabled = true;
  87891. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87892. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  87893. if (!component) {
  87894. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  87895. scene._addComponent(component);
  87896. }
  87897. this._emitter = emitter;
  87898. this.id = name;
  87899. scene.lensFlareSystems.push(this);
  87900. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  87901. var engine = scene.getEngine();
  87902. // VBO
  87903. var vertices = [];
  87904. vertices.push(1, 1);
  87905. vertices.push(-1, 1);
  87906. vertices.push(-1, -1);
  87907. vertices.push(1, -1);
  87908. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87909. // Indices
  87910. var indices = [];
  87911. indices.push(0);
  87912. indices.push(1);
  87913. indices.push(2);
  87914. indices.push(0);
  87915. indices.push(2);
  87916. indices.push(3);
  87917. this._indexBuffer = engine.createIndexBuffer(indices);
  87918. // Effects
  87919. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  87920. }
  87921. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  87922. get: function () {
  87923. return this._isEnabled;
  87924. },
  87925. set: function (value) {
  87926. this._isEnabled = value;
  87927. },
  87928. enumerable: true,
  87929. configurable: true
  87930. });
  87931. LensFlareSystem.prototype.getScene = function () {
  87932. return this._scene;
  87933. };
  87934. LensFlareSystem.prototype.getEmitter = function () {
  87935. return this._emitter;
  87936. };
  87937. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  87938. this._emitter = newEmitter;
  87939. };
  87940. LensFlareSystem.prototype.getEmitterPosition = function () {
  87941. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  87942. };
  87943. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  87944. var position = this.getEmitterPosition();
  87945. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  87946. this._positionX = position.x;
  87947. this._positionY = position.y;
  87948. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  87949. if (this.viewportBorder > 0) {
  87950. globalViewport.x -= this.viewportBorder;
  87951. globalViewport.y -= this.viewportBorder;
  87952. globalViewport.width += this.viewportBorder * 2;
  87953. globalViewport.height += this.viewportBorder * 2;
  87954. position.x += this.viewportBorder;
  87955. position.y += this.viewportBorder;
  87956. this._positionX += this.viewportBorder;
  87957. this._positionY += this.viewportBorder;
  87958. }
  87959. if (position.z > 0) {
  87960. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  87961. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  87962. return true;
  87963. }
  87964. return true;
  87965. }
  87966. return false;
  87967. };
  87968. /** @hidden */
  87969. LensFlareSystem.prototype._isVisible = function () {
  87970. if (!this._isEnabled || !this._scene.activeCamera) {
  87971. return false;
  87972. }
  87973. var emitterPosition = this.getEmitterPosition();
  87974. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  87975. var distance = direction.length();
  87976. direction.normalize();
  87977. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  87978. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  87979. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  87980. };
  87981. LensFlareSystem.prototype.render = function () {
  87982. if (!this._effect.isReady() || !this._scene.activeCamera)
  87983. return false;
  87984. var engine = this._scene.getEngine();
  87985. var viewport = this._scene.activeCamera.viewport;
  87986. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  87987. // Position
  87988. if (!this.computeEffectivePosition(globalViewport)) {
  87989. return false;
  87990. }
  87991. // Visibility
  87992. if (!this._isVisible()) {
  87993. return false;
  87994. }
  87995. // Intensity
  87996. var awayX;
  87997. var awayY;
  87998. if (this._positionX < this.borderLimit + globalViewport.x) {
  87999. awayX = this.borderLimit + globalViewport.x - this._positionX;
  88000. }
  88001. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  88002. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  88003. }
  88004. else {
  88005. awayX = 0;
  88006. }
  88007. if (this._positionY < this.borderLimit + globalViewport.y) {
  88008. awayY = this.borderLimit + globalViewport.y - this._positionY;
  88009. }
  88010. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  88011. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  88012. }
  88013. else {
  88014. awayY = 0;
  88015. }
  88016. var away = (awayX > awayY) ? awayX : awayY;
  88017. away -= this.viewportBorder;
  88018. if (away > this.borderLimit) {
  88019. away = this.borderLimit;
  88020. }
  88021. var intensity = 1.0 - (away / this.borderLimit);
  88022. if (intensity < 0) {
  88023. return false;
  88024. }
  88025. if (intensity > 1.0) {
  88026. intensity = 1.0;
  88027. }
  88028. if (this.viewportBorder > 0) {
  88029. globalViewport.x += this.viewportBorder;
  88030. globalViewport.y += this.viewportBorder;
  88031. globalViewport.width -= this.viewportBorder * 2;
  88032. globalViewport.height -= this.viewportBorder * 2;
  88033. this._positionX -= this.viewportBorder;
  88034. this._positionY -= this.viewportBorder;
  88035. }
  88036. // Position
  88037. var centerX = globalViewport.x + globalViewport.width / 2;
  88038. var centerY = globalViewport.y + globalViewport.height / 2;
  88039. var distX = centerX - this._positionX;
  88040. var distY = centerY - this._positionY;
  88041. // Effects
  88042. engine.enableEffect(this._effect);
  88043. engine.setState(false);
  88044. engine.setDepthBuffer(false);
  88045. // VBOs
  88046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  88047. // Flares
  88048. for (var index = 0; index < this.lensFlares.length; index++) {
  88049. var flare = this.lensFlares[index];
  88050. engine.setAlphaMode(flare.alphaMode);
  88051. var x = centerX - (distX * flare.position);
  88052. var y = centerY - (distY * flare.position);
  88053. var cw = flare.size;
  88054. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  88055. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  88056. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  88057. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  88058. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  88059. // Texture
  88060. this._effect.setTexture("textureSampler", flare.texture);
  88061. // Color
  88062. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  88063. // Draw order
  88064. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88065. }
  88066. engine.setDepthBuffer(true);
  88067. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88068. return true;
  88069. };
  88070. LensFlareSystem.prototype.dispose = function () {
  88071. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88072. if (vertexBuffer) {
  88073. vertexBuffer.dispose();
  88074. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88075. }
  88076. if (this._indexBuffer) {
  88077. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88078. this._indexBuffer = null;
  88079. }
  88080. while (this.lensFlares.length) {
  88081. this.lensFlares[0].dispose();
  88082. }
  88083. // Remove from scene
  88084. var index = this._scene.lensFlareSystems.indexOf(this);
  88085. this._scene.lensFlareSystems.splice(index, 1);
  88086. };
  88087. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  88088. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  88089. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  88090. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  88091. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  88092. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  88093. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  88094. var parsedFlare = parsedLensFlareSystem.flares[index];
  88095. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  88096. }
  88097. return lensFlareSystem;
  88098. };
  88099. LensFlareSystem.prototype.serialize = function () {
  88100. var serializationObject = {};
  88101. serializationObject.id = this.id;
  88102. serializationObject.name = this.name;
  88103. serializationObject.emitterId = this.getEmitter().id;
  88104. serializationObject.borderLimit = this.borderLimit;
  88105. serializationObject.flares = [];
  88106. for (var index = 0; index < this.lensFlares.length; index++) {
  88107. var flare = this.lensFlares[index];
  88108. serializationObject.flares.push({
  88109. size: flare.size,
  88110. position: flare.position,
  88111. color: flare.color.asArray(),
  88112. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  88113. });
  88114. }
  88115. return serializationObject;
  88116. };
  88117. return LensFlareSystem;
  88118. }());
  88119. BABYLON.LensFlareSystem = LensFlareSystem;
  88120. })(BABYLON || (BABYLON = {}));
  88121. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  88122. var BABYLON;
  88123. (function (BABYLON) {
  88124. /**
  88125. * This is a holder class for the physics joint created by the physics plugin.
  88126. * It holds a set of functions to control the underlying joint.
  88127. */
  88128. var PhysicsJoint = /** @class */ (function () {
  88129. function PhysicsJoint(type, jointData) {
  88130. this.type = type;
  88131. this.jointData = jointData;
  88132. jointData.nativeParams = jointData.nativeParams || {};
  88133. }
  88134. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  88135. get: function () {
  88136. return this._physicsJoint;
  88137. },
  88138. set: function (newJoint) {
  88139. if (this._physicsJoint) {
  88140. //remove from the wolrd
  88141. }
  88142. this._physicsJoint = newJoint;
  88143. },
  88144. enumerable: true,
  88145. configurable: true
  88146. });
  88147. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  88148. set: function (physicsPlugin) {
  88149. this._physicsPlugin = physicsPlugin;
  88150. },
  88151. enumerable: true,
  88152. configurable: true
  88153. });
  88154. /**
  88155. * Execute a function that is physics-plugin specific.
  88156. * @param {Function} func the function that will be executed.
  88157. * It accepts two parameters: the physics world and the physics joint.
  88158. */
  88159. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  88160. func(this._physicsPlugin.world, this._physicsJoint);
  88161. };
  88162. //TODO check if the native joints are the same
  88163. //Joint Types
  88164. PhysicsJoint.DistanceJoint = 0;
  88165. PhysicsJoint.HingeJoint = 1;
  88166. PhysicsJoint.BallAndSocketJoint = 2;
  88167. PhysicsJoint.WheelJoint = 3;
  88168. PhysicsJoint.SliderJoint = 4;
  88169. //OIMO
  88170. PhysicsJoint.PrismaticJoint = 5;
  88171. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  88172. PhysicsJoint.UniversalJoint = 6;
  88173. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  88174. //Cannon
  88175. //Similar to a Ball-Joint. Different in params
  88176. PhysicsJoint.PointToPointJoint = 8;
  88177. //Cannon only at the moment
  88178. PhysicsJoint.SpringJoint = 9;
  88179. PhysicsJoint.LockJoint = 10;
  88180. return PhysicsJoint;
  88181. }());
  88182. BABYLON.PhysicsJoint = PhysicsJoint;
  88183. /**
  88184. * A class representing a physics distance joint.
  88185. */
  88186. var DistanceJoint = /** @class */ (function (_super) {
  88187. __extends(DistanceJoint, _super);
  88188. function DistanceJoint(jointData) {
  88189. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  88190. }
  88191. /**
  88192. * Update the predefined distance.
  88193. */
  88194. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  88195. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  88196. };
  88197. return DistanceJoint;
  88198. }(PhysicsJoint));
  88199. BABYLON.DistanceJoint = DistanceJoint;
  88200. var MotorEnabledJoint = /** @class */ (function (_super) {
  88201. __extends(MotorEnabledJoint, _super);
  88202. function MotorEnabledJoint(type, jointData) {
  88203. return _super.call(this, type, jointData) || this;
  88204. }
  88205. /**
  88206. * Set the motor values.
  88207. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88208. * @param {number} force the force to apply
  88209. * @param {number} maxForce max force for this motor.
  88210. */
  88211. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  88212. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88213. };
  88214. /**
  88215. * Set the motor's limits.
  88216. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88217. */
  88218. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88219. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88220. };
  88221. return MotorEnabledJoint;
  88222. }(PhysicsJoint));
  88223. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  88224. /**
  88225. * This class represents a single hinge physics joint
  88226. */
  88227. var HingeJoint = /** @class */ (function (_super) {
  88228. __extends(HingeJoint, _super);
  88229. function HingeJoint(jointData) {
  88230. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  88231. }
  88232. /**
  88233. * Set the motor values.
  88234. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88235. * @param {number} force the force to apply
  88236. * @param {number} maxForce max force for this motor.
  88237. */
  88238. HingeJoint.prototype.setMotor = function (force, maxForce) {
  88239. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88240. };
  88241. /**
  88242. * Set the motor's limits.
  88243. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88244. */
  88245. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88246. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88247. };
  88248. return HingeJoint;
  88249. }(MotorEnabledJoint));
  88250. BABYLON.HingeJoint = HingeJoint;
  88251. /**
  88252. * This class represents a dual hinge physics joint (same as wheel joint)
  88253. */
  88254. var Hinge2Joint = /** @class */ (function (_super) {
  88255. __extends(Hinge2Joint, _super);
  88256. function Hinge2Joint(jointData) {
  88257. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  88258. }
  88259. /**
  88260. * Set the motor values.
  88261. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88262. * @param {number} force the force to apply
  88263. * @param {number} maxForce max force for this motor.
  88264. * @param {motorIndex} the motor's index, 0 or 1.
  88265. */
  88266. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  88267. if (motorIndex === void 0) { motorIndex = 0; }
  88268. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  88269. };
  88270. /**
  88271. * Set the motor limits.
  88272. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88273. * @param {number} upperLimit the upper limit
  88274. * @param {number} lowerLimit lower limit
  88275. * @param {motorIndex} the motor's index, 0 or 1.
  88276. */
  88277. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  88278. if (motorIndex === void 0) { motorIndex = 0; }
  88279. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  88280. };
  88281. return Hinge2Joint;
  88282. }(MotorEnabledJoint));
  88283. BABYLON.Hinge2Joint = Hinge2Joint;
  88284. })(BABYLON || (BABYLON = {}));
  88285. //# sourceMappingURL=babylon.physicsJoint.js.map
  88286. var BABYLON;
  88287. (function (BABYLON) {
  88288. var PhysicsImpostor = /** @class */ (function () {
  88289. function PhysicsImpostor(object, type, _options, _scene) {
  88290. if (_options === void 0) { _options = { mass: 0 }; }
  88291. var _this = this;
  88292. this.object = object;
  88293. this.type = type;
  88294. this._options = _options;
  88295. this._scene = _scene;
  88296. this._bodyUpdateRequired = false;
  88297. this._onBeforePhysicsStepCallbacks = new Array();
  88298. this._onAfterPhysicsStepCallbacks = new Array();
  88299. this._onPhysicsCollideCallbacks = [];
  88300. this._deltaPosition = BABYLON.Vector3.Zero();
  88301. this._isDisposed = false;
  88302. //temp variables for parent rotation calculations
  88303. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  88304. this._tmpQuat = new BABYLON.Quaternion();
  88305. this._tmpQuat2 = new BABYLON.Quaternion();
  88306. /**
  88307. * this function is executed by the physics engine.
  88308. */
  88309. this.beforeStep = function () {
  88310. if (!_this._physicsEngine) {
  88311. return;
  88312. }
  88313. _this.object.translate(_this._deltaPosition, -1);
  88314. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  88315. _this.object.computeWorldMatrix(false);
  88316. if (_this.object.parent && _this.object.rotationQuaternion) {
  88317. _this.getParentsRotation();
  88318. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  88319. }
  88320. else {
  88321. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  88322. }
  88323. if (!_this._options.disableBidirectionalTransformation) {
  88324. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  88325. }
  88326. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  88327. func(_this);
  88328. });
  88329. };
  88330. /**
  88331. * this function is executed by the physics engine.
  88332. */
  88333. this.afterStep = function () {
  88334. if (!_this._physicsEngine) {
  88335. return;
  88336. }
  88337. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  88338. func(_this);
  88339. });
  88340. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  88341. // object has now its world rotation. needs to be converted to local.
  88342. if (_this.object.parent && _this.object.rotationQuaternion) {
  88343. _this.getParentsRotation();
  88344. _this._tmpQuat.conjugateInPlace();
  88345. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  88346. }
  88347. // take the position set and make it the absolute position of this object.
  88348. _this.object.setAbsolutePosition(_this.object.position);
  88349. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  88350. _this.object.translate(_this._deltaPosition, 1);
  88351. };
  88352. /**
  88353. * Legacy collision detection event support
  88354. */
  88355. this.onCollideEvent = null;
  88356. //event and body object due to cannon's event-based architecture.
  88357. this.onCollide = function (e) {
  88358. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  88359. return;
  88360. }
  88361. if (!_this._physicsEngine) {
  88362. return;
  88363. }
  88364. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  88365. if (otherImpostor) {
  88366. // Legacy collision detection event support
  88367. if (_this.onCollideEvent) {
  88368. _this.onCollideEvent(_this, otherImpostor);
  88369. }
  88370. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  88371. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  88372. }).forEach(function (obj) {
  88373. obj.callback(_this, otherImpostor);
  88374. });
  88375. }
  88376. };
  88377. //sanity check!
  88378. if (!this.object) {
  88379. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  88380. return;
  88381. }
  88382. //legacy support for old syntax.
  88383. if (!this._scene && object.getScene) {
  88384. this._scene = object.getScene();
  88385. }
  88386. if (!this._scene) {
  88387. return;
  88388. }
  88389. this._physicsEngine = this._scene.getPhysicsEngine();
  88390. if (!this._physicsEngine) {
  88391. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  88392. }
  88393. else {
  88394. //set the object's quaternion, if not set
  88395. if (!this.object.rotationQuaternion) {
  88396. if (this.object.rotation) {
  88397. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  88398. }
  88399. else {
  88400. this.object.rotationQuaternion = new BABYLON.Quaternion();
  88401. }
  88402. }
  88403. //default options params
  88404. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  88405. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  88406. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  88407. this._joints = [];
  88408. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  88409. if (!this.object.parent || this._options.ignoreParent) {
  88410. this._init();
  88411. }
  88412. else if (this.object.parent.physicsImpostor) {
  88413. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  88414. }
  88415. }
  88416. }
  88417. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  88418. get: function () {
  88419. return this._isDisposed;
  88420. },
  88421. enumerable: true,
  88422. configurable: true
  88423. });
  88424. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  88425. get: function () {
  88426. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  88427. },
  88428. set: function (value) {
  88429. this.setMass(value);
  88430. },
  88431. enumerable: true,
  88432. configurable: true
  88433. });
  88434. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  88435. get: function () {
  88436. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  88437. },
  88438. set: function (value) {
  88439. if (!this._physicsEngine) {
  88440. return;
  88441. }
  88442. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  88443. },
  88444. enumerable: true,
  88445. configurable: true
  88446. });
  88447. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  88448. get: function () {
  88449. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  88450. },
  88451. set: function (value) {
  88452. if (!this._physicsEngine) {
  88453. return;
  88454. }
  88455. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  88456. },
  88457. enumerable: true,
  88458. configurable: true
  88459. });
  88460. /**
  88461. * This function will completly initialize this impostor.
  88462. * It will create a new body - but only if this mesh has no parent.
  88463. * If it has, this impostor will not be used other than to define the impostor
  88464. * of the child mesh.
  88465. * @hidden
  88466. */
  88467. PhysicsImpostor.prototype._init = function () {
  88468. if (!this._physicsEngine) {
  88469. return;
  88470. }
  88471. this._physicsEngine.removeImpostor(this);
  88472. this.physicsBody = null;
  88473. this._parent = this._parent || this._getPhysicsParent();
  88474. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  88475. this._physicsEngine.addImpostor(this);
  88476. }
  88477. };
  88478. PhysicsImpostor.prototype._getPhysicsParent = function () {
  88479. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  88480. var parentMesh = this.object.parent;
  88481. return parentMesh.physicsImpostor;
  88482. }
  88483. return null;
  88484. };
  88485. /**
  88486. * Should a new body be generated.
  88487. */
  88488. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  88489. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  88490. };
  88491. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  88492. this.forceUpdate();
  88493. };
  88494. /**
  88495. * Force a regeneration of this or the parent's impostor's body.
  88496. * Use under cautious - This will remove all joints already implemented.
  88497. */
  88498. PhysicsImpostor.prototype.forceUpdate = function () {
  88499. this._init();
  88500. if (this.parent && !this._options.ignoreParent) {
  88501. this.parent.forceUpdate();
  88502. }
  88503. };
  88504. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  88505. /*public get mesh(): AbstractMesh {
  88506. return this._mesh;
  88507. }*/
  88508. /**
  88509. * Gets the body that holds this impostor. Either its own, or its parent.
  88510. */
  88511. get: function () {
  88512. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  88513. },
  88514. /**
  88515. * Set the physics body. Used mainly by the physics engine/plugin
  88516. */
  88517. set: function (physicsBody) {
  88518. if (this._physicsBody && this._physicsEngine) {
  88519. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  88520. }
  88521. this._physicsBody = physicsBody;
  88522. this.resetUpdateFlags();
  88523. },
  88524. enumerable: true,
  88525. configurable: true
  88526. });
  88527. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  88528. get: function () {
  88529. return !this._options.ignoreParent && this._parent ? this._parent : null;
  88530. },
  88531. set: function (value) {
  88532. this._parent = value;
  88533. },
  88534. enumerable: true,
  88535. configurable: true
  88536. });
  88537. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  88538. this._bodyUpdateRequired = false;
  88539. };
  88540. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  88541. if (this.object.getBoundingInfo) {
  88542. var q = this.object.rotationQuaternion;
  88543. //reset rotation
  88544. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  88545. //calculate the world matrix with no rotation
  88546. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88547. var boundingInfo = this.object.getBoundingInfo();
  88548. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  88549. //bring back the rotation
  88550. this.object.rotationQuaternion = q;
  88551. //calculate the world matrix with the new rotation
  88552. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88553. return size;
  88554. }
  88555. else {
  88556. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  88557. }
  88558. };
  88559. PhysicsImpostor.prototype.getObjectCenter = function () {
  88560. if (this.object.getBoundingInfo) {
  88561. var boundingInfo = this.object.getBoundingInfo();
  88562. return boundingInfo.boundingBox.centerWorld;
  88563. }
  88564. else {
  88565. return this.object.position;
  88566. }
  88567. };
  88568. /**
  88569. * Get a specific parametes from the options parameter.
  88570. */
  88571. PhysicsImpostor.prototype.getParam = function (paramName) {
  88572. return this._options[paramName];
  88573. };
  88574. /**
  88575. * Sets a specific parameter in the options given to the physics plugin
  88576. */
  88577. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  88578. this._options[paramName] = value;
  88579. this._bodyUpdateRequired = true;
  88580. };
  88581. /**
  88582. * Specifically change the body's mass option. Won't recreate the physics body object
  88583. */
  88584. PhysicsImpostor.prototype.setMass = function (mass) {
  88585. if (this.getParam("mass") !== mass) {
  88586. this.setParam("mass", mass);
  88587. }
  88588. if (this._physicsEngine) {
  88589. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  88590. }
  88591. };
  88592. PhysicsImpostor.prototype.getLinearVelocity = function () {
  88593. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  88594. };
  88595. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  88596. if (this._physicsEngine) {
  88597. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  88598. }
  88599. };
  88600. PhysicsImpostor.prototype.getAngularVelocity = function () {
  88601. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  88602. };
  88603. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  88604. if (this._physicsEngine) {
  88605. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  88606. }
  88607. };
  88608. /**
  88609. * Execute a function with the physics plugin native code.
  88610. * Provide a function the will have two variables - the world object and the physics body object.
  88611. */
  88612. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  88613. if (this._physicsEngine) {
  88614. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  88615. }
  88616. };
  88617. /**
  88618. * Register a function that will be executed before the physics world is stepping forward.
  88619. */
  88620. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  88621. this._onBeforePhysicsStepCallbacks.push(func);
  88622. };
  88623. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  88624. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  88625. if (index > -1) {
  88626. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  88627. }
  88628. else {
  88629. BABYLON.Tools.Warn("Function to remove was not found");
  88630. }
  88631. };
  88632. /**
  88633. * Register a function that will be executed after the physics step
  88634. */
  88635. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  88636. this._onAfterPhysicsStepCallbacks.push(func);
  88637. };
  88638. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  88639. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  88640. if (index > -1) {
  88641. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  88642. }
  88643. else {
  88644. BABYLON.Tools.Warn("Function to remove was not found");
  88645. }
  88646. };
  88647. /**
  88648. * register a function that will be executed when this impostor collides against a different body.
  88649. */
  88650. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  88651. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88652. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  88653. };
  88654. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  88655. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88656. var index = -1;
  88657. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  88658. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  88659. // chcek the arrays match
  88660. var sameList = cbDef.otherImpostors.every(function (impostor) {
  88661. return collidedAgainstList.indexOf(impostor) > -1;
  88662. });
  88663. if (sameList) {
  88664. index = idx;
  88665. }
  88666. return sameList;
  88667. }
  88668. return false;
  88669. });
  88670. if (found) {
  88671. this._onPhysicsCollideCallbacks.splice(index, 1);
  88672. }
  88673. else {
  88674. BABYLON.Tools.Warn("Function to remove was not found");
  88675. }
  88676. };
  88677. PhysicsImpostor.prototype.getParentsRotation = function () {
  88678. var parent = this.object.parent;
  88679. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  88680. while (parent) {
  88681. if (parent.rotationQuaternion) {
  88682. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  88683. }
  88684. else {
  88685. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  88686. }
  88687. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  88688. parent = parent.parent;
  88689. }
  88690. return this._tmpQuat;
  88691. };
  88692. /**
  88693. * Apply a force
  88694. */
  88695. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  88696. if (this._physicsEngine) {
  88697. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  88698. }
  88699. return this;
  88700. };
  88701. /**
  88702. * Apply an impulse
  88703. */
  88704. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  88705. if (this._physicsEngine) {
  88706. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  88707. }
  88708. return this;
  88709. };
  88710. /**
  88711. * A help function to create a joint.
  88712. */
  88713. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  88714. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  88715. this.addJoint(otherImpostor, joint);
  88716. return this;
  88717. };
  88718. /**
  88719. * Add a joint to this impostor with a different impostor.
  88720. */
  88721. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  88722. this._joints.push({
  88723. otherImpostor: otherImpostor,
  88724. joint: joint
  88725. });
  88726. if (this._physicsEngine) {
  88727. this._physicsEngine.addJoint(this, otherImpostor, joint);
  88728. }
  88729. return this;
  88730. };
  88731. /**
  88732. * Will keep this body still, in a sleep mode.
  88733. */
  88734. PhysicsImpostor.prototype.sleep = function () {
  88735. if (this._physicsEngine) {
  88736. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  88737. }
  88738. return this;
  88739. };
  88740. /**
  88741. * Wake the body up.
  88742. */
  88743. PhysicsImpostor.prototype.wakeUp = function () {
  88744. if (this._physicsEngine) {
  88745. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  88746. }
  88747. return this;
  88748. };
  88749. PhysicsImpostor.prototype.clone = function (newObject) {
  88750. if (!newObject)
  88751. return null;
  88752. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  88753. };
  88754. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  88755. var _this = this;
  88756. //no dispose if no physics engine is available.
  88757. if (!this._physicsEngine) {
  88758. return;
  88759. }
  88760. this._joints.forEach(function (j) {
  88761. if (_this._physicsEngine) {
  88762. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  88763. }
  88764. });
  88765. //dispose the physics body
  88766. this._physicsEngine.removeImpostor(this);
  88767. if (this.parent) {
  88768. this.parent.forceUpdate();
  88769. }
  88770. else {
  88771. /*this._object.getChildMeshes().forEach(function(mesh) {
  88772. if (mesh.physicsImpostor) {
  88773. if (disposeChildren) {
  88774. mesh.physicsImpostor.dispose();
  88775. mesh.physicsImpostor = null;
  88776. }
  88777. }
  88778. })*/
  88779. }
  88780. this._isDisposed = true;
  88781. };
  88782. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  88783. this._deltaPosition.copyFrom(position);
  88784. };
  88785. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  88786. if (!this._deltaRotation) {
  88787. this._deltaRotation = new BABYLON.Quaternion();
  88788. }
  88789. this._deltaRotation.copyFrom(rotation);
  88790. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  88791. };
  88792. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  88793. if (this._physicsEngine) {
  88794. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  88795. }
  88796. return this;
  88797. };
  88798. PhysicsImpostor.prototype.getRadius = function () {
  88799. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  88800. };
  88801. /**
  88802. * Sync a bone with this impostor
  88803. * @param bone The bone to sync to the impostor.
  88804. * @param boneMesh The mesh that the bone is influencing.
  88805. * @param jointPivot The pivot of the joint / bone in local space.
  88806. * @param distToJoint Optional distance from the impostor to the joint.
  88807. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88808. */
  88809. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  88810. var tempVec = PhysicsImpostor._tmpVecs[0];
  88811. var mesh = this.object;
  88812. if (mesh.rotationQuaternion) {
  88813. if (adjustRotation) {
  88814. var tempQuat = PhysicsImpostor._tmpQuat;
  88815. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  88816. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  88817. }
  88818. else {
  88819. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  88820. }
  88821. }
  88822. tempVec.x = 0;
  88823. tempVec.y = 0;
  88824. tempVec.z = 0;
  88825. if (jointPivot) {
  88826. tempVec.x = jointPivot.x;
  88827. tempVec.y = jointPivot.y;
  88828. tempVec.z = jointPivot.z;
  88829. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  88830. if (distToJoint === undefined || distToJoint === null) {
  88831. distToJoint = jointPivot.length();
  88832. }
  88833. tempVec.x *= distToJoint;
  88834. tempVec.y *= distToJoint;
  88835. tempVec.z *= distToJoint;
  88836. }
  88837. if (bone.getParent()) {
  88838. tempVec.addInPlace(mesh.getAbsolutePosition());
  88839. bone.setAbsolutePosition(tempVec, boneMesh);
  88840. }
  88841. else {
  88842. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  88843. boneMesh.position.x -= tempVec.x;
  88844. boneMesh.position.y -= tempVec.y;
  88845. boneMesh.position.z -= tempVec.z;
  88846. }
  88847. };
  88848. /**
  88849. * Sync impostor to a bone
  88850. * @param bone The bone that the impostor will be synced to.
  88851. * @param boneMesh The mesh that the bone is influencing.
  88852. * @param jointPivot The pivot of the joint / bone in local space.
  88853. * @param distToJoint Optional distance from the impostor to the joint.
  88854. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88855. * @param boneAxis Optional vector3 axis the bone is aligned with
  88856. */
  88857. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  88858. var mesh = this.object;
  88859. if (mesh.rotationQuaternion) {
  88860. if (adjustRotation) {
  88861. var tempQuat = PhysicsImpostor._tmpQuat;
  88862. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  88863. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  88864. }
  88865. else {
  88866. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  88867. }
  88868. }
  88869. var pos = PhysicsImpostor._tmpVecs[0];
  88870. var boneDir = PhysicsImpostor._tmpVecs[1];
  88871. if (!boneAxis) {
  88872. boneAxis = PhysicsImpostor._tmpVecs[2];
  88873. boneAxis.x = 0;
  88874. boneAxis.y = 1;
  88875. boneAxis.z = 0;
  88876. }
  88877. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  88878. bone.getAbsolutePositionToRef(boneMesh, pos);
  88879. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  88880. distToJoint = jointPivot.length();
  88881. }
  88882. if (distToJoint !== undefined && distToJoint !== null) {
  88883. pos.x += boneDir.x * distToJoint;
  88884. pos.y += boneDir.y * distToJoint;
  88885. pos.z += boneDir.z * distToJoint;
  88886. }
  88887. mesh.setAbsolutePosition(pos);
  88888. };
  88889. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  88890. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  88891. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88892. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  88893. //Impostor types
  88894. PhysicsImpostor.NoImpostor = 0;
  88895. PhysicsImpostor.SphereImpostor = 1;
  88896. PhysicsImpostor.BoxImpostor = 2;
  88897. PhysicsImpostor.PlaneImpostor = 3;
  88898. PhysicsImpostor.MeshImpostor = 4;
  88899. PhysicsImpostor.CylinderImpostor = 7;
  88900. PhysicsImpostor.ParticleImpostor = 8;
  88901. PhysicsImpostor.HeightmapImpostor = 9;
  88902. return PhysicsImpostor;
  88903. }());
  88904. BABYLON.PhysicsImpostor = PhysicsImpostor;
  88905. })(BABYLON || (BABYLON = {}));
  88906. //# sourceMappingURL=babylon.physicsImpostor.js.map
  88907. var BABYLON;
  88908. (function (BABYLON) {
  88909. var PhysicsEngine = /** @class */ (function () {
  88910. function PhysicsEngine(gravity, _physicsPlugin) {
  88911. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  88912. this._physicsPlugin = _physicsPlugin;
  88913. //new methods and parameters
  88914. this._impostors = [];
  88915. this._joints = [];
  88916. if (!this._physicsPlugin.isSupported()) {
  88917. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  88918. + "Please make sure it is included.");
  88919. }
  88920. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  88921. this.setGravity(gravity);
  88922. this.setTimeStep();
  88923. }
  88924. PhysicsEngine.prototype.setGravity = function (gravity) {
  88925. this.gravity = gravity;
  88926. this._physicsPlugin.setGravity(this.gravity);
  88927. };
  88928. /**
  88929. * Set the time step of the physics engine.
  88930. * default is 1/60.
  88931. * To slow it down, enter 1/600 for example.
  88932. * To speed it up, 1/30
  88933. * @param {number} newTimeStep the new timestep to apply to this world.
  88934. */
  88935. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  88936. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  88937. this._physicsPlugin.setTimeStep(newTimeStep);
  88938. };
  88939. /**
  88940. * Get the time step of the physics engine.
  88941. */
  88942. PhysicsEngine.prototype.getTimeStep = function () {
  88943. return this._physicsPlugin.getTimeStep();
  88944. };
  88945. PhysicsEngine.prototype.dispose = function () {
  88946. this._impostors.forEach(function (impostor) {
  88947. impostor.dispose();
  88948. });
  88949. this._physicsPlugin.dispose();
  88950. };
  88951. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  88952. return this._physicsPlugin.name;
  88953. };
  88954. /**
  88955. * Adding a new impostor for the impostor tracking.
  88956. * This will be done by the impostor itself.
  88957. * @param {PhysicsImpostor} impostor the impostor to add
  88958. */
  88959. PhysicsEngine.prototype.addImpostor = function (impostor) {
  88960. impostor.uniqueId = this._impostors.push(impostor);
  88961. //if no parent, generate the body
  88962. if (!impostor.parent) {
  88963. this._physicsPlugin.generatePhysicsBody(impostor);
  88964. }
  88965. };
  88966. /**
  88967. * Remove an impostor from the engine.
  88968. * This impostor and its mesh will not longer be updated by the physics engine.
  88969. * @param {PhysicsImpostor} impostor the impostor to remove
  88970. */
  88971. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  88972. var index = this._impostors.indexOf(impostor);
  88973. if (index > -1) {
  88974. var removed = this._impostors.splice(index, 1);
  88975. //Is it needed?
  88976. if (removed.length) {
  88977. //this will also remove it from the world.
  88978. removed[0].physicsBody = null;
  88979. }
  88980. }
  88981. };
  88982. /**
  88983. * Add a joint to the physics engine
  88984. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  88985. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  88986. * @param {PhysicsJoint} the joint that will connect both impostors.
  88987. */
  88988. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  88989. var impostorJoint = {
  88990. mainImpostor: mainImpostor,
  88991. connectedImpostor: connectedImpostor,
  88992. joint: joint
  88993. };
  88994. joint.physicsPlugin = this._physicsPlugin;
  88995. this._joints.push(impostorJoint);
  88996. this._physicsPlugin.generateJoint(impostorJoint);
  88997. };
  88998. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  88999. var matchingJoints = this._joints.filter(function (impostorJoint) {
  89000. return (impostorJoint.connectedImpostor === connectedImpostor
  89001. && impostorJoint.joint === joint
  89002. && impostorJoint.mainImpostor === mainImpostor);
  89003. });
  89004. if (matchingJoints.length) {
  89005. this._physicsPlugin.removeJoint(matchingJoints[0]);
  89006. //TODO remove it from the list as well
  89007. }
  89008. };
  89009. /**
  89010. * Called by the scene. no need to call it.
  89011. * @hidden
  89012. */
  89013. PhysicsEngine.prototype._step = function (delta) {
  89014. var _this = this;
  89015. //check if any mesh has no body / requires an update
  89016. this._impostors.forEach(function (impostor) {
  89017. if (impostor.isBodyInitRequired()) {
  89018. _this._physicsPlugin.generatePhysicsBody(impostor);
  89019. }
  89020. });
  89021. if (delta > 0.1) {
  89022. delta = 0.1;
  89023. }
  89024. else if (delta <= 0) {
  89025. delta = 1.0 / 60.0;
  89026. }
  89027. this._physicsPlugin.executeStep(delta, this._impostors);
  89028. };
  89029. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  89030. return this._physicsPlugin;
  89031. };
  89032. PhysicsEngine.prototype.getImpostors = function () {
  89033. return this._impostors;
  89034. };
  89035. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  89036. for (var i = 0; i < this._impostors.length; ++i) {
  89037. if (this._impostors[i].object === object) {
  89038. return this._impostors[i];
  89039. }
  89040. }
  89041. return null;
  89042. };
  89043. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  89044. for (var i = 0; i < this._impostors.length; ++i) {
  89045. if (this._impostors[i].physicsBody === body) {
  89046. return this._impostors[i];
  89047. }
  89048. }
  89049. return null;
  89050. };
  89051. // Statics
  89052. PhysicsEngine.Epsilon = 0.001;
  89053. return PhysicsEngine;
  89054. }());
  89055. BABYLON.PhysicsEngine = PhysicsEngine;
  89056. })(BABYLON || (BABYLON = {}));
  89057. //# sourceMappingURL=babylon.physicsEngine.js.map
  89058. var BABYLON;
  89059. (function (BABYLON) {
  89060. var PhysicsHelper = /** @class */ (function () {
  89061. function PhysicsHelper(scene) {
  89062. this._scene = scene;
  89063. this._physicsEngine = this._scene.getPhysicsEngine();
  89064. if (!this._physicsEngine) {
  89065. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  89066. }
  89067. }
  89068. /**
  89069. * @param {Vector3} origin the origin of the explosion
  89070. * @param {number} radius the explosion radius
  89071. * @param {number} strength the explosion strength
  89072. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89073. */
  89074. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  89075. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89076. if (!this._physicsEngine) {
  89077. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  89078. return null;
  89079. }
  89080. var impostors = this._physicsEngine.getImpostors();
  89081. if (impostors.length === 0) {
  89082. return null;
  89083. }
  89084. var event = new PhysicsRadialExplosionEvent(this._scene);
  89085. impostors.forEach(function (impostor) {
  89086. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89087. if (!impostorForceAndContactPoint) {
  89088. return;
  89089. }
  89090. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89091. });
  89092. event.dispose(false);
  89093. return event;
  89094. };
  89095. /**
  89096. * @param {Vector3} origin the origin of the explosion
  89097. * @param {number} radius the explosion radius
  89098. * @param {number} strength the explosion strength
  89099. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89100. */
  89101. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  89102. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89103. if (!this._physicsEngine) {
  89104. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89105. return null;
  89106. }
  89107. var impostors = this._physicsEngine.getImpostors();
  89108. if (impostors.length === 0) {
  89109. return null;
  89110. }
  89111. var event = new PhysicsRadialExplosionEvent(this._scene);
  89112. impostors.forEach(function (impostor) {
  89113. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89114. if (!impostorForceAndContactPoint) {
  89115. return;
  89116. }
  89117. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89118. });
  89119. event.dispose(false);
  89120. return event;
  89121. };
  89122. /**
  89123. * @param {Vector3} origin the origin of the explosion
  89124. * @param {number} radius the explosion radius
  89125. * @param {number} strength the explosion strength
  89126. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89127. */
  89128. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  89129. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89130. if (!this._physicsEngine) {
  89131. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89132. return null;
  89133. }
  89134. var impostors = this._physicsEngine.getImpostors();
  89135. if (impostors.length === 0) {
  89136. return null;
  89137. }
  89138. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  89139. event.dispose(false);
  89140. return event;
  89141. };
  89142. /**
  89143. * @param {Vector3} origin the origin of the updraft
  89144. * @param {number} radius the radius of the updraft
  89145. * @param {number} strength the strength of the updraft
  89146. * @param {number} height the height of the updraft
  89147. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  89148. */
  89149. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  89150. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  89151. if (!this._physicsEngine) {
  89152. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89153. return null;
  89154. }
  89155. if (this._physicsEngine.getImpostors().length === 0) {
  89156. return null;
  89157. }
  89158. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  89159. event.dispose(false);
  89160. return event;
  89161. };
  89162. /**
  89163. * @param {Vector3} origin the of the vortex
  89164. * @param {number} radius the radius of the vortex
  89165. * @param {number} strength the strength of the vortex
  89166. * @param {number} height the height of the vortex
  89167. */
  89168. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  89169. if (!this._physicsEngine) {
  89170. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89171. return null;
  89172. }
  89173. if (this._physicsEngine.getImpostors().length === 0) {
  89174. return null;
  89175. }
  89176. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  89177. event.dispose(false);
  89178. return event;
  89179. };
  89180. return PhysicsHelper;
  89181. }());
  89182. BABYLON.PhysicsHelper = PhysicsHelper;
  89183. /***** Radial explosion *****/
  89184. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  89185. function PhysicsRadialExplosionEvent(scene) {
  89186. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  89187. this._rays = [];
  89188. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  89189. this._scene = scene;
  89190. }
  89191. /**
  89192. * Returns the data related to the radial explosion event (sphere & rays).
  89193. * @returns {PhysicsRadialExplosionEventData}
  89194. */
  89195. PhysicsRadialExplosionEvent.prototype.getData = function () {
  89196. this._dataFetched = true;
  89197. return {
  89198. sphere: this._sphere,
  89199. rays: this._rays,
  89200. };
  89201. };
  89202. /**
  89203. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  89204. * @param impostor
  89205. * @param {Vector3} origin the origin of the explosion
  89206. * @param {number} radius the explosion radius
  89207. * @param {number} strength the explosion strength
  89208. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  89209. * @returns {Nullable<PhysicsForceAndContactPoint>}
  89210. */
  89211. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  89212. if (impostor.mass === 0) {
  89213. return null;
  89214. }
  89215. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  89216. return null;
  89217. }
  89218. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89219. return null;
  89220. }
  89221. var impostorObjectCenter = impostor.getObjectCenter();
  89222. var direction = impostorObjectCenter.subtract(origin);
  89223. var ray = new BABYLON.Ray(origin, direction, radius);
  89224. this._rays.push(ray);
  89225. var hit = ray.intersectsMesh(impostor.object);
  89226. var contactPoint = hit.pickedPoint;
  89227. if (!contactPoint) {
  89228. return null;
  89229. }
  89230. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  89231. if (distanceFromOrigin > radius) {
  89232. return null;
  89233. }
  89234. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  89235. ? strength
  89236. : strength * (1 - (distanceFromOrigin / radius));
  89237. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89238. return { force: force, contactPoint: contactPoint };
  89239. };
  89240. /**
  89241. * Disposes the sphere.
  89242. * @param {bolean} force
  89243. */
  89244. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  89245. var _this = this;
  89246. if (force === void 0) { force = true; }
  89247. if (force) {
  89248. this._sphere.dispose();
  89249. }
  89250. else {
  89251. setTimeout(function () {
  89252. if (!_this._dataFetched) {
  89253. _this._sphere.dispose();
  89254. }
  89255. }, 0);
  89256. }
  89257. };
  89258. /*** Helpers ***/
  89259. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  89260. if (!this._sphere) {
  89261. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  89262. this._sphere.isVisible = false;
  89263. }
  89264. };
  89265. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  89266. var impostorObject = impostor.object;
  89267. this._prepareSphere();
  89268. this._sphere.position = origin;
  89269. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  89270. this._sphere._updateBoundingInfo();
  89271. this._sphere.computeWorldMatrix(true);
  89272. return this._sphere.intersectsMesh(impostorObject, true);
  89273. };
  89274. return PhysicsRadialExplosionEvent;
  89275. }());
  89276. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  89277. /***** Gravitational Field *****/
  89278. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  89279. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  89280. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89281. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89282. this._physicsHelper = physicsHelper;
  89283. this._scene = scene;
  89284. this._origin = origin;
  89285. this._radius = radius;
  89286. this._strength = strength;
  89287. this._falloff = falloff;
  89288. this._tickCallback = this._tick.bind(this);
  89289. }
  89290. /**
  89291. * Returns the data related to the gravitational field event (sphere).
  89292. * @returns {PhysicsGravitationalFieldEventData}
  89293. */
  89294. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  89295. this._dataFetched = true;
  89296. return {
  89297. sphere: this._sphere,
  89298. };
  89299. };
  89300. /**
  89301. * Enables the gravitational field.
  89302. */
  89303. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  89304. this._tickCallback.call(this);
  89305. this._scene.registerBeforeRender(this._tickCallback);
  89306. };
  89307. /**
  89308. * Disables the gravitational field.
  89309. */
  89310. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  89311. this._scene.unregisterBeforeRender(this._tickCallback);
  89312. };
  89313. /**
  89314. * Disposes the sphere.
  89315. * @param {bolean} force
  89316. */
  89317. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  89318. var _this = this;
  89319. if (force === void 0) { force = true; }
  89320. if (force) {
  89321. this._sphere.dispose();
  89322. }
  89323. else {
  89324. setTimeout(function () {
  89325. if (!_this._dataFetched) {
  89326. _this._sphere.dispose();
  89327. }
  89328. }, 0);
  89329. }
  89330. };
  89331. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  89332. // Since the params won't change, we fetch the event only once
  89333. if (this._sphere) {
  89334. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89335. }
  89336. else {
  89337. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89338. if (radialExplosionEvent) {
  89339. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  89340. }
  89341. }
  89342. };
  89343. return PhysicsGravitationalFieldEvent;
  89344. }());
  89345. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  89346. /***** Updraft *****/
  89347. var PhysicsUpdraftEvent = /** @class */ (function () {
  89348. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  89349. this._scene = _scene;
  89350. this._origin = _origin;
  89351. this._radius = _radius;
  89352. this._strength = _strength;
  89353. this._height = _height;
  89354. this._updraftMode = _updraftMode;
  89355. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89356. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  89357. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89358. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89359. this._physicsEngine = this._scene.getPhysicsEngine();
  89360. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89361. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89362. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89363. this._originDirection = this._origin.subtract(this._originTop).normalize();
  89364. }
  89365. this._tickCallback = this._tick.bind(this);
  89366. }
  89367. /**
  89368. * Returns the data related to the updraft event (cylinder).
  89369. * @returns {PhysicsUpdraftEventData}
  89370. */
  89371. PhysicsUpdraftEvent.prototype.getData = function () {
  89372. this._dataFetched = true;
  89373. return {
  89374. cylinder: this._cylinder,
  89375. };
  89376. };
  89377. /**
  89378. * Enables the updraft.
  89379. */
  89380. PhysicsUpdraftEvent.prototype.enable = function () {
  89381. this._tickCallback.call(this);
  89382. this._scene.registerBeforeRender(this._tickCallback);
  89383. };
  89384. /**
  89385. * Disables the cortex.
  89386. */
  89387. PhysicsUpdraftEvent.prototype.disable = function () {
  89388. this._scene.unregisterBeforeRender(this._tickCallback);
  89389. };
  89390. /**
  89391. * Disposes the sphere.
  89392. * @param {bolean} force
  89393. */
  89394. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  89395. var _this = this;
  89396. if (force === void 0) { force = true; }
  89397. if (force) {
  89398. this._cylinder.dispose();
  89399. }
  89400. else {
  89401. setTimeout(function () {
  89402. if (!_this._dataFetched) {
  89403. _this._cylinder.dispose();
  89404. }
  89405. }, 0);
  89406. }
  89407. };
  89408. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89409. if (impostor.mass === 0) {
  89410. return null;
  89411. }
  89412. if (!this._intersectsWithCylinder(impostor)) {
  89413. return null;
  89414. }
  89415. var impostorObjectCenter = impostor.getObjectCenter();
  89416. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89417. var direction = this._originDirection;
  89418. }
  89419. else {
  89420. var direction = impostorObjectCenter.subtract(this._originTop);
  89421. }
  89422. var multiplier = this._strength * -1;
  89423. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89424. return { force: force, contactPoint: impostorObjectCenter };
  89425. };
  89426. PhysicsUpdraftEvent.prototype._tick = function () {
  89427. var _this = this;
  89428. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89429. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89430. if (!impostorForceAndContactPoint) {
  89431. return;
  89432. }
  89433. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89434. });
  89435. };
  89436. /*** Helpers ***/
  89437. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  89438. if (!this._cylinder) {
  89439. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  89440. height: this._height,
  89441. diameter: this._radius * 2,
  89442. }, this._scene);
  89443. this._cylinder.isVisible = false;
  89444. }
  89445. };
  89446. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  89447. var impostorObject = impostor.object;
  89448. this._prepareCylinder();
  89449. this._cylinder.position = this._cylinderPosition;
  89450. return this._cylinder.intersectsMesh(impostorObject, true);
  89451. };
  89452. return PhysicsUpdraftEvent;
  89453. }());
  89454. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  89455. /***** Vortex *****/
  89456. var PhysicsVortexEvent = /** @class */ (function () {
  89457. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  89458. this._scene = _scene;
  89459. this._origin = _origin;
  89460. this._radius = _radius;
  89461. this._strength = _strength;
  89462. this._height = _height;
  89463. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89464. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  89465. this._updraftMultiplier = 0.02;
  89466. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89467. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89468. this._physicsEngine = this._scene.getPhysicsEngine();
  89469. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89470. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89471. this._tickCallback = this._tick.bind(this);
  89472. }
  89473. /**
  89474. * Returns the data related to the vortex event (cylinder).
  89475. * @returns {PhysicsVortexEventData}
  89476. */
  89477. PhysicsVortexEvent.prototype.getData = function () {
  89478. this._dataFetched = true;
  89479. return {
  89480. cylinder: this._cylinder,
  89481. };
  89482. };
  89483. /**
  89484. * Enables the vortex.
  89485. */
  89486. PhysicsVortexEvent.prototype.enable = function () {
  89487. this._tickCallback.call(this);
  89488. this._scene.registerBeforeRender(this._tickCallback);
  89489. };
  89490. /**
  89491. * Disables the cortex.
  89492. */
  89493. PhysicsVortexEvent.prototype.disable = function () {
  89494. this._scene.unregisterBeforeRender(this._tickCallback);
  89495. };
  89496. /**
  89497. * Disposes the sphere.
  89498. * @param {bolean} force
  89499. */
  89500. PhysicsVortexEvent.prototype.dispose = function (force) {
  89501. var _this = this;
  89502. if (force === void 0) { force = true; }
  89503. if (force) {
  89504. this._cylinder.dispose();
  89505. }
  89506. else {
  89507. setTimeout(function () {
  89508. if (!_this._dataFetched) {
  89509. _this._cylinder.dispose();
  89510. }
  89511. }, 0);
  89512. }
  89513. };
  89514. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89515. if (impostor.mass === 0) {
  89516. return null;
  89517. }
  89518. if (!this._intersectsWithCylinder(impostor)) {
  89519. return null;
  89520. }
  89521. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89522. return null;
  89523. }
  89524. var impostorObjectCenter = impostor.getObjectCenter();
  89525. 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)
  89526. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  89527. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  89528. var hit = ray.intersectsMesh(impostor.object);
  89529. var contactPoint = hit.pickedPoint;
  89530. if (!contactPoint) {
  89531. return null;
  89532. }
  89533. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  89534. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  89535. var directionToOrigin = contactPoint.normalize();
  89536. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89537. directionToOrigin = directionToOrigin.negate();
  89538. }
  89539. // TODO: find a more physically based solution
  89540. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89541. var forceX = directionToOrigin.x * this._strength / 8;
  89542. var forceY = directionToOrigin.y * this._updraftMultiplier;
  89543. var forceZ = directionToOrigin.z * this._strength / 8;
  89544. }
  89545. else {
  89546. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  89547. var forceY = this._originTop.y * this._updraftMultiplier;
  89548. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  89549. }
  89550. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  89551. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  89552. return { force: force, contactPoint: impostorObjectCenter };
  89553. };
  89554. PhysicsVortexEvent.prototype._tick = function () {
  89555. var _this = this;
  89556. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89557. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89558. if (!impostorForceAndContactPoint) {
  89559. return;
  89560. }
  89561. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89562. });
  89563. };
  89564. /*** Helpers ***/
  89565. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  89566. if (!this._cylinder) {
  89567. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  89568. height: this._height,
  89569. diameter: this._radius * 2,
  89570. }, this._scene);
  89571. this._cylinder.isVisible = false;
  89572. }
  89573. };
  89574. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  89575. var impostorObject = impostor.object;
  89576. this._prepareCylinder();
  89577. this._cylinder.position = this._cylinderPosition;
  89578. return this._cylinder.intersectsMesh(impostorObject, true);
  89579. };
  89580. return PhysicsVortexEvent;
  89581. }());
  89582. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  89583. /***** Enums *****/
  89584. /**
  89585. * The strenght of the force in correspondence to the distance of the affected object
  89586. */
  89587. var PhysicsRadialImpulseFalloff;
  89588. (function (PhysicsRadialImpulseFalloff) {
  89589. /** Defines that impulse is constant in strength across it's whole radius */
  89590. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  89591. /** DEfines that impulse gets weaker if it's further from the origin */
  89592. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  89593. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  89594. /**
  89595. * The strenght of the force in correspondence to the distance of the affected object
  89596. */
  89597. var PhysicsUpdraftMode;
  89598. (function (PhysicsUpdraftMode) {
  89599. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  89600. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  89601. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  89602. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  89603. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  89604. })(BABYLON || (BABYLON = {}));
  89605. //# sourceMappingURL=babylon.physicsHelper.js.map
  89606. var BABYLON;
  89607. (function (BABYLON) {
  89608. var CannonJSPlugin = /** @class */ (function () {
  89609. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  89610. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  89611. if (iterations === void 0) { iterations = 10; }
  89612. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  89613. this.name = "CannonJSPlugin";
  89614. this._physicsMaterials = new Array();
  89615. this._fixedTimeStep = 1 / 60;
  89616. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  89617. this.BJSCANNON = CANNON;
  89618. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  89619. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  89620. this._tmpPosition = BABYLON.Vector3.Zero();
  89621. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  89622. this._tmpUnityRotation = new BABYLON.Quaternion();
  89623. if (!this.isSupported()) {
  89624. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  89625. return;
  89626. }
  89627. this._extendNamespace();
  89628. this.world = new this.BJSCANNON.World();
  89629. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  89630. this.world.solver.iterations = iterations;
  89631. }
  89632. CannonJSPlugin.prototype.setGravity = function (gravity) {
  89633. this.world.gravity.copy(gravity);
  89634. };
  89635. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  89636. this._fixedTimeStep = timeStep;
  89637. };
  89638. CannonJSPlugin.prototype.getTimeStep = function () {
  89639. return this._fixedTimeStep;
  89640. };
  89641. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  89642. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  89643. };
  89644. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89645. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89646. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89647. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  89648. };
  89649. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89650. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89651. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89652. impostor.physicsBody.applyForce(impulse, worldPoint);
  89653. };
  89654. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89655. //parent-child relationship. Does this impostor has a parent impostor?
  89656. if (impostor.parent) {
  89657. if (impostor.physicsBody) {
  89658. this.removePhysicsBody(impostor);
  89659. //TODO is that needed?
  89660. impostor.forceUpdate();
  89661. }
  89662. return;
  89663. }
  89664. //should a new body be created for this impostor?
  89665. if (impostor.isBodyInitRequired()) {
  89666. var shape = this._createShape(impostor);
  89667. //unregister events, if body is being changed
  89668. var oldBody = impostor.physicsBody;
  89669. if (oldBody) {
  89670. this.removePhysicsBody(impostor);
  89671. }
  89672. //create the body and material
  89673. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  89674. var bodyCreationObject = {
  89675. mass: impostor.getParam("mass"),
  89676. material: material
  89677. };
  89678. // A simple extend, in case native options were used.
  89679. var nativeOptions = impostor.getParam("nativeOptions");
  89680. for (var key in nativeOptions) {
  89681. if (nativeOptions.hasOwnProperty(key)) {
  89682. bodyCreationObject[key] = nativeOptions[key];
  89683. }
  89684. }
  89685. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  89686. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  89687. this.world.addEventListener("preStep", impostor.beforeStep);
  89688. this.world.addEventListener("postStep", impostor.afterStep);
  89689. impostor.physicsBody.addShape(shape);
  89690. this.world.add(impostor.physicsBody);
  89691. //try to keep the body moving in the right direction by taking old properties.
  89692. //Should be tested!
  89693. if (oldBody) {
  89694. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  89695. impostor.physicsBody[param].copy(oldBody[param]);
  89696. });
  89697. }
  89698. this._processChildMeshes(impostor);
  89699. }
  89700. //now update the body's transformation
  89701. this._updatePhysicsBodyTransformation(impostor);
  89702. };
  89703. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  89704. var _this = this;
  89705. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  89706. var currentRotation = mainImpostor.object.rotationQuaternion;
  89707. if (meshChildren.length) {
  89708. var processMesh = function (localPosition, mesh) {
  89709. if (!currentRotation || !mesh.rotationQuaternion) {
  89710. return;
  89711. }
  89712. var childImpostor = mesh.getPhysicsImpostor();
  89713. if (childImpostor) {
  89714. var parent = childImpostor.parent;
  89715. if (parent !== mainImpostor) {
  89716. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  89717. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  89718. if (childImpostor.physicsBody) {
  89719. _this.removePhysicsBody(childImpostor);
  89720. childImpostor.physicsBody = null;
  89721. }
  89722. childImpostor.parent = mainImpostor;
  89723. childImpostor.resetUpdateFlags();
  89724. 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));
  89725. //Add the mass of the children.
  89726. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  89727. }
  89728. }
  89729. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  89730. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  89731. };
  89732. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  89733. }
  89734. };
  89735. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  89736. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  89737. this.world.removeEventListener("preStep", impostor.beforeStep);
  89738. this.world.removeEventListener("postStep", impostor.afterStep);
  89739. this.world.remove(impostor.physicsBody);
  89740. };
  89741. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  89742. var mainBody = impostorJoint.mainImpostor.physicsBody;
  89743. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  89744. if (!mainBody || !connectedBody) {
  89745. return;
  89746. }
  89747. var constraint;
  89748. var jointData = impostorJoint.joint.jointData;
  89749. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  89750. var constraintData = {
  89751. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  89752. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  89753. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  89754. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  89755. maxForce: jointData.nativeParams.maxForce,
  89756. collideConnected: !!jointData.collision
  89757. };
  89758. switch (impostorJoint.joint.type) {
  89759. case BABYLON.PhysicsJoint.HingeJoint:
  89760. case BABYLON.PhysicsJoint.Hinge2Joint:
  89761. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  89762. break;
  89763. case BABYLON.PhysicsJoint.DistanceJoint:
  89764. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  89765. break;
  89766. case BABYLON.PhysicsJoint.SpringJoint:
  89767. var springData = jointData;
  89768. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  89769. restLength: springData.length,
  89770. stiffness: springData.stiffness,
  89771. damping: springData.damping,
  89772. localAnchorA: constraintData.pivotA,
  89773. localAnchorB: constraintData.pivotB
  89774. });
  89775. break;
  89776. case BABYLON.PhysicsJoint.LockJoint:
  89777. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  89778. break;
  89779. case BABYLON.PhysicsJoint.PointToPointJoint:
  89780. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  89781. default:
  89782. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  89783. break;
  89784. }
  89785. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  89786. constraint.collideConnected = !!jointData.collision;
  89787. impostorJoint.joint.physicsJoint = constraint;
  89788. //don't add spring as constraint, as it is not one.
  89789. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89790. this.world.addConstraint(constraint);
  89791. }
  89792. else {
  89793. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  89794. constraint.applyForce();
  89795. };
  89796. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89797. }
  89798. };
  89799. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89800. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89801. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  89802. }
  89803. else {
  89804. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89805. }
  89806. };
  89807. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  89808. var index;
  89809. var mat;
  89810. for (index = 0; index < this._physicsMaterials.length; index++) {
  89811. mat = this._physicsMaterials[index];
  89812. if (mat.friction === friction && mat.restitution === restitution) {
  89813. return mat;
  89814. }
  89815. }
  89816. var currentMat = new this.BJSCANNON.Material(name);
  89817. currentMat.friction = friction;
  89818. currentMat.restitution = restitution;
  89819. this._physicsMaterials.push(currentMat);
  89820. return currentMat;
  89821. };
  89822. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  89823. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  89824. };
  89825. CannonJSPlugin.prototype._createShape = function (impostor) {
  89826. var object = impostor.object;
  89827. var returnValue;
  89828. var extendSize = impostor.getObjectExtendSize();
  89829. switch (impostor.type) {
  89830. case BABYLON.PhysicsImpostor.SphereImpostor:
  89831. var radiusX = extendSize.x;
  89832. var radiusY = extendSize.y;
  89833. var radiusZ = extendSize.z;
  89834. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  89835. break;
  89836. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  89837. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89838. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  89839. break;
  89840. case BABYLON.PhysicsImpostor.BoxImpostor:
  89841. var box = extendSize.scale(0.5);
  89842. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  89843. break;
  89844. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89845. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  89846. returnValue = new this.BJSCANNON.Plane();
  89847. break;
  89848. case BABYLON.PhysicsImpostor.MeshImpostor:
  89849. // should transform the vertex data to world coordinates!!
  89850. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  89851. var rawFaces = object.getIndices ? object.getIndices() : [];
  89852. if (!rawVerts)
  89853. return;
  89854. // get only scale! so the object could transform correctly.
  89855. var oldPosition = object.position.clone();
  89856. var oldRotation = object.rotation && object.rotation.clone();
  89857. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  89858. object.position.copyFromFloats(0, 0, 0);
  89859. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89860. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89861. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89862. var transform = object.computeWorldMatrix(true);
  89863. // convert rawVerts to object space
  89864. var temp = new Array();
  89865. var index;
  89866. for (index = 0; index < rawVerts.length; index += 3) {
  89867. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  89868. }
  89869. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  89870. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  89871. //now set back the transformation!
  89872. object.position.copyFrom(oldPosition);
  89873. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  89874. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  89875. break;
  89876. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  89877. var oldPosition2 = object.position.clone();
  89878. var oldRotation2 = object.rotation && object.rotation.clone();
  89879. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  89880. object.position.copyFromFloats(0, 0, 0);
  89881. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89882. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89883. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89884. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  89885. returnValue = this._createHeightmap(object);
  89886. object.position.copyFrom(oldPosition2);
  89887. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  89888. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  89889. object.computeWorldMatrix(true);
  89890. break;
  89891. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89892. returnValue = new this.BJSCANNON.Particle();
  89893. break;
  89894. }
  89895. return returnValue;
  89896. };
  89897. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  89898. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89899. var transform = object.computeWorldMatrix(true);
  89900. // convert rawVerts to object space
  89901. var temp = new Array();
  89902. var index;
  89903. for (index = 0; index < pos.length; index += 3) {
  89904. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  89905. }
  89906. pos = temp;
  89907. var matrix = new Array();
  89908. //For now pointDepth will not be used and will be automatically calculated.
  89909. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  89910. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  89911. var boundingInfo = object.getBoundingInfo();
  89912. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  89913. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  89914. var elementSize = dim * 2 / arraySize;
  89915. for (var i = 0; i < pos.length; i = i + 3) {
  89916. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  89917. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  89918. var y = -pos[i + 2] + minY;
  89919. if (!matrix[x]) {
  89920. matrix[x] = [];
  89921. }
  89922. if (!matrix[x][z]) {
  89923. matrix[x][z] = y;
  89924. }
  89925. matrix[x][z] = Math.max(y, matrix[x][z]);
  89926. }
  89927. for (var x = 0; x <= arraySize; ++x) {
  89928. if (!matrix[x]) {
  89929. var loc = 1;
  89930. while (!matrix[(x + loc) % arraySize]) {
  89931. loc++;
  89932. }
  89933. matrix[x] = matrix[(x + loc) % arraySize].slice();
  89934. //console.log("missing x", x);
  89935. }
  89936. for (var z = 0; z <= arraySize; ++z) {
  89937. if (!matrix[x][z]) {
  89938. var loc = 1;
  89939. var newValue;
  89940. while (newValue === undefined) {
  89941. newValue = matrix[x][(z + loc++) % arraySize];
  89942. }
  89943. matrix[x][z] = newValue;
  89944. }
  89945. }
  89946. }
  89947. var shape = new this.BJSCANNON.Heightfield(matrix, {
  89948. elementSize: elementSize
  89949. });
  89950. //For future reference, needed for body transformation
  89951. shape.minY = minY;
  89952. return shape;
  89953. };
  89954. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  89955. var object = impostor.object;
  89956. //make sure it is updated...
  89957. object.computeWorldMatrix && object.computeWorldMatrix(true);
  89958. // The delta between the mesh position and the mesh bounding box center
  89959. var bInfo = object.getBoundingInfo();
  89960. if (!bInfo)
  89961. return;
  89962. var center = impostor.getObjectCenter();
  89963. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  89964. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  89965. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  89966. this._tmpPosition.copyFrom(center);
  89967. var quaternion = object.rotationQuaternion;
  89968. if (!quaternion) {
  89969. return;
  89970. }
  89971. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  89972. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  89973. //-90 DEG in X, precalculated
  89974. quaternion = quaternion.multiply(this._minus90X);
  89975. //Invert! (Precalculated, 90 deg in X)
  89976. //No need to clone. this will never change.
  89977. impostor.setDeltaRotation(this._plus90X);
  89978. }
  89979. //If it is a heightfield, if should be centered.
  89980. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  89981. var mesh = object;
  89982. var boundingInfo = mesh.getBoundingInfo();
  89983. //calculate the correct body position:
  89984. var rotationQuaternion = mesh.rotationQuaternion;
  89985. mesh.rotationQuaternion = this._tmpUnityRotation;
  89986. mesh.computeWorldMatrix(true);
  89987. //get original center with no rotation
  89988. var c = center.clone();
  89989. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  89990. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  89991. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  89992. mesh.setPreTransformMatrix(p);
  89993. mesh.computeWorldMatrix(true);
  89994. //calculate the translation
  89995. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  89996. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  89997. //add it inverted to the delta
  89998. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  89999. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  90000. //rotation is back
  90001. mesh.rotationQuaternion = rotationQuaternion;
  90002. mesh.setPreTransformMatrix(oldPivot);
  90003. mesh.computeWorldMatrix(true);
  90004. }
  90005. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  90006. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  90007. //this._tmpPosition.copyFrom(object.position);
  90008. }
  90009. impostor.setDeltaPosition(this._tmpDeltaPosition);
  90010. //Now update the impostor object
  90011. impostor.physicsBody.position.copy(this._tmpPosition);
  90012. impostor.physicsBody.quaternion.copy(quaternion);
  90013. };
  90014. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90015. impostor.object.position.copyFrom(impostor.physicsBody.position);
  90016. if (impostor.object.rotationQuaternion) {
  90017. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  90018. }
  90019. };
  90020. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90021. impostor.physicsBody.position.copy(newPosition);
  90022. impostor.physicsBody.quaternion.copy(newRotation);
  90023. };
  90024. CannonJSPlugin.prototype.isSupported = function () {
  90025. return this.BJSCANNON !== undefined;
  90026. };
  90027. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90028. impostor.physicsBody.velocity.copy(velocity);
  90029. };
  90030. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90031. impostor.physicsBody.angularVelocity.copy(velocity);
  90032. };
  90033. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90034. var v = impostor.physicsBody.velocity;
  90035. if (!v) {
  90036. return null;
  90037. }
  90038. return new BABYLON.Vector3(v.x, v.y, v.z);
  90039. };
  90040. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90041. var v = impostor.physicsBody.angularVelocity;
  90042. if (!v) {
  90043. return null;
  90044. }
  90045. return new BABYLON.Vector3(v.x, v.y, v.z);
  90046. };
  90047. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90048. impostor.physicsBody.mass = mass;
  90049. impostor.physicsBody.updateMassProperties();
  90050. };
  90051. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  90052. return impostor.physicsBody.mass;
  90053. };
  90054. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  90055. return impostor.physicsBody.material.friction;
  90056. };
  90057. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90058. impostor.physicsBody.material.friction = friction;
  90059. };
  90060. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90061. return impostor.physicsBody.material.restitution;
  90062. };
  90063. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90064. impostor.physicsBody.material.restitution = restitution;
  90065. };
  90066. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  90067. impostor.physicsBody.sleep();
  90068. };
  90069. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  90070. impostor.physicsBody.wakeUp();
  90071. };
  90072. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90073. joint.physicsJoint.distance = maxDistance;
  90074. };
  90075. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90076. // if (!motorIndex) {
  90077. // joint.physicsJoint.enableMotor();
  90078. // }
  90079. // }
  90080. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90081. // if (!motorIndex) {
  90082. // joint.physicsJoint.disableMotor();
  90083. // }
  90084. // }
  90085. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90086. if (!motorIndex) {
  90087. joint.physicsJoint.enableMotor();
  90088. joint.physicsJoint.setMotorSpeed(speed);
  90089. if (maxForce) {
  90090. this.setLimit(joint, maxForce);
  90091. }
  90092. }
  90093. };
  90094. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  90095. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  90096. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  90097. };
  90098. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90099. var body = impostor.physicsBody;
  90100. mesh.position.x = body.position.x;
  90101. mesh.position.y = body.position.y;
  90102. mesh.position.z = body.position.z;
  90103. if (mesh.rotationQuaternion) {
  90104. mesh.rotationQuaternion.x = body.quaternion.x;
  90105. mesh.rotationQuaternion.y = body.quaternion.y;
  90106. mesh.rotationQuaternion.z = body.quaternion.z;
  90107. mesh.rotationQuaternion.w = body.quaternion.w;
  90108. }
  90109. };
  90110. CannonJSPlugin.prototype.getRadius = function (impostor) {
  90111. var shape = impostor.physicsBody.shapes[0];
  90112. return shape.boundingSphereRadius;
  90113. };
  90114. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90115. var shape = impostor.physicsBody.shapes[0];
  90116. result.x = shape.halfExtents.x * 2;
  90117. result.y = shape.halfExtents.y * 2;
  90118. result.z = shape.halfExtents.z * 2;
  90119. };
  90120. CannonJSPlugin.prototype.dispose = function () {
  90121. };
  90122. CannonJSPlugin.prototype._extendNamespace = function () {
  90123. //this will force cannon to execute at least one step when using interpolation
  90124. var step_tmp1 = new this.BJSCANNON.Vec3();
  90125. var Engine = this.BJSCANNON;
  90126. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  90127. maxSubSteps = maxSubSteps || 10;
  90128. timeSinceLastCalled = timeSinceLastCalled || 0;
  90129. if (timeSinceLastCalled === 0) {
  90130. this.internalStep(dt);
  90131. this.time += dt;
  90132. }
  90133. else {
  90134. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  90135. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  90136. var t0 = performance.now();
  90137. for (var i = 0; i !== internalSteps; i++) {
  90138. this.internalStep(dt);
  90139. if (performance.now() - t0 > dt * 1000) {
  90140. break;
  90141. }
  90142. }
  90143. this.time += timeSinceLastCalled;
  90144. var h = this.time % dt;
  90145. var h_div_dt = h / dt;
  90146. var interpvelo = step_tmp1;
  90147. var bodies = this.bodies;
  90148. for (var j = 0; j !== bodies.length; j++) {
  90149. var b = bodies[j];
  90150. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  90151. b.position.vsub(b.previousPosition, interpvelo);
  90152. interpvelo.scale(h_div_dt, interpvelo);
  90153. b.position.vadd(interpvelo, b.interpolatedPosition);
  90154. }
  90155. else {
  90156. b.interpolatedPosition.copy(b.position);
  90157. b.interpolatedQuaternion.copy(b.quaternion);
  90158. }
  90159. }
  90160. }
  90161. };
  90162. };
  90163. return CannonJSPlugin;
  90164. }());
  90165. BABYLON.CannonJSPlugin = CannonJSPlugin;
  90166. })(BABYLON || (BABYLON = {}));
  90167. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  90168. var BABYLON;
  90169. (function (BABYLON) {
  90170. var OimoJSPlugin = /** @class */ (function () {
  90171. function OimoJSPlugin(iterations) {
  90172. this.name = "OimoJSPlugin";
  90173. this._tmpImpostorsArray = [];
  90174. this._tmpPositionVector = BABYLON.Vector3.Zero();
  90175. this.BJSOIMO = OIMO;
  90176. this.world = new this.BJSOIMO.World({
  90177. iterations: iterations
  90178. });
  90179. this.world.clear();
  90180. }
  90181. OimoJSPlugin.prototype.setGravity = function (gravity) {
  90182. this.world.gravity.copy(gravity);
  90183. };
  90184. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  90185. this.world.timeStep = timeStep;
  90186. };
  90187. OimoJSPlugin.prototype.getTimeStep = function () {
  90188. return this.world.timeStep;
  90189. };
  90190. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  90191. var _this = this;
  90192. impostors.forEach(function (impostor) {
  90193. impostor.beforeStep();
  90194. });
  90195. this.world.step();
  90196. impostors.forEach(function (impostor) {
  90197. impostor.afterStep();
  90198. //update the ordered impostors array
  90199. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  90200. });
  90201. //check for collisions
  90202. var contact = this.world.contacts;
  90203. while (contact !== null) {
  90204. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  90205. contact = contact.next;
  90206. continue;
  90207. }
  90208. //is this body colliding with any other? get the impostor
  90209. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  90210. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  90211. if (!mainImpostor || !collidingImpostor) {
  90212. contact = contact.next;
  90213. continue;
  90214. }
  90215. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  90216. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  90217. contact = contact.next;
  90218. }
  90219. };
  90220. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90221. var mass = impostor.physicsBody.mass;
  90222. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  90223. };
  90224. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90225. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  90226. this.applyImpulse(impostor, force, contactPoint);
  90227. };
  90228. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90229. var _this = this;
  90230. //parent-child relationship. Does this impostor has a parent impostor?
  90231. if (impostor.parent) {
  90232. if (impostor.physicsBody) {
  90233. this.removePhysicsBody(impostor);
  90234. //TODO is that needed?
  90235. impostor.forceUpdate();
  90236. }
  90237. return;
  90238. }
  90239. if (impostor.isBodyInitRequired()) {
  90240. var bodyConfig = {
  90241. name: impostor.uniqueId,
  90242. //Oimo must have mass, also for static objects.
  90243. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  90244. size: [],
  90245. type: [],
  90246. pos: [],
  90247. posShape: [],
  90248. rot: [],
  90249. rotShape: [],
  90250. move: impostor.getParam("mass") !== 0,
  90251. density: impostor.getParam("mass"),
  90252. friction: impostor.getParam("friction"),
  90253. restitution: impostor.getParam("restitution"),
  90254. //Supporting older versions of Oimo
  90255. world: this.world
  90256. };
  90257. var impostors = [impostor];
  90258. var addToArray = function (parent) {
  90259. if (!parent.getChildMeshes)
  90260. return;
  90261. parent.getChildMeshes().forEach(function (m) {
  90262. if (m.physicsImpostor) {
  90263. impostors.push(m.physicsImpostor);
  90264. //m.physicsImpostor._init();
  90265. }
  90266. });
  90267. };
  90268. addToArray(impostor.object);
  90269. var checkWithEpsilon_1 = function (value) {
  90270. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  90271. };
  90272. var globalQuaternion_1 = new BABYLON.Quaternion();
  90273. impostors.forEach(function (i) {
  90274. if (!i.object.rotationQuaternion) {
  90275. return;
  90276. }
  90277. //get the correct bounding box
  90278. var oldQuaternion = i.object.rotationQuaternion;
  90279. globalQuaternion_1 = oldQuaternion.clone();
  90280. var rot = oldQuaternion.toEulerAngles();
  90281. var extendSize = i.getObjectExtendSize();
  90282. var radToDeg = 57.295779513082320876;
  90283. if (i === impostor) {
  90284. var center = impostor.getObjectCenter();
  90285. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  90286. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  90287. //Can also use Array.prototype.push.apply
  90288. bodyConfig.pos.push(center.x);
  90289. bodyConfig.pos.push(center.y);
  90290. bodyConfig.pos.push(center.z);
  90291. bodyConfig.posShape.push(0, 0, 0);
  90292. //tmp solution
  90293. bodyConfig.rot.push(0);
  90294. bodyConfig.rot.push(0);
  90295. bodyConfig.rot.push(0);
  90296. bodyConfig.rotShape.push(0, 0, 0);
  90297. }
  90298. else {
  90299. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  90300. bodyConfig.posShape.push(localPosition.x);
  90301. bodyConfig.posShape.push(localPosition.y);
  90302. bodyConfig.posShape.push(localPosition.z);
  90303. bodyConfig.pos.push(0, 0, 0);
  90304. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  90305. bodyConfig.rot.push(0);
  90306. bodyConfig.rot.push(0);
  90307. bodyConfig.rot.push(0);
  90308. bodyConfig.rotShape.push(rot.x * radToDeg);
  90309. bodyConfig.rotShape.push(rot.y * radToDeg);
  90310. bodyConfig.rotShape.push(rot.z * radToDeg);
  90311. }
  90312. // register mesh
  90313. switch (i.type) {
  90314. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90315. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  90316. case BABYLON.PhysicsImpostor.SphereImpostor:
  90317. var radiusX = extendSize.x;
  90318. var radiusY = extendSize.y;
  90319. var radiusZ = extendSize.z;
  90320. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  90321. bodyConfig.type.push('sphere');
  90322. //due to the way oimo works with compounds, add 3 times
  90323. bodyConfig.size.push(size);
  90324. bodyConfig.size.push(size);
  90325. bodyConfig.size.push(size);
  90326. break;
  90327. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90328. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  90329. var sizeY = checkWithEpsilon_1(extendSize.y);
  90330. bodyConfig.type.push('cylinder');
  90331. bodyConfig.size.push(sizeX);
  90332. bodyConfig.size.push(sizeY);
  90333. //due to the way oimo works with compounds, add one more value.
  90334. bodyConfig.size.push(sizeY);
  90335. break;
  90336. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90337. case BABYLON.PhysicsImpostor.BoxImpostor:
  90338. default:
  90339. var sizeX = checkWithEpsilon_1(extendSize.x);
  90340. var sizeY = checkWithEpsilon_1(extendSize.y);
  90341. var sizeZ = checkWithEpsilon_1(extendSize.z);
  90342. bodyConfig.type.push('box');
  90343. //if (i === impostor) {
  90344. bodyConfig.size.push(sizeX);
  90345. bodyConfig.size.push(sizeY);
  90346. bodyConfig.size.push(sizeZ);
  90347. //} else {
  90348. // bodyConfig.size.push(0,0,0);
  90349. //}
  90350. break;
  90351. }
  90352. //actually not needed, but hey...
  90353. i.object.rotationQuaternion = oldQuaternion;
  90354. });
  90355. impostor.physicsBody = this.world.add(bodyConfig);
  90356. // set the quaternion, ignoring the previously defined (euler) rotation
  90357. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  90358. // update with delta 0, so the body will reveive the new rotation.
  90359. impostor.physicsBody.updatePosition(0);
  90360. }
  90361. else {
  90362. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  90363. }
  90364. impostor.setDeltaPosition(this._tmpPositionVector);
  90365. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  90366. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  90367. };
  90368. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90369. //impostor.physicsBody.dispose();
  90370. //Same as : (older oimo versions)
  90371. this.world.removeRigidBody(impostor.physicsBody);
  90372. };
  90373. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90374. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90375. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90376. if (!mainBody || !connectedBody) {
  90377. return;
  90378. }
  90379. var jointData = impostorJoint.joint.jointData;
  90380. var options = jointData.nativeParams || {};
  90381. var type;
  90382. var nativeJointData = {
  90383. body1: mainBody,
  90384. body2: connectedBody,
  90385. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  90386. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  90387. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  90388. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  90389. min: options.min,
  90390. max: options.max,
  90391. collision: options.collision || jointData.collision,
  90392. spring: options.spring,
  90393. //supporting older version of Oimo
  90394. world: this.world
  90395. };
  90396. switch (impostorJoint.joint.type) {
  90397. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90398. type = "jointBall";
  90399. break;
  90400. case BABYLON.PhysicsJoint.SpringJoint:
  90401. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  90402. var springData = jointData;
  90403. nativeJointData.min = springData.length || nativeJointData.min;
  90404. //Max should also be set, just make sure it is at least min
  90405. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  90406. case BABYLON.PhysicsJoint.DistanceJoint:
  90407. type = "jointDistance";
  90408. nativeJointData.max = jointData.maxDistance;
  90409. break;
  90410. case BABYLON.PhysicsJoint.PrismaticJoint:
  90411. type = "jointPrisme";
  90412. break;
  90413. case BABYLON.PhysicsJoint.SliderJoint:
  90414. type = "jointSlide";
  90415. break;
  90416. case BABYLON.PhysicsJoint.WheelJoint:
  90417. type = "jointWheel";
  90418. break;
  90419. case BABYLON.PhysicsJoint.HingeJoint:
  90420. default:
  90421. type = "jointHinge";
  90422. break;
  90423. }
  90424. nativeJointData.type = type;
  90425. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  90426. };
  90427. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90428. //Bug in Oimo prevents us from disposing a joint in the playground
  90429. //joint.joint.physicsJoint.dispose();
  90430. //So we will bruteforce it!
  90431. try {
  90432. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  90433. }
  90434. catch (e) {
  90435. BABYLON.Tools.Warn(e);
  90436. }
  90437. };
  90438. OimoJSPlugin.prototype.isSupported = function () {
  90439. return this.BJSOIMO !== undefined;
  90440. };
  90441. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90442. if (!impostor.physicsBody.sleeping) {
  90443. //TODO check that
  90444. /*if (impostor.physicsBody.shapes.next) {
  90445. var parentShape = this._getLastShape(impostor.physicsBody);
  90446. impostor.object.position.copyFrom(parentShape.position);
  90447. console.log(parentShape.position);
  90448. } else {*/
  90449. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  90450. //}
  90451. if (impostor.object.rotationQuaternion) {
  90452. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  90453. }
  90454. }
  90455. };
  90456. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90457. var body = impostor.physicsBody;
  90458. body.position.copy(newPosition);
  90459. body.orientation.copy(newRotation);
  90460. body.syncShapes();
  90461. body.awake();
  90462. };
  90463. /*private _getLastShape(body: any): any {
  90464. var lastShape = body.shapes;
  90465. while (lastShape.next) {
  90466. lastShape = lastShape.next;
  90467. }
  90468. return lastShape;
  90469. }*/
  90470. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90471. impostor.physicsBody.linearVelocity.copy(velocity);
  90472. };
  90473. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90474. impostor.physicsBody.angularVelocity.copy(velocity);
  90475. };
  90476. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90477. var v = impostor.physicsBody.linearVelocity;
  90478. if (!v) {
  90479. return null;
  90480. }
  90481. return new BABYLON.Vector3(v.x, v.y, v.z);
  90482. };
  90483. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90484. var v = impostor.physicsBody.angularVelocity;
  90485. if (!v) {
  90486. return null;
  90487. }
  90488. return new BABYLON.Vector3(v.x, v.y, v.z);
  90489. };
  90490. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90491. var staticBody = mass === 0;
  90492. //this will actually set the body's density and not its mass.
  90493. //But this is how oimo treats the mass variable.
  90494. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  90495. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  90496. };
  90497. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  90498. return impostor.physicsBody.shapes.density;
  90499. };
  90500. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  90501. return impostor.physicsBody.shapes.friction;
  90502. };
  90503. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90504. impostor.physicsBody.shapes.friction = friction;
  90505. };
  90506. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90507. return impostor.physicsBody.shapes.restitution;
  90508. };
  90509. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90510. impostor.physicsBody.shapes.restitution = restitution;
  90511. };
  90512. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  90513. impostor.physicsBody.sleep();
  90514. };
  90515. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  90516. impostor.physicsBody.awake();
  90517. };
  90518. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90519. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  90520. if (minDistance !== void 0) {
  90521. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  90522. }
  90523. };
  90524. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90525. //TODO separate rotational and transational motors.
  90526. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90527. if (motor) {
  90528. motor.setMotor(speed, maxForce);
  90529. }
  90530. };
  90531. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  90532. //TODO separate rotational and transational motors.
  90533. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90534. if (motor) {
  90535. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  90536. }
  90537. };
  90538. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90539. var body = impostor.physicsBody;
  90540. mesh.position.x = body.position.x;
  90541. mesh.position.y = body.position.y;
  90542. mesh.position.z = body.position.z;
  90543. if (mesh.rotationQuaternion) {
  90544. mesh.rotationQuaternion.x = body.orientation.x;
  90545. mesh.rotationQuaternion.y = body.orientation.y;
  90546. mesh.rotationQuaternion.z = body.orientation.z;
  90547. mesh.rotationQuaternion.w = body.orientation.s;
  90548. }
  90549. };
  90550. OimoJSPlugin.prototype.getRadius = function (impostor) {
  90551. return impostor.physicsBody.shapes.radius;
  90552. };
  90553. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90554. var shape = impostor.physicsBody.shapes;
  90555. result.x = shape.halfWidth * 2;
  90556. result.y = shape.halfHeight * 2;
  90557. result.z = shape.halfDepth * 2;
  90558. };
  90559. OimoJSPlugin.prototype.dispose = function () {
  90560. this.world.clear();
  90561. };
  90562. return OimoJSPlugin;
  90563. }());
  90564. BABYLON.OimoJSPlugin = OimoJSPlugin;
  90565. })(BABYLON || (BABYLON = {}));
  90566. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  90567. var BABYLON;
  90568. (function (BABYLON) {
  90569. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  90570. // All values and structures referenced from:
  90571. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  90572. var DDS_MAGIC = 0x20534444;
  90573. var
  90574. //DDSD_CAPS = 0x1,
  90575. //DDSD_HEIGHT = 0x2,
  90576. //DDSD_WIDTH = 0x4,
  90577. //DDSD_PITCH = 0x8,
  90578. //DDSD_PIXELFORMAT = 0x1000,
  90579. DDSD_MIPMAPCOUNT = 0x20000;
  90580. //DDSD_LINEARSIZE = 0x80000,
  90581. //DDSD_DEPTH = 0x800000;
  90582. // var DDSCAPS_COMPLEX = 0x8,
  90583. // DDSCAPS_MIPMAP = 0x400000,
  90584. // DDSCAPS_TEXTURE = 0x1000;
  90585. var DDSCAPS2_CUBEMAP = 0x200;
  90586. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  90587. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  90588. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  90589. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  90590. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  90591. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  90592. // DDSCAPS2_VOLUME = 0x200000;
  90593. var
  90594. //DDPF_ALPHAPIXELS = 0x1,
  90595. //DDPF_ALPHA = 0x2,
  90596. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  90597. //DDPF_YUV = 0x200,
  90598. DDPF_LUMINANCE = 0x20000;
  90599. function FourCCToInt32(value) {
  90600. return value.charCodeAt(0) +
  90601. (value.charCodeAt(1) << 8) +
  90602. (value.charCodeAt(2) << 16) +
  90603. (value.charCodeAt(3) << 24);
  90604. }
  90605. function Int32ToFourCC(value) {
  90606. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  90607. }
  90608. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  90609. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  90610. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  90611. var FOURCC_DX10 = FourCCToInt32("DX10");
  90612. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  90613. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  90614. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  90615. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  90616. var headerLengthInt = 31; // The header length in 32 bit ints
  90617. // Offsets into the header array
  90618. var off_magic = 0;
  90619. var off_size = 1;
  90620. var off_flags = 2;
  90621. var off_height = 3;
  90622. var off_width = 4;
  90623. var off_mipmapCount = 7;
  90624. var off_pfFlags = 20;
  90625. var off_pfFourCC = 21;
  90626. var off_RGBbpp = 22;
  90627. var off_RMask = 23;
  90628. var off_GMask = 24;
  90629. var off_BMask = 25;
  90630. var off_AMask = 26;
  90631. // var off_caps1 = 27;
  90632. var off_caps2 = 28;
  90633. // var off_caps3 = 29;
  90634. // var off_caps4 = 30;
  90635. var off_dxgiFormat = 32;
  90636. ;
  90637. var DDSTools = /** @class */ (function () {
  90638. function DDSTools() {
  90639. }
  90640. DDSTools.GetDDSInfo = function (arrayBuffer) {
  90641. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90642. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  90643. var mipmapCount = 1;
  90644. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  90645. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90646. }
  90647. var fourCC = header[off_pfFourCC];
  90648. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  90649. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90650. switch (fourCC) {
  90651. case FOURCC_D3DFMT_R16G16B16A16F:
  90652. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90653. break;
  90654. case FOURCC_D3DFMT_R32G32B32A32F:
  90655. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90656. break;
  90657. case FOURCC_DX10:
  90658. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  90659. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90660. break;
  90661. }
  90662. }
  90663. return {
  90664. width: header[off_width],
  90665. height: header[off_height],
  90666. mipmapCount: mipmapCount,
  90667. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  90668. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  90669. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  90670. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  90671. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  90672. dxgiFormat: dxgiFormat,
  90673. textureType: textureType
  90674. };
  90675. };
  90676. DDSTools._ToHalfFloat = function (value) {
  90677. if (!DDSTools._FloatView) {
  90678. DDSTools._FloatView = new Float32Array(1);
  90679. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  90680. }
  90681. DDSTools._FloatView[0] = value;
  90682. var x = DDSTools._Int32View[0];
  90683. var bits = (x >> 16) & 0x8000; /* Get the sign */
  90684. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  90685. var e = (x >> 23) & 0xff; /* Using int is faster here */
  90686. /* If zero, or denormal, or exponent underflows too much for a denormal
  90687. * half, return signed zero. */
  90688. if (e < 103) {
  90689. return bits;
  90690. }
  90691. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  90692. if (e > 142) {
  90693. bits |= 0x7c00;
  90694. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  90695. * not Inf, so make sure we set one mantissa bit too. */
  90696. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  90697. return bits;
  90698. }
  90699. /* If exponent underflows but not too much, return a denormal */
  90700. if (e < 113) {
  90701. m |= 0x0800;
  90702. /* Extra rounding may overflow and set mantissa to 0 and exponent
  90703. * to 1, which is OK. */
  90704. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  90705. return bits;
  90706. }
  90707. bits |= ((e - 112) << 10) | (m >> 1);
  90708. bits += m & 1;
  90709. return bits;
  90710. };
  90711. DDSTools._FromHalfFloat = function (value) {
  90712. var s = (value & 0x8000) >> 15;
  90713. var e = (value & 0x7C00) >> 10;
  90714. var f = value & 0x03FF;
  90715. if (e === 0) {
  90716. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  90717. }
  90718. else if (e == 0x1F) {
  90719. return f ? NaN : ((s ? -1 : 1) * Infinity);
  90720. }
  90721. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  90722. };
  90723. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90724. var destArray = new Float32Array(dataLength);
  90725. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90726. var index = 0;
  90727. for (var y = 0; y < height; y++) {
  90728. for (var x = 0; x < width; x++) {
  90729. var srcPos = (x + y * width) * 4;
  90730. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  90731. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  90732. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  90733. if (DDSTools.StoreLODInAlphaChannel) {
  90734. destArray[index + 3] = lod;
  90735. }
  90736. else {
  90737. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  90738. }
  90739. index += 4;
  90740. }
  90741. }
  90742. return destArray;
  90743. };
  90744. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90745. if (DDSTools.StoreLODInAlphaChannel) {
  90746. var destArray = new Uint16Array(dataLength);
  90747. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90748. var index = 0;
  90749. for (var y = 0; y < height; y++) {
  90750. for (var x = 0; x < width; x++) {
  90751. var srcPos = (x + y * width) * 4;
  90752. destArray[index] = srcData[srcPos];
  90753. destArray[index + 1] = srcData[srcPos + 1];
  90754. destArray[index + 2] = srcData[srcPos + 2];
  90755. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  90756. index += 4;
  90757. }
  90758. }
  90759. return destArray;
  90760. }
  90761. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  90762. };
  90763. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90764. if (DDSTools.StoreLODInAlphaChannel) {
  90765. var destArray = new Float32Array(dataLength);
  90766. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90767. var index = 0;
  90768. for (var y = 0; y < height; y++) {
  90769. for (var x = 0; x < width; x++) {
  90770. var srcPos = (x + y * width) * 4;
  90771. destArray[index] = srcData[srcPos];
  90772. destArray[index + 1] = srcData[srcPos + 1];
  90773. destArray[index + 2] = srcData[srcPos + 2];
  90774. destArray[index + 3] = lod;
  90775. index += 4;
  90776. }
  90777. }
  90778. return destArray;
  90779. }
  90780. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  90781. };
  90782. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90783. var destArray = new Uint8Array(dataLength);
  90784. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90785. var index = 0;
  90786. for (var y = 0; y < height; y++) {
  90787. for (var x = 0; x < width; x++) {
  90788. var srcPos = (x + y * width) * 4;
  90789. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  90790. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  90791. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  90792. if (DDSTools.StoreLODInAlphaChannel) {
  90793. destArray[index + 3] = lod;
  90794. }
  90795. else {
  90796. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  90797. }
  90798. index += 4;
  90799. }
  90800. }
  90801. return destArray;
  90802. };
  90803. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90804. var destArray = new Uint8Array(dataLength);
  90805. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90806. var index = 0;
  90807. for (var y = 0; y < height; y++) {
  90808. for (var x = 0; x < width; x++) {
  90809. var srcPos = (x + y * width) * 4;
  90810. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  90811. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  90812. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  90813. if (DDSTools.StoreLODInAlphaChannel) {
  90814. destArray[index + 3] = lod;
  90815. }
  90816. else {
  90817. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  90818. }
  90819. index += 4;
  90820. }
  90821. }
  90822. return destArray;
  90823. };
  90824. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  90825. var byteArray = new Uint8Array(dataLength);
  90826. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90827. var index = 0;
  90828. for (var y = 0; y < height; y++) {
  90829. for (var x = 0; x < width; x++) {
  90830. var srcPos = (x + y * width) * 4;
  90831. byteArray[index] = srcData[srcPos + rOffset];
  90832. byteArray[index + 1] = srcData[srcPos + gOffset];
  90833. byteArray[index + 2] = srcData[srcPos + bOffset];
  90834. byteArray[index + 3] = srcData[srcPos + aOffset];
  90835. index += 4;
  90836. }
  90837. }
  90838. return byteArray;
  90839. };
  90840. DDSTools._ExtractLongWordOrder = function (value) {
  90841. if (value === 0 || value === 255 || value === -16777216) {
  90842. return 0;
  90843. }
  90844. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  90845. };
  90846. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  90847. var byteArray = new Uint8Array(dataLength);
  90848. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90849. var index = 0;
  90850. for (var y = 0; y < height; y++) {
  90851. for (var x = 0; x < width; x++) {
  90852. var srcPos = (x + y * width) * 3;
  90853. byteArray[index] = srcData[srcPos + rOffset];
  90854. byteArray[index + 1] = srcData[srcPos + gOffset];
  90855. byteArray[index + 2] = srcData[srcPos + bOffset];
  90856. index += 3;
  90857. }
  90858. }
  90859. return byteArray;
  90860. };
  90861. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  90862. var byteArray = new Uint8Array(dataLength);
  90863. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90864. var index = 0;
  90865. for (var y = 0; y < height; y++) {
  90866. for (var x = 0; x < width; x++) {
  90867. var srcPos = (x + y * width);
  90868. byteArray[index] = srcData[srcPos];
  90869. index++;
  90870. }
  90871. }
  90872. return byteArray;
  90873. };
  90874. /**
  90875. * Uploads DDS Levels to a Babylon Texture
  90876. * @hidden
  90877. */
  90878. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  90879. if (lodIndex === void 0) { lodIndex = -1; }
  90880. var sphericalPolynomialFaces = null;
  90881. if (info.sphericalPolynomial) {
  90882. sphericalPolynomialFaces = new Array();
  90883. }
  90884. var ext = engine.getCaps().s3tc;
  90885. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90886. var fourCC, width, height, dataLength = 0, dataOffset;
  90887. var byteArray, mipmapCount, mip;
  90888. var internalCompressedFormat = 0;
  90889. var blockBytes = 1;
  90890. if (header[off_magic] !== DDS_MAGIC) {
  90891. BABYLON.Tools.Error("Invalid magic number in DDS header");
  90892. return;
  90893. }
  90894. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  90895. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  90896. return;
  90897. }
  90898. if (info.isCompressed && !ext) {
  90899. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  90900. return;
  90901. }
  90902. var bpp = header[off_RGBbpp];
  90903. dataOffset = header[off_size] + 4;
  90904. var computeFormats = false;
  90905. if (info.isFourCC) {
  90906. fourCC = header[off_pfFourCC];
  90907. switch (fourCC) {
  90908. case FOURCC_DXT1:
  90909. blockBytes = 8;
  90910. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  90911. break;
  90912. case FOURCC_DXT3:
  90913. blockBytes = 16;
  90914. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  90915. break;
  90916. case FOURCC_DXT5:
  90917. blockBytes = 16;
  90918. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  90919. break;
  90920. case FOURCC_D3DFMT_R16G16B16A16F:
  90921. computeFormats = true;
  90922. break;
  90923. case FOURCC_D3DFMT_R32G32B32A32F:
  90924. computeFormats = true;
  90925. break;
  90926. case FOURCC_DX10:
  90927. // There is an additionnal header so dataOffset need to be changed
  90928. dataOffset += 5 * 4; // 5 uints
  90929. var supported = false;
  90930. switch (info.dxgiFormat) {
  90931. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  90932. computeFormats = true;
  90933. supported = true;
  90934. break;
  90935. case DXGI_FORMAT_B8G8R8X8_UNORM:
  90936. info.isRGB = true;
  90937. info.isFourCC = false;
  90938. bpp = 32;
  90939. supported = true;
  90940. break;
  90941. }
  90942. if (supported) {
  90943. break;
  90944. }
  90945. default:
  90946. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  90947. return;
  90948. }
  90949. }
  90950. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  90951. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  90952. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  90953. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  90954. if (computeFormats) {
  90955. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  90956. }
  90957. mipmapCount = 1;
  90958. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  90959. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90960. }
  90961. for (var face = 0; face < faces; face++) {
  90962. width = header[off_width];
  90963. height = header[off_height];
  90964. for (mip = 0; mip < mipmapCount; ++mip) {
  90965. if (lodIndex === -1 || lodIndex === mip) {
  90966. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  90967. var i = (lodIndex === -1) ? mip : 0;
  90968. if (!info.isCompressed && info.isFourCC) {
  90969. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90970. dataLength = width * height * 4;
  90971. var floatArray = null;
  90972. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  90973. if (bpp === 128) {
  90974. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90975. if (sphericalPolynomialFaces && i == 0) {
  90976. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90977. }
  90978. }
  90979. else if (bpp === 64) {
  90980. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90981. if (sphericalPolynomialFaces && i == 0) {
  90982. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90983. }
  90984. }
  90985. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90986. }
  90987. else {
  90988. if (bpp === 128) {
  90989. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90990. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90991. if (sphericalPolynomialFaces && i == 0) {
  90992. sphericalPolynomialFaces.push(floatArray);
  90993. }
  90994. }
  90995. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  90996. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90997. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90998. if (sphericalPolynomialFaces && i == 0) {
  90999. sphericalPolynomialFaces.push(floatArray);
  91000. }
  91001. }
  91002. else { // 64
  91003. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91004. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91005. if (sphericalPolynomialFaces && i == 0) {
  91006. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91007. }
  91008. }
  91009. }
  91010. if (floatArray) {
  91011. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  91012. }
  91013. }
  91014. else if (info.isRGB) {
  91015. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91016. if (bpp === 24) {
  91017. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  91018. dataLength = width * height * 3;
  91019. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  91020. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91021. }
  91022. else { // 32
  91023. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91024. dataLength = width * height * 4;
  91025. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  91026. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91027. }
  91028. }
  91029. else if (info.isLuminance) {
  91030. var unpackAlignment = engine._getUnpackAlignement();
  91031. var unpaddedRowSize = width;
  91032. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  91033. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  91034. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  91035. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  91036. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91037. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91038. }
  91039. else {
  91040. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  91041. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  91042. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91043. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  91044. }
  91045. }
  91046. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  91047. width *= 0.5;
  91048. height *= 0.5;
  91049. width = Math.max(1.0, width);
  91050. height = Math.max(1.0, height);
  91051. }
  91052. if (currentFace !== undefined) {
  91053. // Loading a single face
  91054. break;
  91055. }
  91056. }
  91057. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  91058. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  91059. size: header[off_width],
  91060. right: sphericalPolynomialFaces[0],
  91061. left: sphericalPolynomialFaces[1],
  91062. up: sphericalPolynomialFaces[2],
  91063. down: sphericalPolynomialFaces[3],
  91064. front: sphericalPolynomialFaces[4],
  91065. back: sphericalPolynomialFaces[5],
  91066. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  91067. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91068. gammaSpace: false,
  91069. });
  91070. }
  91071. else {
  91072. info.sphericalPolynomial = undefined;
  91073. }
  91074. };
  91075. DDSTools.StoreLODInAlphaChannel = false;
  91076. return DDSTools;
  91077. }());
  91078. BABYLON.DDSTools = DDSTools;
  91079. })(BABYLON || (BABYLON = {}));
  91080. //# sourceMappingURL=babylon.dds.js.map
  91081. var BABYLON;
  91082. (function (BABYLON) {
  91083. /**
  91084. * Implementation of the DDS Texture Loader.
  91085. */
  91086. var DDSTextureLoader = /** @class */ (function () {
  91087. function DDSTextureLoader() {
  91088. /**
  91089. * Defines wether the loader supports cascade loading the different faces.
  91090. */
  91091. this.supportCascades = true;
  91092. }
  91093. /**
  91094. * This returns if the loader support the current file information.
  91095. * @param extension defines the file extension of the file being loaded
  91096. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91097. * @param fallback defines the fallback internal texture if any
  91098. * @param isBase64 defines whether the texture is encoded as a base64
  91099. * @param isBuffer defines whether the texture data are stored as a buffer
  91100. * @returns true if the loader can load the specified file
  91101. */
  91102. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91103. return extension.indexOf(".dds") === 0;
  91104. };
  91105. /**
  91106. * Transform the url before loading if required.
  91107. * @param rootUrl the url of the texture
  91108. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91109. * @returns the transformed texture
  91110. */
  91111. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91112. return rootUrl;
  91113. };
  91114. /**
  91115. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91116. * @param rootUrl the url of the texture
  91117. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91118. * @returns the fallback texture
  91119. */
  91120. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91121. return null;
  91122. };
  91123. /**
  91124. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91125. * @param data contains the texture data
  91126. * @param texture defines the BabylonJS internal texture
  91127. * @param createPolynomials will be true if polynomials have been requested
  91128. * @param onLoad defines the callback to trigger once the texture is ready
  91129. * @param onError defines the callback to trigger in case of error
  91130. */
  91131. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  91132. var engine = texture.getEngine();
  91133. var info;
  91134. var loadMipmap = false;
  91135. if (Array.isArray(imgs)) {
  91136. for (var index = 0; index < imgs.length; index++) {
  91137. var data_1 = imgs[index];
  91138. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  91139. texture.width = info.width;
  91140. texture.height = info.height;
  91141. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91142. engine._unpackFlipY(info.isCompressed);
  91143. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  91144. if (!info.isFourCC && info.mipmapCount === 1) {
  91145. engine.generateMipMapsForCubemap(texture);
  91146. }
  91147. }
  91148. }
  91149. else {
  91150. var data = imgs;
  91151. info = BABYLON.DDSTools.GetDDSInfo(data);
  91152. texture.width = info.width;
  91153. texture.height = info.height;
  91154. if (createPolynomials) {
  91155. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  91156. }
  91157. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91158. engine._unpackFlipY(info.isCompressed);
  91159. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  91160. if (!info.isFourCC && info.mipmapCount === 1) {
  91161. engine.generateMipMapsForCubemap(texture);
  91162. }
  91163. }
  91164. engine._setCubeMapTextureParams(loadMipmap);
  91165. texture.isReady = true;
  91166. if (onLoad) {
  91167. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  91168. }
  91169. };
  91170. /**
  91171. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91172. * @param data contains the texture data
  91173. * @param texture defines the BabylonJS internal texture
  91174. * @param callback defines the method to call once ready to upload
  91175. */
  91176. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  91177. var info = BABYLON.DDSTools.GetDDSInfo(data);
  91178. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  91179. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  91180. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  91181. });
  91182. };
  91183. return DDSTextureLoader;
  91184. }());
  91185. // Register the loader.
  91186. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  91187. })(BABYLON || (BABYLON = {}));
  91188. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  91189. var BABYLON;
  91190. (function (BABYLON) {
  91191. /*
  91192. * Based on jsTGALoader - Javascript loader for TGA file
  91193. * By Vincent Thibault
  91194. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  91195. */
  91196. var TGATools = /** @class */ (function () {
  91197. function TGATools() {
  91198. }
  91199. TGATools.GetTGAHeader = function (data) {
  91200. var offset = 0;
  91201. var header = {
  91202. id_length: data[offset++],
  91203. colormap_type: data[offset++],
  91204. image_type: data[offset++],
  91205. colormap_index: data[offset++] | data[offset++] << 8,
  91206. colormap_length: data[offset++] | data[offset++] << 8,
  91207. colormap_size: data[offset++],
  91208. origin: [
  91209. data[offset++] | data[offset++] << 8,
  91210. data[offset++] | data[offset++] << 8
  91211. ],
  91212. width: data[offset++] | data[offset++] << 8,
  91213. height: data[offset++] | data[offset++] << 8,
  91214. pixel_size: data[offset++],
  91215. flags: data[offset++]
  91216. };
  91217. return header;
  91218. };
  91219. /**
  91220. * Uploads TGA content to a Babylon Texture
  91221. * @hidden
  91222. */
  91223. TGATools.UploadContent = function (texture, data) {
  91224. // Not enough data to contain header ?
  91225. if (data.length < 19) {
  91226. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  91227. return;
  91228. }
  91229. // Read Header
  91230. var offset = 18;
  91231. var header = TGATools.GetTGAHeader(data);
  91232. // Assume it's a valid Targa file.
  91233. if (header.id_length + offset > data.length) {
  91234. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  91235. return;
  91236. }
  91237. // Skip not needed data
  91238. offset += header.id_length;
  91239. var use_rle = false;
  91240. var use_pal = false;
  91241. var use_grey = false;
  91242. // Get some informations.
  91243. switch (header.image_type) {
  91244. case TGATools._TYPE_RLE_INDEXED:
  91245. use_rle = true;
  91246. case TGATools._TYPE_INDEXED:
  91247. use_pal = true;
  91248. break;
  91249. case TGATools._TYPE_RLE_RGB:
  91250. use_rle = true;
  91251. case TGATools._TYPE_RGB:
  91252. // use_rgb = true;
  91253. break;
  91254. case TGATools._TYPE_RLE_GREY:
  91255. use_rle = true;
  91256. case TGATools._TYPE_GREY:
  91257. use_grey = true;
  91258. break;
  91259. }
  91260. var pixel_data;
  91261. // var numAlphaBits = header.flags & 0xf;
  91262. var pixel_size = header.pixel_size >> 3;
  91263. var pixel_total = header.width * header.height * pixel_size;
  91264. // Read palettes
  91265. var palettes;
  91266. if (use_pal) {
  91267. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  91268. }
  91269. // Read LRE
  91270. if (use_rle) {
  91271. pixel_data = new Uint8Array(pixel_total);
  91272. var c, count, i;
  91273. var localOffset = 0;
  91274. var pixels = new Uint8Array(pixel_size);
  91275. while (offset < pixel_total && localOffset < pixel_total) {
  91276. c = data[offset++];
  91277. count = (c & 0x7f) + 1;
  91278. // RLE pixels
  91279. if (c & 0x80) {
  91280. // Bind pixel tmp array
  91281. for (i = 0; i < pixel_size; ++i) {
  91282. pixels[i] = data[offset++];
  91283. }
  91284. // Copy pixel array
  91285. for (i = 0; i < count; ++i) {
  91286. pixel_data.set(pixels, localOffset + i * pixel_size);
  91287. }
  91288. localOffset += pixel_size * count;
  91289. }
  91290. // Raw pixels
  91291. else {
  91292. count *= pixel_size;
  91293. for (i = 0; i < count; ++i) {
  91294. pixel_data[localOffset + i] = data[offset++];
  91295. }
  91296. localOffset += count;
  91297. }
  91298. }
  91299. }
  91300. // RAW Pixels
  91301. else {
  91302. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  91303. }
  91304. // Load to texture
  91305. var x_start, y_start, x_step, y_step, y_end, x_end;
  91306. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  91307. default:
  91308. case TGATools._ORIGIN_UL:
  91309. x_start = 0;
  91310. x_step = 1;
  91311. x_end = header.width;
  91312. y_start = 0;
  91313. y_step = 1;
  91314. y_end = header.height;
  91315. break;
  91316. case TGATools._ORIGIN_BL:
  91317. x_start = 0;
  91318. x_step = 1;
  91319. x_end = header.width;
  91320. y_start = header.height - 1;
  91321. y_step = -1;
  91322. y_end = -1;
  91323. break;
  91324. case TGATools._ORIGIN_UR:
  91325. x_start = header.width - 1;
  91326. x_step = -1;
  91327. x_end = -1;
  91328. y_start = 0;
  91329. y_step = 1;
  91330. y_end = header.height;
  91331. break;
  91332. case TGATools._ORIGIN_BR:
  91333. x_start = header.width - 1;
  91334. x_step = -1;
  91335. x_end = -1;
  91336. y_start = header.height - 1;
  91337. y_step = -1;
  91338. y_end = -1;
  91339. break;
  91340. }
  91341. // Load the specify method
  91342. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  91343. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  91344. var engine = texture.getEngine();
  91345. engine._uploadDataToTextureDirectly(texture, imageData);
  91346. };
  91347. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91348. var image = pixel_data, colormap = palettes;
  91349. var width = header.width, height = header.height;
  91350. var color, i = 0, x, y;
  91351. var imageData = new Uint8Array(width * height * 4);
  91352. for (y = y_start; y !== y_end; y += y_step) {
  91353. for (x = x_start; x !== x_end; x += x_step, i++) {
  91354. color = image[i];
  91355. imageData[(x + width * y) * 4 + 3] = 255;
  91356. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  91357. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  91358. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  91359. }
  91360. }
  91361. return imageData;
  91362. };
  91363. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91364. var image = pixel_data;
  91365. var width = header.width, height = header.height;
  91366. var color, i = 0, x, y;
  91367. var imageData = new Uint8Array(width * height * 4);
  91368. for (y = y_start; y !== y_end; y += y_step) {
  91369. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91370. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  91371. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  91372. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  91373. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  91374. imageData[(x + width * y) * 4 + 0] = r;
  91375. imageData[(x + width * y) * 4 + 1] = g;
  91376. imageData[(x + width * y) * 4 + 2] = b;
  91377. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  91378. }
  91379. }
  91380. return imageData;
  91381. };
  91382. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91383. var image = pixel_data;
  91384. var width = header.width, height = header.height;
  91385. var i = 0, x, y;
  91386. var imageData = new Uint8Array(width * height * 4);
  91387. for (y = y_start; y !== y_end; y += y_step) {
  91388. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  91389. imageData[(x + width * y) * 4 + 3] = 255;
  91390. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91391. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91392. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91393. }
  91394. }
  91395. return imageData;
  91396. };
  91397. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91398. var image = pixel_data;
  91399. var width = header.width, height = header.height;
  91400. var i = 0, x, y;
  91401. var imageData = new Uint8Array(width * height * 4);
  91402. for (y = y_start; y !== y_end; y += y_step) {
  91403. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  91404. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91405. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91406. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91407. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  91408. }
  91409. }
  91410. return imageData;
  91411. };
  91412. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91413. var image = pixel_data;
  91414. var width = header.width, height = header.height;
  91415. var color, i = 0, x, y;
  91416. var imageData = new Uint8Array(width * height * 4);
  91417. for (y = y_start; y !== y_end; y += y_step) {
  91418. for (x = x_start; x !== x_end; x += x_step, i++) {
  91419. color = image[i];
  91420. imageData[(x + width * y) * 4 + 0] = color;
  91421. imageData[(x + width * y) * 4 + 1] = color;
  91422. imageData[(x + width * y) * 4 + 2] = color;
  91423. imageData[(x + width * y) * 4 + 3] = 255;
  91424. }
  91425. }
  91426. return imageData;
  91427. };
  91428. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91429. var image = pixel_data;
  91430. var width = header.width, height = header.height;
  91431. var i = 0, x, y;
  91432. var imageData = new Uint8Array(width * height * 4);
  91433. for (y = y_start; y !== y_end; y += y_step) {
  91434. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91435. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  91436. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  91437. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91438. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  91439. }
  91440. }
  91441. return imageData;
  91442. };
  91443. //private static _TYPE_NO_DATA = 0;
  91444. TGATools._TYPE_INDEXED = 1;
  91445. TGATools._TYPE_RGB = 2;
  91446. TGATools._TYPE_GREY = 3;
  91447. TGATools._TYPE_RLE_INDEXED = 9;
  91448. TGATools._TYPE_RLE_RGB = 10;
  91449. TGATools._TYPE_RLE_GREY = 11;
  91450. TGATools._ORIGIN_MASK = 0x30;
  91451. TGATools._ORIGIN_SHIFT = 0x04;
  91452. TGATools._ORIGIN_BL = 0x00;
  91453. TGATools._ORIGIN_BR = 0x01;
  91454. TGATools._ORIGIN_UL = 0x02;
  91455. TGATools._ORIGIN_UR = 0x03;
  91456. return TGATools;
  91457. }());
  91458. BABYLON.TGATools = TGATools;
  91459. })(BABYLON || (BABYLON = {}));
  91460. //# sourceMappingURL=babylon.tga.js.map
  91461. var BABYLON;
  91462. (function (BABYLON) {
  91463. /**
  91464. * Implementation of the TGA Texture Loader.
  91465. */
  91466. var TGATextureLoader = /** @class */ (function () {
  91467. function TGATextureLoader() {
  91468. /**
  91469. * Defines wether the loader supports cascade loading the different faces.
  91470. */
  91471. this.supportCascades = false;
  91472. }
  91473. /**
  91474. * This returns if the loader support the current file information.
  91475. * @param extension defines the file extension of the file being loaded
  91476. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91477. * @param fallback defines the fallback internal texture if any
  91478. * @param isBase64 defines whether the texture is encoded as a base64
  91479. * @param isBuffer defines whether the texture data are stored as a buffer
  91480. * @returns true if the loader can load the specified file
  91481. */
  91482. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91483. return extension.indexOf(".tga") === 0;
  91484. };
  91485. /**
  91486. * Transform the url before loading if required.
  91487. * @param rootUrl the url of the texture
  91488. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91489. * @returns the transformed texture
  91490. */
  91491. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91492. return rootUrl;
  91493. };
  91494. /**
  91495. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91496. * @param rootUrl the url of the texture
  91497. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91498. * @returns the fallback texture
  91499. */
  91500. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91501. return null;
  91502. };
  91503. /**
  91504. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91505. * @param data contains the texture data
  91506. * @param texture defines the BabylonJS internal texture
  91507. * @param createPolynomials will be true if polynomials have been requested
  91508. * @param onLoad defines the callback to trigger once the texture is ready
  91509. * @param onError defines the callback to trigger in case of error
  91510. */
  91511. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91512. throw ".env not supported in Cube.";
  91513. };
  91514. /**
  91515. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91516. * @param data contains the texture data
  91517. * @param texture defines the BabylonJS internal texture
  91518. * @param callback defines the method to call once ready to upload
  91519. */
  91520. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  91521. var uintData = new Uint8Array(data);
  91522. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  91523. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  91524. BABYLON.TGATools.UploadContent(texture, uintData);
  91525. });
  91526. };
  91527. return TGATextureLoader;
  91528. }());
  91529. // Register the loader.
  91530. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  91531. })(BABYLON || (BABYLON = {}));
  91532. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  91533. var BABYLON;
  91534. (function (BABYLON) {
  91535. /**
  91536. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  91537. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  91538. */
  91539. var KhronosTextureContainer = /** @class */ (function () {
  91540. /**
  91541. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  91542. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  91543. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  91544. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  91545. */
  91546. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  91547. this.arrayBuffer = arrayBuffer;
  91548. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  91549. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  91550. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  91551. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  91552. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  91553. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  91554. BABYLON.Tools.Error("texture missing KTX identifier");
  91555. return;
  91556. }
  91557. // load the reset of the header in native 32 bit int
  91558. var header = new Int32Array(this.arrayBuffer, 12, 13);
  91559. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  91560. var oppositeEndianess = header[0] === 0x01020304;
  91561. // read all the header elements in order they exist in the file, without modification (sans endainness)
  91562. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  91563. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  91564. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  91565. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  91566. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  91567. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  91568. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  91569. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  91570. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  91571. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  91572. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  91573. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  91574. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  91575. if (this.glType !== 0) {
  91576. BABYLON.Tools.Error("only compressed formats currently supported");
  91577. return;
  91578. }
  91579. else {
  91580. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  91581. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  91582. }
  91583. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  91584. BABYLON.Tools.Error("only 2D textures currently supported");
  91585. return;
  91586. }
  91587. if (this.numberOfArrayElements !== 0) {
  91588. BABYLON.Tools.Error("texture arrays not currently supported");
  91589. return;
  91590. }
  91591. if (this.numberOfFaces !== facesExpected) {
  91592. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  91593. return;
  91594. }
  91595. // we now have a completely validated file, so could use existence of loadType as success
  91596. // would need to make this more elaborate & adjust checks above to support more than one load type
  91597. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  91598. }
  91599. // not as fast hardware based, but will probably never need to use
  91600. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  91601. return ((val & 0xFF) << 24)
  91602. | ((val & 0xFF00) << 8)
  91603. | ((val >> 8) & 0xFF00)
  91604. | ((val >> 24) & 0xFF);
  91605. };
  91606. /**
  91607. * Uploads KTX content to a Babylon Texture.
  91608. * It is assumed that the texture has already been created & is currently bound
  91609. * @hidden
  91610. */
  91611. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  91612. switch (this.loadType) {
  91613. case KhronosTextureContainer.COMPRESSED_2D:
  91614. this._upload2DCompressedLevels(texture, loadMipmaps);
  91615. break;
  91616. case KhronosTextureContainer.TEX_2D:
  91617. case KhronosTextureContainer.COMPRESSED_3D:
  91618. case KhronosTextureContainer.TEX_3D:
  91619. }
  91620. };
  91621. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  91622. // initialize width & height for level 1
  91623. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  91624. var width = this.pixelWidth;
  91625. var height = this.pixelHeight;
  91626. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  91627. for (var level = 0; level < mipmapCount; level++) {
  91628. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  91629. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  91630. for (var face = 0; face < this.numberOfFaces; face++) {
  91631. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  91632. var engine = texture.getEngine();
  91633. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  91634. dataOffset += imageSize; // add size of the image for the next face/mipmap
  91635. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  91636. }
  91637. width = Math.max(1.0, width * 0.5);
  91638. height = Math.max(1.0, height * 0.5);
  91639. }
  91640. };
  91641. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  91642. // load types
  91643. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  91644. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  91645. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  91646. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  91647. return KhronosTextureContainer;
  91648. }());
  91649. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  91650. })(BABYLON || (BABYLON = {}));
  91651. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  91652. var BABYLON;
  91653. (function (BABYLON) {
  91654. /**
  91655. * Implementation of the KTX Texture Loader.
  91656. */
  91657. var KTXTextureLoader = /** @class */ (function () {
  91658. function KTXTextureLoader() {
  91659. /**
  91660. * Defines wether the loader supports cascade loading the different faces.
  91661. */
  91662. this.supportCascades = false;
  91663. }
  91664. /**
  91665. * This returns if the loader support the current file information.
  91666. * @param extension defines the file extension of the file being loaded
  91667. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91668. * @param fallback defines the fallback internal texture if any
  91669. * @param isBase64 defines whether the texture is encoded as a base64
  91670. * @param isBuffer defines whether the texture data are stored as a buffer
  91671. * @returns true if the loader can load the specified file
  91672. */
  91673. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91674. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  91675. return true;
  91676. }
  91677. return false;
  91678. };
  91679. /**
  91680. * Transform the url before loading if required.
  91681. * @param rootUrl the url of the texture
  91682. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91683. * @returns the transformed texture
  91684. */
  91685. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91686. var lastDot = rootUrl.lastIndexOf('.');
  91687. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  91688. };
  91689. /**
  91690. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91691. * @param rootUrl the url of the texture
  91692. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91693. * @returns the fallback texture
  91694. */
  91695. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91696. // remove the format appended to the rootUrl in the original createCubeTexture call.
  91697. var exp = new RegExp("" + textureFormatInUse + "$");
  91698. return rootUrl.replace(exp, "");
  91699. };
  91700. /**
  91701. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91702. * @param data contains the texture data
  91703. * @param texture defines the BabylonJS internal texture
  91704. * @param createPolynomials will be true if polynomials have been requested
  91705. * @param onLoad defines the callback to trigger once the texture is ready
  91706. * @param onError defines the callback to trigger in case of error
  91707. */
  91708. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91709. if (Array.isArray(data)) {
  91710. return;
  91711. }
  91712. var engine = texture.getEngine();
  91713. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  91714. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  91715. engine._unpackFlipY(true);
  91716. ktx.uploadLevels(texture, texture.generateMipMaps);
  91717. texture.width = ktx.pixelWidth;
  91718. texture.height = ktx.pixelHeight;
  91719. engine._setCubeMapTextureParams(loadMipmap);
  91720. texture.isReady = true;
  91721. };
  91722. /**
  91723. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91724. * @param data contains the texture data
  91725. * @param texture defines the BabylonJS internal texture
  91726. * @param callback defines the method to call once ready to upload
  91727. */
  91728. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  91729. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  91730. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  91731. ktx.uploadLevels(texture, texture.generateMipMaps);
  91732. });
  91733. };
  91734. return KTXTextureLoader;
  91735. }());
  91736. // Register the loader.
  91737. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  91738. })(BABYLON || (BABYLON = {}));
  91739. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  91740. var BABYLON;
  91741. (function (BABYLON) {
  91742. /**
  91743. * Sets of helpers addressing the serialization and deserialization of environment texture
  91744. * stored in a BabylonJS env file.
  91745. * Those files are usually stored as .env files.
  91746. */
  91747. var EnvironmentTextureTools = /** @class */ (function () {
  91748. function EnvironmentTextureTools() {
  91749. }
  91750. /**
  91751. * Gets the environment info from an env file.
  91752. * @param data The array buffer containing the .env bytes.
  91753. * @returns the environment file info (the json header) if successfully parsed.
  91754. */
  91755. EnvironmentTextureTools.GetEnvInfo = function (data) {
  91756. var dataView = new DataView(data);
  91757. var pos = 0;
  91758. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91759. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  91760. BABYLON.Tools.Error('Not a babylon environment map');
  91761. return null;
  91762. }
  91763. }
  91764. // Read json manifest - collect characters up to null terminator
  91765. var manifestString = '';
  91766. var charCode = 0x00;
  91767. while ((charCode = dataView.getUint8(pos++))) {
  91768. manifestString += String.fromCharCode(charCode);
  91769. }
  91770. var manifest = JSON.parse(manifestString);
  91771. if (manifest.specular) {
  91772. // Extend the header with the position of the payload.
  91773. manifest.specular.specularDataPosition = pos;
  91774. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  91775. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  91776. }
  91777. return manifest;
  91778. };
  91779. /**
  91780. * Creates an environment texture from a loaded cube texture.
  91781. * @param texture defines the cube texture to convert in env file
  91782. * @return a promise containing the environment data if succesfull.
  91783. */
  91784. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  91785. var _this = this;
  91786. var internalTexture = texture.getInternalTexture();
  91787. if (!internalTexture) {
  91788. return Promise.reject("The cube texture is invalid.");
  91789. }
  91790. if (!texture._prefiltered) {
  91791. return Promise.reject("The cube texture is invalid (not prefiltered).");
  91792. }
  91793. var engine = internalTexture.getEngine();
  91794. if (engine && engine.premultipliedAlpha) {
  91795. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  91796. }
  91797. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  91798. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  91799. }
  91800. var canvas = engine.getRenderingCanvas();
  91801. if (!canvas) {
  91802. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  91803. }
  91804. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91805. if (!engine.getCaps().textureFloatRender) {
  91806. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91807. if (!engine.getCaps().textureHalfFloatRender) {
  91808. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  91809. }
  91810. }
  91811. var cubeWidth = internalTexture.width;
  91812. var hostingScene = new BABYLON.Scene(engine);
  91813. var specularTextures = {};
  91814. var promises = [];
  91815. // Read and collect all mipmaps data from the cube.
  91816. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  91817. mipmapsCount = Math.round(mipmapsCount);
  91818. var _loop_1 = function (i) {
  91819. var faceWidth = Math.pow(2, mipmapsCount - i);
  91820. var _loop_2 = function (face) {
  91821. var data = texture.readPixels(face, i);
  91822. // Creates a temp texture with the face data.
  91823. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  91824. // And rgbdEncode them.
  91825. var promise = new Promise(function (resolve, reject) {
  91826. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  91827. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91828. rgbdPostProcess.onApply = function (effect) {
  91829. effect._bindTexture("textureSampler", tempTexture);
  91830. };
  91831. // As the process needs to happen on the main canvas, keep track of the current size
  91832. var currentW = engine.getRenderWidth();
  91833. var currentH = engine.getRenderHeight();
  91834. // Set the desired size for the texture
  91835. engine.setSize(faceWidth, faceWidth);
  91836. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  91837. // Reading datas from WebGL
  91838. BABYLON.Tools.ToBlob(canvas, function (blob) {
  91839. var fileReader = new FileReader();
  91840. fileReader.onload = function (event) {
  91841. var arrayBuffer = event.target.result;
  91842. specularTextures[i * 6 + face] = arrayBuffer;
  91843. resolve();
  91844. };
  91845. fileReader.readAsArrayBuffer(blob);
  91846. });
  91847. // Reapply the previous canvas size
  91848. engine.setSize(currentW, currentH);
  91849. });
  91850. });
  91851. promises.push(promise);
  91852. };
  91853. // All faces of the cube.
  91854. for (var face = 0; face < 6; face++) {
  91855. _loop_2(face);
  91856. }
  91857. };
  91858. for (var i = 0; i <= mipmapsCount; i++) {
  91859. _loop_1(i);
  91860. }
  91861. // Once all the textures haves been collected as RGBD stored in PNGs
  91862. return Promise.all(promises).then(function () {
  91863. // We can delete the hosting scene keeping track of all the creation objects
  91864. hostingScene.dispose();
  91865. // Creates the json header for the env texture
  91866. var info = {
  91867. version: 1,
  91868. width: cubeWidth,
  91869. irradiance: _this._CreateEnvTextureIrradiance(texture),
  91870. specular: {
  91871. mipmaps: [],
  91872. lodGenerationScale: texture.lodGenerationScale
  91873. }
  91874. };
  91875. // Sets the specular image data information
  91876. var position = 0;
  91877. for (var i = 0; i <= mipmapsCount; i++) {
  91878. for (var face = 0; face < 6; face++) {
  91879. var byteLength = specularTextures[i * 6 + face].byteLength;
  91880. info.specular.mipmaps.push({
  91881. length: byteLength,
  91882. position: position
  91883. });
  91884. position += byteLength;
  91885. }
  91886. }
  91887. // Encode the JSON as an array buffer
  91888. var infoString = JSON.stringify(info);
  91889. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  91890. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  91891. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  91892. infoView[i] = infoString.charCodeAt(i);
  91893. }
  91894. // Ends up with a null terminator for easier parsing
  91895. infoView[infoString.length] = 0x00;
  91896. // Computes the final required size and creates the storage
  91897. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  91898. var finalBuffer = new ArrayBuffer(totalSize);
  91899. var finalBufferView = new Uint8Array(finalBuffer);
  91900. var dataView = new DataView(finalBuffer);
  91901. // Copy the magic bytes identifying the file in
  91902. var pos = 0;
  91903. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91904. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  91905. }
  91906. // Add the json info
  91907. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  91908. pos += infoBuffer.byteLength;
  91909. // Finally inserts the texture data
  91910. for (var i = 0; i <= mipmapsCount; i++) {
  91911. for (var face = 0; face < 6; face++) {
  91912. var dataBuffer = specularTextures[i * 6 + face];
  91913. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  91914. pos += dataBuffer.byteLength;
  91915. }
  91916. }
  91917. // Voila
  91918. return finalBuffer;
  91919. });
  91920. };
  91921. /**
  91922. * Creates a JSON representation of the spherical data.
  91923. * @param texture defines the texture containing the polynomials
  91924. * @return the JSON representation of the spherical info
  91925. */
  91926. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  91927. var polynmials = texture.sphericalPolynomial;
  91928. if (polynmials == null) {
  91929. return null;
  91930. }
  91931. return {
  91932. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  91933. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  91934. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  91935. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  91936. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  91937. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  91938. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  91939. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  91940. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  91941. };
  91942. };
  91943. /**
  91944. * Uploads the texture info contained in the env file to the GPU.
  91945. * @param texture defines the internal texture to upload to
  91946. * @param arrayBuffer defines the buffer cotaining the data to load
  91947. * @param info defines the texture info retrieved through the GetEnvInfo method
  91948. * @returns a promise
  91949. */
  91950. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  91951. if (info.version !== 1) {
  91952. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  91953. }
  91954. var specularInfo = info.specular;
  91955. if (!specularInfo) {
  91956. // Nothing else parsed so far
  91957. return Promise.resolve();
  91958. }
  91959. // Double checks the enclosed info
  91960. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  91961. mipmapsCount = Math.round(mipmapsCount) + 1;
  91962. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  91963. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  91964. }
  91965. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  91966. var imageData = new Array(mipmapsCount);
  91967. for (var i = 0; i < mipmapsCount; i++) {
  91968. imageData[i] = new Array(6);
  91969. for (var face = 0; face < 6; face++) {
  91970. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  91971. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  91972. }
  91973. }
  91974. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  91975. };
  91976. /**
  91977. * Uploads the levels of image data to the GPU.
  91978. * @param texture defines the internal texture to upload to
  91979. * @param imageData defines the array buffer views of image data [mipmap][face]
  91980. * @returns a promise
  91981. */
  91982. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  91983. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  91984. throw new Error("Texture size must be a power of two");
  91985. }
  91986. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  91987. // Gets everything ready.
  91988. var engine = texture.getEngine();
  91989. var expandTexture = false;
  91990. var generateNonLODTextures = false;
  91991. var rgbdPostProcess = null;
  91992. var cubeRtt = null;
  91993. var lodTextures = null;
  91994. var caps = engine.getCaps();
  91995. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91996. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91997. texture.generateMipMaps = true;
  91998. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  91999. // Add extra process if texture lod is not supported
  92000. if (!caps.textureLOD) {
  92001. expandTexture = false;
  92002. generateNonLODTextures = true;
  92003. lodTextures = {};
  92004. }
  92005. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  92006. else if (engine.webGLVersion < 2) {
  92007. expandTexture = false;
  92008. }
  92009. // If half float available we can uncompress the texture
  92010. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  92011. expandTexture = true;
  92012. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92013. }
  92014. // If full float available we can uncompress the texture
  92015. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  92016. expandTexture = true;
  92017. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92018. }
  92019. // Expand the texture if possible
  92020. if (expandTexture) {
  92021. // Simply run through the decode PP
  92022. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  92023. texture._isRGBD = false;
  92024. texture.invertY = false;
  92025. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  92026. generateDepthBuffer: false,
  92027. generateMipMaps: true,
  92028. generateStencilBuffer: false,
  92029. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  92030. type: texture.type,
  92031. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  92032. });
  92033. }
  92034. else {
  92035. texture._isRGBD = true;
  92036. texture.invertY = true;
  92037. // In case of missing support, applies the same patch than DDS files.
  92038. if (generateNonLODTextures) {
  92039. var mipSlices = 3;
  92040. var scale = texture._lodGenerationScale;
  92041. var offset = texture._lodGenerationOffset;
  92042. for (var i = 0; i < mipSlices; i++) {
  92043. //compute LOD from even spacing in smoothness (matching shader calculation)
  92044. var smoothness = i / (mipSlices - 1);
  92045. var roughness = 1 - smoothness;
  92046. var minLODIndex = offset; // roughness = 0
  92047. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  92048. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  92049. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  92050. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  92051. glTextureFromLod.isCube = true;
  92052. glTextureFromLod.invertY = true;
  92053. glTextureFromLod.generateMipMaps = false;
  92054. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  92055. // Wrap in a base texture for easy binding.
  92056. var lodTexture = new BABYLON.BaseTexture(null);
  92057. lodTexture.isCube = true;
  92058. lodTexture._texture = glTextureFromLod;
  92059. lodTextures[mipmapIndex] = lodTexture;
  92060. switch (i) {
  92061. case 0:
  92062. texture._lodTextureLow = lodTexture;
  92063. break;
  92064. case 1:
  92065. texture._lodTextureMid = lodTexture;
  92066. break;
  92067. case 2:
  92068. texture._lodTextureHigh = lodTexture;
  92069. break;
  92070. }
  92071. }
  92072. }
  92073. }
  92074. var promises = [];
  92075. var _loop_3 = function (i) {
  92076. var _loop_4 = function (face) {
  92077. // Constructs an image element from image data
  92078. var bytes = imageData[i][face];
  92079. var blob = new Blob([bytes], { type: 'image/png' });
  92080. var url = URL.createObjectURL(blob);
  92081. var image = new Image();
  92082. image.src = url;
  92083. // Enqueue promise to upload to the texture.
  92084. var promise = new Promise(function (resolve, reject) {
  92085. image.onload = function () {
  92086. if (expandTexture) {
  92087. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  92088. reject(message);
  92089. }, image);
  92090. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92091. // Uncompress the data to a RTT
  92092. rgbdPostProcess.onApply = function (effect) {
  92093. effect._bindTexture("textureSampler", tempTexture_1);
  92094. effect.setFloat2("scale", 1, 1);
  92095. };
  92096. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  92097. // Cleanup
  92098. engine.restoreDefaultFramebuffer();
  92099. tempTexture_1.dispose();
  92100. window.URL.revokeObjectURL(url);
  92101. resolve();
  92102. });
  92103. }
  92104. else {
  92105. engine._uploadImageToTexture(texture, image, face, i);
  92106. // Upload the face to the non lod texture support
  92107. if (generateNonLODTextures) {
  92108. var lodTexture = lodTextures[i];
  92109. if (lodTexture) {
  92110. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  92111. }
  92112. }
  92113. resolve();
  92114. }
  92115. };
  92116. image.onerror = function (error) {
  92117. reject(error);
  92118. };
  92119. });
  92120. promises.push(promise);
  92121. };
  92122. // All faces
  92123. for (var face = 0; face < 6; face++) {
  92124. _loop_4(face);
  92125. }
  92126. };
  92127. // All mipmaps up to provided number of images
  92128. for (var i = 0; i < imageData.length; i++) {
  92129. _loop_3(i);
  92130. }
  92131. // Fill remaining mipmaps with black textures.
  92132. if (imageData.length < mipmapsCount) {
  92133. var data = void 0;
  92134. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  92135. var dataLength = size * size * 4;
  92136. switch (texture.type) {
  92137. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  92138. data = new Uint8Array(dataLength);
  92139. break;
  92140. }
  92141. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  92142. data = new Uint16Array(dataLength);
  92143. break;
  92144. }
  92145. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  92146. data = new Float32Array(dataLength);
  92147. break;
  92148. }
  92149. }
  92150. for (var i = imageData.length; i < mipmapsCount; i++) {
  92151. for (var face = 0; face < 6; face++) {
  92152. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  92153. }
  92154. }
  92155. }
  92156. // Once all done, finishes the cleanup and return
  92157. return Promise.all(promises).then(function () {
  92158. // Release temp RTT.
  92159. if (cubeRtt) {
  92160. engine._releaseFramebufferObjects(cubeRtt);
  92161. cubeRtt._swapAndDie(texture);
  92162. }
  92163. // Release temp Post Process.
  92164. if (rgbdPostProcess) {
  92165. rgbdPostProcess.dispose();
  92166. }
  92167. // Flag internal texture as ready in case they are in use.
  92168. if (generateNonLODTextures) {
  92169. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  92170. texture._lodTextureHigh._texture.isReady = true;
  92171. }
  92172. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  92173. texture._lodTextureMid._texture.isReady = true;
  92174. }
  92175. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  92176. texture._lodTextureLow._texture.isReady = true;
  92177. }
  92178. }
  92179. });
  92180. };
  92181. /**
  92182. * Uploads spherical polynomials information to the texture.
  92183. * @param texture defines the texture we are trying to upload the information to
  92184. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  92185. */
  92186. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  92187. if (info.version !== 1) {
  92188. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  92189. }
  92190. var irradianceInfo = info.irradiance;
  92191. if (!irradianceInfo) {
  92192. return;
  92193. }
  92194. var sp = new BABYLON.SphericalPolynomial();
  92195. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  92196. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  92197. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  92198. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  92199. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  92200. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  92201. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  92202. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  92203. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  92204. texture._sphericalPolynomial = sp;
  92205. };
  92206. /**
  92207. * Magic number identifying the env file.
  92208. */
  92209. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  92210. return EnvironmentTextureTools;
  92211. }());
  92212. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  92213. })(BABYLON || (BABYLON = {}));
  92214. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  92215. var BABYLON;
  92216. (function (BABYLON) {
  92217. /**
  92218. * Implementation of the ENV Texture Loader.
  92219. */
  92220. var ENVTextureLoader = /** @class */ (function () {
  92221. function ENVTextureLoader() {
  92222. /**
  92223. * Defines wether the loader supports cascade loading the different faces.
  92224. */
  92225. this.supportCascades = false;
  92226. }
  92227. /**
  92228. * This returns if the loader support the current file information.
  92229. * @param extension defines the file extension of the file being loaded
  92230. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92231. * @param fallback defines the fallback internal texture if any
  92232. * @param isBase64 defines whether the texture is encoded as a base64
  92233. * @param isBuffer defines whether the texture data are stored as a buffer
  92234. * @returns true if the loader can load the specified file
  92235. */
  92236. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92237. return extension.indexOf(".env") === 0;
  92238. };
  92239. /**
  92240. * Transform the url before loading if required.
  92241. * @param rootUrl the url of the texture
  92242. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92243. * @returns the transformed texture
  92244. */
  92245. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92246. return rootUrl;
  92247. };
  92248. /**
  92249. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92250. * @param rootUrl the url of the texture
  92251. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92252. * @returns the fallback texture
  92253. */
  92254. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92255. return null;
  92256. };
  92257. /**
  92258. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92259. * @param data contains the texture data
  92260. * @param texture defines the BabylonJS internal texture
  92261. * @param createPolynomials will be true if polynomials have been requested
  92262. * @param onLoad defines the callback to trigger once the texture is ready
  92263. * @param onError defines the callback to trigger in case of error
  92264. */
  92265. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92266. if (Array.isArray(data)) {
  92267. return;
  92268. }
  92269. data = data;
  92270. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  92271. if (info) {
  92272. texture.width = info.width;
  92273. texture.height = info.width;
  92274. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  92275. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  92276. texture.isReady = true;
  92277. if (onLoad) {
  92278. onLoad();
  92279. }
  92280. });
  92281. }
  92282. else if (onError) {
  92283. onError("Can not parse the environment file", null);
  92284. }
  92285. };
  92286. /**
  92287. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92288. * @param data contains the texture data
  92289. * @param texture defines the BabylonJS internal texture
  92290. * @param callback defines the method to call once ready to upload
  92291. */
  92292. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  92293. throw ".env not supported in 2d.";
  92294. };
  92295. return ENVTextureLoader;
  92296. }());
  92297. // Register the loader.
  92298. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  92299. })(BABYLON || (BABYLON = {}));
  92300. //# sourceMappingURL=babylon.envTextureLoader.js.map
  92301. var BABYLON;
  92302. (function (BABYLON) {
  92303. /**
  92304. * Renders a layer on top of an existing scene
  92305. */
  92306. var UtilityLayerRenderer = /** @class */ (function () {
  92307. /**
  92308. * Instantiates a UtilityLayerRenderer
  92309. * @param originalScene the original scene that will be rendered on top of
  92310. */
  92311. function UtilityLayerRenderer(
  92312. /** the original scene that will be rendered on top of */
  92313. originalScene) {
  92314. var _this = this;
  92315. this.originalScene = originalScene;
  92316. this._pointerCaptures = {};
  92317. this._lastPointerEvents = {};
  92318. /**
  92319. * If the utility layer should automatically be rendered on top of existing scene
  92320. */
  92321. this.shouldRender = true;
  92322. /**
  92323. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  92324. */
  92325. this.onlyCheckPointerDownEvents = true;
  92326. /**
  92327. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  92328. */
  92329. this.processAllEvents = false;
  92330. /**
  92331. * Observable raised when the pointer move from the utility layer scene to the main scene
  92332. */
  92333. this.onPointerOutObservable = new BABYLON.Observable();
  92334. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  92335. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  92336. this.utilityLayerScene._allowPostProcessClearColor = false;
  92337. originalScene.getEngine().scenes.pop();
  92338. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  92339. this.utilityLayerScene.detachControl();
  92340. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  92341. if (!_this.processAllEvents) {
  92342. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  92343. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  92344. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  92345. return;
  92346. }
  92347. }
  92348. var pointerEvent = (prePointerInfo.event);
  92349. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  92350. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92351. return;
  92352. }
  92353. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  92354. if (!prePointerInfo.ray && utilityScenePick) {
  92355. prePointerInfo.ray = utilityScenePick.ray;
  92356. }
  92357. // always fire the prepointer oversvable
  92358. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  92359. // allow every non pointer down event to flow to the utility layer
  92360. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  92361. if (!prePointerInfo.skipOnPointerObservable) {
  92362. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92363. }
  92364. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  92365. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92366. }
  92367. return;
  92368. }
  92369. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  92370. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  92371. if (utilityScenePick && utilityScenePick.hit) {
  92372. if (!prePointerInfo.skipOnPointerObservable) {
  92373. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92374. }
  92375. prePointerInfo.skipOnPointerObservable = true;
  92376. }
  92377. }
  92378. else {
  92379. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  92380. var pointerEvent_1 = (prePointerInfo.event);
  92381. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  92382. if (originalScenePick && utilityScenePick) {
  92383. // No pick in utility scene
  92384. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  92385. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92386. // We touched an utility mesh present in the main scene
  92387. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92388. prePointerInfo.skipOnPointerObservable = true;
  92389. }
  92390. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92391. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  92392. }
  92393. }
  92394. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  92395. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  92396. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  92397. // If a previous utility layer set this, do not unset this
  92398. if (!prePointerInfo.skipOnPointerObservable) {
  92399. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  92400. }
  92401. }
  92402. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  92403. // We have a pick in both scenes but main is closer than utility
  92404. // We touched an utility mesh present in the main scene
  92405. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92406. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92407. prePointerInfo.skipOnPointerObservable = true;
  92408. }
  92409. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  92410. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  92411. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  92412. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  92413. }
  92414. }
  92415. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  92416. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  92417. }
  92418. }
  92419. }
  92420. });
  92421. // Render directly on top of existing scene without clearing
  92422. this.utilityLayerScene.autoClear = false;
  92423. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  92424. if (_this.shouldRender) {
  92425. _this.render();
  92426. }
  92427. });
  92428. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  92429. _this.dispose();
  92430. });
  92431. this._updateCamera();
  92432. }
  92433. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  92434. /**
  92435. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  92436. */
  92437. get: function () {
  92438. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  92439. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92440. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92441. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92442. });
  92443. }
  92444. return UtilityLayerRenderer._DefaultUtilityLayer;
  92445. },
  92446. enumerable: true,
  92447. configurable: true
  92448. });
  92449. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  92450. /**
  92451. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  92452. */
  92453. get: function () {
  92454. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  92455. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92456. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  92457. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92458. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92459. });
  92460. }
  92461. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  92462. },
  92463. enumerable: true,
  92464. configurable: true
  92465. });
  92466. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  92467. if (!prePointerInfo.skipOnPointerObservable) {
  92468. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  92469. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  92470. }
  92471. };
  92472. /**
  92473. * Renders the utility layers scene on top of the original scene
  92474. */
  92475. UtilityLayerRenderer.prototype.render = function () {
  92476. this._updateCamera();
  92477. if (this.utilityLayerScene.activeCamera) {
  92478. // Set the camera's scene to utility layers scene
  92479. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  92480. var camera = this.utilityLayerScene.activeCamera;
  92481. camera._scene = this.utilityLayerScene;
  92482. if (camera.leftCamera) {
  92483. camera.leftCamera._scene = this.utilityLayerScene;
  92484. }
  92485. if (camera.rightCamera) {
  92486. camera.rightCamera._scene = this.utilityLayerScene;
  92487. }
  92488. this.utilityLayerScene.render(false);
  92489. // Reset camera's scene back to original
  92490. camera._scene = oldScene;
  92491. if (camera.leftCamera) {
  92492. camera.leftCamera._scene = oldScene;
  92493. }
  92494. if (camera.rightCamera) {
  92495. camera.rightCamera._scene = oldScene;
  92496. }
  92497. }
  92498. };
  92499. /**
  92500. * Disposes of the renderer
  92501. */
  92502. UtilityLayerRenderer.prototype.dispose = function () {
  92503. this.onPointerOutObservable.clear();
  92504. if (this._afterRenderObserver) {
  92505. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  92506. }
  92507. if (this._sceneDisposeObserver) {
  92508. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  92509. }
  92510. if (this._originalPointerObserver) {
  92511. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  92512. }
  92513. this.utilityLayerScene.dispose();
  92514. };
  92515. UtilityLayerRenderer.prototype._updateCamera = function () {
  92516. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  92517. };
  92518. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92519. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92520. return UtilityLayerRenderer;
  92521. }());
  92522. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  92523. })(BABYLON || (BABYLON = {}));
  92524. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  92525. //# sourceMappingURL=babylon.behavior.js.map
  92526. var BABYLON;
  92527. (function (BABYLON) {
  92528. /**
  92529. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  92530. */
  92531. var PointerDragBehavior = /** @class */ (function () {
  92532. /**
  92533. * Creates a pointer drag behavior that can be attached to a mesh
  92534. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  92535. */
  92536. function PointerDragBehavior(options) {
  92537. /**
  92538. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  92539. */
  92540. this.maxDragAngle = 0;
  92541. /**
  92542. * @hidden
  92543. */
  92544. this._useAlternatePickedPointAboveMaxDragAngle = false;
  92545. /**
  92546. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  92547. */
  92548. this.currentDraggingPointerID = -1;
  92549. /**
  92550. * If the behavior is currently in a dragging state
  92551. */
  92552. this.dragging = false;
  92553. /**
  92554. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  92555. */
  92556. this.dragDeltaRatio = 0.2;
  92557. /**
  92558. * If the drag plane orientation should be updated during the dragging (Default: true)
  92559. */
  92560. this.updateDragPlane = true;
  92561. // Debug mode will display drag planes to help visualize behavior
  92562. this._debugMode = false;
  92563. this._moving = false;
  92564. /**
  92565. * Fires each time the attached mesh is dragged with the pointer
  92566. * * delta between last drag position and current drag position in world space
  92567. * * dragDistance along the drag axis
  92568. * * dragPlaneNormal normal of the current drag plane used during the drag
  92569. * * dragPlanePoint in world space where the drag intersects the drag plane
  92570. */
  92571. this.onDragObservable = new BABYLON.Observable();
  92572. /**
  92573. * Fires each time a drag begins (eg. mouse down on mesh)
  92574. */
  92575. this.onDragStartObservable = new BABYLON.Observable();
  92576. /**
  92577. * Fires each time a drag ends (eg. mouse release after drag)
  92578. */
  92579. this.onDragEndObservable = new BABYLON.Observable();
  92580. /**
  92581. * If the attached mesh should be moved when dragged
  92582. */
  92583. this.moveAttached = true;
  92584. /**
  92585. * If the drag behavior will react to drag events (Default: true)
  92586. */
  92587. this.enabled = true;
  92588. /**
  92589. * If camera controls should be detached during the drag
  92590. */
  92591. this.detachCameraControls = true;
  92592. /**
  92593. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  92594. */
  92595. this.useObjectOrienationForDragging = true;
  92596. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92597. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  92598. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  92599. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92600. this._attachedElement = null;
  92601. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92602. this._lastPointerRay = {};
  92603. this._dragDelta = new BABYLON.Vector3();
  92604. // Variables to avoid instantiation in the below method
  92605. this._pointA = new BABYLON.Vector3(0, 0, 0);
  92606. this._pointB = new BABYLON.Vector3(0, 0, 0);
  92607. this._pointC = new BABYLON.Vector3(0, 0, 0);
  92608. this._lineA = new BABYLON.Vector3(0, 0, 0);
  92609. this._lineB = new BABYLON.Vector3(0, 0, 0);
  92610. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  92611. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  92612. this._options = options ? options : {};
  92613. var optionCount = 0;
  92614. if (this._options.dragAxis) {
  92615. optionCount++;
  92616. }
  92617. if (this._options.dragPlaneNormal) {
  92618. optionCount++;
  92619. }
  92620. if (optionCount > 1) {
  92621. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  92622. }
  92623. }
  92624. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  92625. /**
  92626. * The name of the behavior
  92627. */
  92628. get: function () {
  92629. return "PointerDrag";
  92630. },
  92631. enumerable: true,
  92632. configurable: true
  92633. });
  92634. /**
  92635. * Initializes the behavior
  92636. */
  92637. PointerDragBehavior.prototype.init = function () { };
  92638. /**
  92639. * Attaches the drag behavior the passed in mesh
  92640. * @param ownerNode The mesh that will be dragged around once attached
  92641. */
  92642. PointerDragBehavior.prototype.attach = function (ownerNode) {
  92643. var _this = this;
  92644. this._scene = ownerNode.getScene();
  92645. this._attachedNode = ownerNode;
  92646. // Initialize drag plane to not interfere with existing scene
  92647. if (!PointerDragBehavior._planeScene) {
  92648. if (this._debugMode) {
  92649. PointerDragBehavior._planeScene = this._scene;
  92650. }
  92651. else {
  92652. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  92653. PointerDragBehavior._planeScene.detachControl();
  92654. this._scene.getEngine().scenes.pop();
  92655. this._scene.onDisposeObservable.addOnce(function () {
  92656. PointerDragBehavior._planeScene.dispose();
  92657. PointerDragBehavior._planeScene = null;
  92658. });
  92659. }
  92660. }
  92661. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  92662. // State of the drag
  92663. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  92664. var pickPredicate = function (m) {
  92665. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  92666. };
  92667. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92668. if (!_this.enabled) {
  92669. return;
  92670. }
  92671. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92672. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92673. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  92674. }
  92675. }
  92676. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  92677. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  92678. _this.releaseDrag();
  92679. }
  92680. }
  92681. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  92682. var pointerId = pointerInfo.event.pointerId;
  92683. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  92684. if (!_this._lastPointerRay[pointerId]) {
  92685. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92686. }
  92687. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  92688. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  92689. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  92690. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  92691. _this._moveDrag(pointerInfo.pickInfo.ray);
  92692. }
  92693. }
  92694. }
  92695. });
  92696. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  92697. if (_this._moving && _this.moveAttached) {
  92698. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  92699. // Slowly move mesh to avoid jitter
  92700. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  92701. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  92702. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  92703. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  92704. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  92705. }
  92706. });
  92707. };
  92708. PointerDragBehavior.prototype.releaseDrag = function () {
  92709. this.dragging = false;
  92710. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  92711. this.currentDraggingPointerID = -1;
  92712. this._moving = false;
  92713. // Reattach camera controls
  92714. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92715. this._scene.activeCamera.attachControl(this._attachedElement, true);
  92716. }
  92717. };
  92718. /**
  92719. * Simulates the start of a pointer drag event on the behavior
  92720. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  92721. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  92722. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  92723. */
  92724. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  92725. if (pointerId === void 0) { pointerId = 1; }
  92726. this._startDrag(pointerId, fromRay, startPickedPoint);
  92727. if (this._lastPointerRay[pointerId]) {
  92728. // if there was a last pointer ray drag the object there
  92729. this._moveDrag(this._lastPointerRay[pointerId]);
  92730. }
  92731. };
  92732. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  92733. if (pointerId === void 0) { pointerId = 1; }
  92734. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  92735. return;
  92736. }
  92737. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  92738. // Create start ray from the camera to the object
  92739. if (fromRay) {
  92740. this._startDragRay.direction.copyFrom(fromRay.direction);
  92741. this._startDragRay.origin.copyFrom(fromRay.origin);
  92742. }
  92743. else {
  92744. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  92745. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  92746. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  92747. }
  92748. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  92749. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  92750. if (pickedPoint) {
  92751. this.dragging = true;
  92752. this.currentDraggingPointerID = pointerId;
  92753. this.lastDragPosition.copyFrom(pickedPoint);
  92754. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  92755. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  92756. // Detatch camera controls
  92757. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92758. if (this._scene.activeCamera.inputs.attachedElement) {
  92759. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  92760. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  92761. }
  92762. else {
  92763. this._attachedElement = null;
  92764. }
  92765. }
  92766. }
  92767. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  92768. };
  92769. PointerDragBehavior.prototype._moveDrag = function (ray) {
  92770. this._moving = true;
  92771. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  92772. if (pickedPoint) {
  92773. if (this.updateDragPlane) {
  92774. this._updateDragPlanePosition(ray, pickedPoint);
  92775. }
  92776. var dragLength = 0;
  92777. // depending on the drag mode option drag accordingly
  92778. if (this._options.dragAxis) {
  92779. // Convert local drag axis to world
  92780. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  92781. // Project delta drag from the drag plane onto the drag axis
  92782. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  92783. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  92784. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  92785. }
  92786. else {
  92787. dragLength = this._dragDelta.length();
  92788. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  92789. }
  92790. this._targetPosition.addInPlace(this._dragDelta);
  92791. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  92792. this.lastDragPosition.copyFrom(pickedPoint);
  92793. }
  92794. };
  92795. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  92796. var _this = this;
  92797. if (!ray) {
  92798. return null;
  92799. }
  92800. // Calculate angle between plane normal and ray
  92801. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  92802. // Correct if ray is casted from oposite side
  92803. if (angle > Math.PI / 2) {
  92804. angle = Math.PI - angle;
  92805. }
  92806. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  92807. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  92808. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  92809. // Invert ray direction along the towards object axis
  92810. this._tmpVector.copyFrom(ray.direction);
  92811. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  92812. this._alternatePickedPoint.normalize();
  92813. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  92814. this._tmpVector.addInPlace(this._alternatePickedPoint);
  92815. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  92816. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  92817. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  92818. this._alternatePickedPoint.addInPlace(this._tmpVector);
  92819. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  92820. return this._alternatePickedPoint;
  92821. }
  92822. else {
  92823. return null;
  92824. }
  92825. }
  92826. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  92827. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  92828. return pickResult.pickedPoint;
  92829. }
  92830. else {
  92831. return null;
  92832. }
  92833. };
  92834. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  92835. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  92836. this._pointA.copyFrom(dragPlanePosition);
  92837. if (this._options.dragAxis) {
  92838. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  92839. // Calculate plane normal in direction of camera but perpendicular to drag axis
  92840. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  92841. ray.origin.subtractToRef(this._pointA, this._pointC);
  92842. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  92843. // Get perpendicular line from direction to camera and drag axis
  92844. this._pointB.subtractToRef(this._pointA, this._lineA);
  92845. this._pointC.subtractToRef(this._pointA, this._lineB);
  92846. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  92847. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  92848. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  92849. this._lookAt.normalize();
  92850. this._dragPlane.position.copyFrom(this._pointA);
  92851. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  92852. this._dragPlane.lookAt(this._lookAt);
  92853. }
  92854. else if (this._options.dragPlaneNormal) {
  92855. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  92856. this._dragPlane.position.copyFrom(this._pointA);
  92857. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  92858. this._dragPlane.lookAt(this._lookAt);
  92859. }
  92860. else {
  92861. this._dragPlane.position.copyFrom(this._pointA);
  92862. this._dragPlane.lookAt(ray.origin);
  92863. }
  92864. this._dragPlane.computeWorldMatrix(true);
  92865. };
  92866. /**
  92867. * Detaches the behavior from the mesh
  92868. */
  92869. PointerDragBehavior.prototype.detach = function () {
  92870. if (this._pointerObserver) {
  92871. this._scene.onPointerObservable.remove(this._pointerObserver);
  92872. }
  92873. if (this._beforeRenderObserver) {
  92874. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92875. }
  92876. };
  92877. return PointerDragBehavior;
  92878. }());
  92879. BABYLON.PointerDragBehavior = PointerDragBehavior;
  92880. })(BABYLON || (BABYLON = {}));
  92881. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  92882. var BABYLON;
  92883. (function (BABYLON) {
  92884. /**
  92885. * A behavior that when attached to a mesh will allow the mesh to be scaled
  92886. */
  92887. var MultiPointerScaleBehavior = /** @class */ (function () {
  92888. function MultiPointerScaleBehavior() {
  92889. this._startDistance = 0;
  92890. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  92891. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  92892. this._sceneRenderObserver = null;
  92893. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  92894. this._dragBehaviorA.moveAttached = false;
  92895. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  92896. this._dragBehaviorB.moveAttached = false;
  92897. }
  92898. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  92899. /**
  92900. * The name of the behavior
  92901. */
  92902. get: function () {
  92903. return "MultiPointerScale";
  92904. },
  92905. enumerable: true,
  92906. configurable: true
  92907. });
  92908. /**
  92909. * Initializes the behavior
  92910. */
  92911. MultiPointerScaleBehavior.prototype.init = function () { };
  92912. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  92913. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  92914. };
  92915. /**
  92916. * Attaches the scale behavior the passed in mesh
  92917. * @param ownerNode The mesh that will be scaled around once attached
  92918. */
  92919. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  92920. var _this = this;
  92921. this._ownerNode = ownerNode;
  92922. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  92923. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  92924. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92925. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92926. _this._dragBehaviorA.releaseDrag();
  92927. }
  92928. else {
  92929. _this._initialScale.copyFrom(ownerNode.scaling);
  92930. _this._startDistance = _this._getCurrentDistance();
  92931. }
  92932. }
  92933. });
  92934. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  92935. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92936. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92937. _this._dragBehaviorB.releaseDrag();
  92938. }
  92939. else {
  92940. _this._initialScale.copyFrom(ownerNode.scaling);
  92941. _this._startDistance = _this._getCurrentDistance();
  92942. }
  92943. }
  92944. });
  92945. // Once both drag behaviors are active scale based on the distance between the two pointers
  92946. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92947. behavior.onDragObservable.add(function () {
  92948. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92949. var ratio = _this._getCurrentDistance() / _this._startDistance;
  92950. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  92951. }
  92952. });
  92953. });
  92954. ownerNode.addBehavior(this._dragBehaviorA);
  92955. ownerNode.addBehavior(this._dragBehaviorB);
  92956. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  92957. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  92958. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92959. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  92960. if (change.length() > 0.01) {
  92961. ownerNode.scaling.addInPlace(change);
  92962. }
  92963. }
  92964. });
  92965. };
  92966. /**
  92967. * Detaches the behavior from the mesh
  92968. */
  92969. MultiPointerScaleBehavior.prototype.detach = function () {
  92970. var _this = this;
  92971. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  92972. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92973. behavior.onDragStartObservable.clear();
  92974. behavior.onDragObservable.clear();
  92975. _this._ownerNode.removeBehavior(behavior);
  92976. });
  92977. };
  92978. return MultiPointerScaleBehavior;
  92979. }());
  92980. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  92981. })(BABYLON || (BABYLON = {}));
  92982. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  92983. var BABYLON;
  92984. (function (BABYLON) {
  92985. /**
  92986. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  92987. */
  92988. var SixDofDragBehavior = /** @class */ (function () {
  92989. function SixDofDragBehavior() {
  92990. this._sceneRenderObserver = null;
  92991. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92992. this._moving = false;
  92993. this._startingOrientation = new BABYLON.Quaternion();
  92994. /**
  92995. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  92996. */
  92997. this.zDragFactor = 3;
  92998. /**
  92999. * If the behavior is currently in a dragging state
  93000. */
  93001. this.dragging = false;
  93002. /**
  93003. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  93004. */
  93005. this.dragDeltaRatio = 0.2;
  93006. /**
  93007. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93008. */
  93009. this.currentDraggingPointerID = -1;
  93010. /**
  93011. * If camera controls should be detached during the drag
  93012. */
  93013. this.detachCameraControls = true;
  93014. }
  93015. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  93016. /**
  93017. * The name of the behavior
  93018. */
  93019. get: function () {
  93020. return "SixDofDrag";
  93021. },
  93022. enumerable: true,
  93023. configurable: true
  93024. });
  93025. /**
  93026. * Initializes the behavior
  93027. */
  93028. SixDofDragBehavior.prototype.init = function () { };
  93029. /**
  93030. * Attaches the scale behavior the passed in mesh
  93031. * @param ownerNode The mesh that will be scaled around once attached
  93032. */
  93033. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  93034. var _this = this;
  93035. this._ownerNode = ownerNode;
  93036. this._scene = this._ownerNode.getScene();
  93037. if (!SixDofDragBehavior._virtualScene) {
  93038. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  93039. this._scene.getEngine().scenes.pop();
  93040. }
  93041. var pickedMesh = null;
  93042. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  93043. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  93044. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93045. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  93046. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93047. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  93048. var pickPredicate = function (m) {
  93049. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  93050. };
  93051. var attachedElement = null;
  93052. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93053. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93054. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93055. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93056. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93057. }
  93058. pickedMesh = _this._ownerNode;
  93059. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93060. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93061. // Set position and orientation of the controller
  93062. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93063. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93064. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  93065. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93066. pickedMesh.computeWorldMatrix();
  93067. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  93068. if (!pickedMesh.rotationQuaternion) {
  93069. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  93070. }
  93071. var oldParent = pickedMesh.parent;
  93072. pickedMesh.setParent(null);
  93073. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  93074. pickedMesh.setParent(oldParent);
  93075. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93076. // Update state
  93077. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93078. _this.dragging = true;
  93079. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  93080. // Detatch camera controls
  93081. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93082. if (_this._scene.activeCamera.inputs.attachedElement) {
  93083. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  93084. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  93085. }
  93086. else {
  93087. attachedElement = null;
  93088. }
  93089. }
  93090. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93091. }
  93092. }
  93093. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93094. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93095. _this.dragging = false;
  93096. _this._moving = false;
  93097. _this.currentDraggingPointerID = -1;
  93098. pickedMesh = null;
  93099. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93100. // Reattach camera controls
  93101. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93102. _this._scene.activeCamera.attachControl(attachedElement, true);
  93103. }
  93104. }
  93105. }
  93106. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93107. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  93108. var zDragFactor = _this.zDragFactor;
  93109. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93110. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93111. zDragFactor = 0;
  93112. }
  93113. // Calculate controller drag distance in controller space
  93114. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  93115. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93116. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  93117. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93118. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  93119. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  93120. if (_this._virtualDragMesh.position.z < 0) {
  93121. _this._virtualDragMesh.position.z = 0;
  93122. }
  93123. // Update the controller position
  93124. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93125. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93126. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93127. // Move the virtualObjectsPosition into the picked mesh's space if needed
  93128. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93129. if (pickedMesh.parent) {
  93130. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  93131. }
  93132. if (!_this._moving) {
  93133. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  93134. }
  93135. _this._moving = true;
  93136. }
  93137. }
  93138. });
  93139. var tmpQuaternion = new BABYLON.Quaternion();
  93140. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93141. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93142. if (_this.dragging && _this._moving && pickedMesh) {
  93143. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93144. // Slowly move mesh to avoid jitter
  93145. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  93146. // Get change in rotation
  93147. tmpQuaternion.copyFrom(_this._startingOrientation);
  93148. tmpQuaternion.x = -tmpQuaternion.x;
  93149. tmpQuaternion.y = -tmpQuaternion.y;
  93150. tmpQuaternion.z = -tmpQuaternion.z;
  93151. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  93152. // Convert change in rotation to only y axis rotation
  93153. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  93154. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  93155. // Slowly move mesh to avoid jitter
  93156. var oldParent = pickedMesh.parent;
  93157. pickedMesh.setParent(null);
  93158. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  93159. pickedMesh.setParent(oldParent);
  93160. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93161. }
  93162. });
  93163. };
  93164. /**
  93165. * Detaches the behavior from the mesh
  93166. */
  93167. SixDofDragBehavior.prototype.detach = function () {
  93168. if (this._scene) {
  93169. this._scene.onPointerObservable.remove(this._pointerObserver);
  93170. }
  93171. if (this._ownerNode) {
  93172. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93173. }
  93174. if (this._virtualOriginMesh) {
  93175. this._virtualOriginMesh.dispose();
  93176. }
  93177. if (this._virtualDragMesh) {
  93178. this._virtualDragMesh.dispose();
  93179. }
  93180. };
  93181. return SixDofDragBehavior;
  93182. }());
  93183. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  93184. })(BABYLON || (BABYLON = {}));
  93185. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  93186. var BABYLON;
  93187. (function (BABYLON) {
  93188. /**
  93189. * @hidden
  93190. */
  93191. var FaceDirectionInfo = /** @class */ (function () {
  93192. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  93193. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  93194. if (diff === void 0) { diff = 0; }
  93195. if (ignore === void 0) { ignore = false; }
  93196. this.direction = direction;
  93197. this.rotatedDirection = rotatedDirection;
  93198. this.diff = diff;
  93199. this.ignore = ignore;
  93200. }
  93201. return FaceDirectionInfo;
  93202. }());
  93203. /**
  93204. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  93205. */
  93206. var AttachToBoxBehavior = /** @class */ (function () {
  93207. /**
  93208. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  93209. * @param ui The transform node that should be attched to the mesh
  93210. */
  93211. function AttachToBoxBehavior(ui) {
  93212. this.ui = ui;
  93213. /**
  93214. * The name of the behavior
  93215. */
  93216. this.name = "AttachToBoxBehavior";
  93217. /**
  93218. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  93219. */
  93220. this.distanceAwayFromFace = 0.15;
  93221. /**
  93222. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  93223. */
  93224. this.distanceAwayFromBottomOfFace = 0.15;
  93225. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  93226. this._tmpMatrix = new BABYLON.Matrix();
  93227. this._tmpVector = new BABYLON.Vector3();
  93228. this._zeroVector = BABYLON.Vector3.Zero();
  93229. this._lookAtTmpMatrix = new BABYLON.Matrix();
  93230. /* Does nothing */
  93231. }
  93232. /**
  93233. * Initializes the behavior
  93234. */
  93235. AttachToBoxBehavior.prototype.init = function () {
  93236. /* Does nothing */
  93237. };
  93238. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  93239. var _this = this;
  93240. // Go over each face and calculate the angle between the face's normal and targetDirection
  93241. this._faceVectors.forEach(function (v) {
  93242. if (!_this._target.rotationQuaternion) {
  93243. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  93244. }
  93245. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  93246. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  93247. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  93248. });
  93249. // Return the face information of the one with the normal closeset to target direction
  93250. return this._faceVectors.reduce(function (min, p) {
  93251. if (min.ignore) {
  93252. return p;
  93253. }
  93254. else if (p.ignore) {
  93255. return min;
  93256. }
  93257. else {
  93258. return min.diff < p.diff ? min : p;
  93259. }
  93260. }, this._faceVectors[0]);
  93261. };
  93262. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  93263. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  93264. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  93265. this._lookAtTmpMatrix.invert();
  93266. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  93267. };
  93268. /**
  93269. * Attaches the AttachToBoxBehavior to the passed in mesh
  93270. * @param target The mesh that the specified node will be attached to
  93271. */
  93272. AttachToBoxBehavior.prototype.attach = function (target) {
  93273. var _this = this;
  93274. this._target = target;
  93275. this._scene = this._target.getScene();
  93276. // Every frame, update the app bars position
  93277. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93278. if (!_this._scene.activeCamera) {
  93279. return;
  93280. }
  93281. // Find the face closest to the cameras position
  93282. var cameraPos = _this._scene.activeCamera.position;
  93283. if (_this._scene.activeCamera.devicePosition) {
  93284. cameraPos = _this._scene.activeCamera.devicePosition;
  93285. }
  93286. var facing = _this._closestFace(cameraPos.subtract(target.position));
  93287. if (_this._scene.activeCamera.leftCamera) {
  93288. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93289. }
  93290. else {
  93291. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93292. }
  93293. // Get camera up direction
  93294. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  93295. // Ignore faces to not select a parrelel face for the up vector of the UI
  93296. _this._faceVectors.forEach(function (v) {
  93297. if (facing.direction.x && v.direction.x) {
  93298. v.ignore = true;
  93299. }
  93300. if (facing.direction.y && v.direction.y) {
  93301. v.ignore = true;
  93302. }
  93303. if (facing.direction.z && v.direction.z) {
  93304. v.ignore = true;
  93305. }
  93306. });
  93307. var facingUp = _this._closestFace(_this._tmpVector);
  93308. // Unignore faces
  93309. _this._faceVectors.forEach(function (v) {
  93310. v.ignore = false;
  93311. });
  93312. // Position the app bar on that face
  93313. _this.ui.position.copyFrom(target.position);
  93314. if (facing.direction.x) {
  93315. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93316. _this.ui.position.addInPlace(_this._tmpVector);
  93317. }
  93318. if (facing.direction.y) {
  93319. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93320. _this.ui.position.addInPlace(_this._tmpVector);
  93321. }
  93322. if (facing.direction.z) {
  93323. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93324. _this.ui.position.addInPlace(_this._tmpVector);
  93325. }
  93326. // Rotate to be oriented properly to the camera
  93327. if (!_this.ui.rotationQuaternion) {
  93328. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  93329. }
  93330. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  93331. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  93332. // Place ui the correct distance from the bottom of the mesh
  93333. if (facingUp.direction.x) {
  93334. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  93335. }
  93336. if (facingUp.direction.y) {
  93337. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  93338. }
  93339. if (facingUp.direction.z) {
  93340. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  93341. }
  93342. _this.ui.position.addInPlace(_this._tmpVector);
  93343. });
  93344. };
  93345. /**
  93346. * Detaches the behavior from the mesh
  93347. */
  93348. AttachToBoxBehavior.prototype.detach = function () {
  93349. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  93350. };
  93351. return AttachToBoxBehavior;
  93352. }());
  93353. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  93354. })(BABYLON || (BABYLON = {}));
  93355. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  93356. var BABYLON;
  93357. (function (BABYLON) {
  93358. /**
  93359. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  93360. */
  93361. var FadeInOutBehavior = /** @class */ (function () {
  93362. /**
  93363. * Instatiates the FadeInOutBehavior
  93364. */
  93365. function FadeInOutBehavior() {
  93366. var _this = this;
  93367. /**
  93368. * Time in milliseconds to delay before fading in (Default: 0)
  93369. */
  93370. this.delay = 0;
  93371. /**
  93372. * Time in milliseconds for the mesh to fade in (Default: 300)
  93373. */
  93374. this.fadeInTime = 300;
  93375. this._millisecondsPerFrame = 1000 / 60;
  93376. this._hovered = false;
  93377. this._hoverValue = 0;
  93378. this._ownerNode = null;
  93379. this._update = function () {
  93380. if (_this._ownerNode) {
  93381. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  93382. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  93383. if (_this._ownerNode.visibility > 1) {
  93384. _this._setAllVisibility(_this._ownerNode, 1);
  93385. _this._hoverValue = _this.fadeInTime + _this.delay;
  93386. return;
  93387. }
  93388. else if (_this._ownerNode.visibility < 0) {
  93389. _this._setAllVisibility(_this._ownerNode, 0);
  93390. if (_this._hoverValue < 0) {
  93391. _this._hoverValue = 0;
  93392. return;
  93393. }
  93394. }
  93395. setTimeout(_this._update, _this._millisecondsPerFrame);
  93396. }
  93397. };
  93398. }
  93399. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  93400. /**
  93401. * The name of the behavior
  93402. */
  93403. get: function () {
  93404. return "FadeInOut";
  93405. },
  93406. enumerable: true,
  93407. configurable: true
  93408. });
  93409. /**
  93410. * Initializes the behavior
  93411. */
  93412. FadeInOutBehavior.prototype.init = function () {
  93413. };
  93414. /**
  93415. * Attaches the fade behavior on the passed in mesh
  93416. * @param ownerNode The mesh that will be faded in/out once attached
  93417. */
  93418. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  93419. this._ownerNode = ownerNode;
  93420. this._setAllVisibility(this._ownerNode, 0);
  93421. };
  93422. /**
  93423. * Detaches the behavior from the mesh
  93424. */
  93425. FadeInOutBehavior.prototype.detach = function () {
  93426. this._ownerNode = null;
  93427. };
  93428. /**
  93429. * Triggers the mesh to begin fading in or out
  93430. * @param value if the object should fade in or out (true to fade in)
  93431. */
  93432. FadeInOutBehavior.prototype.fadeIn = function (value) {
  93433. this._hovered = value;
  93434. this._update();
  93435. };
  93436. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  93437. var _this = this;
  93438. mesh.visibility = value;
  93439. mesh.getChildMeshes().forEach(function (c) {
  93440. _this._setAllVisibility(c, value);
  93441. });
  93442. };
  93443. return FadeInOutBehavior;
  93444. }());
  93445. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  93446. })(BABYLON || (BABYLON = {}));
  93447. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  93448. var BABYLON;
  93449. (function (BABYLON) {
  93450. /**
  93451. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  93452. */
  93453. var Gizmo = /** @class */ (function () {
  93454. /**
  93455. * Creates a gizmo
  93456. * @param gizmoLayer The utility layer the gizmo will be added to
  93457. */
  93458. function Gizmo(
  93459. /** The utility layer the gizmo will be added to */
  93460. gizmoLayer) {
  93461. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93462. var _this = this;
  93463. this.gizmoLayer = gizmoLayer;
  93464. /**
  93465. * Ratio for the scale of the gizmo (Default: 1)
  93466. */
  93467. this.scaleRatio = 1;
  93468. this._tmpMatrix = new BABYLON.Matrix();
  93469. /**
  93470. * If a custom mesh has been set (Default: false)
  93471. */
  93472. this._customMeshSet = false;
  93473. /**
  93474. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  93475. */
  93476. this.updateGizmoRotationToMatchAttachedMesh = true;
  93477. /**
  93478. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  93479. */
  93480. this.updateGizmoPositionToMatchAttachedMesh = true;
  93481. /**
  93482. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  93483. */
  93484. this._updateScale = true;
  93485. this._interactionsEnabled = true;
  93486. this._tempVector = new BABYLON.Vector3();
  93487. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  93488. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  93489. _this._update();
  93490. });
  93491. this.attachedMesh = null;
  93492. }
  93493. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  93494. /**
  93495. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  93496. * * When set, interactions will be enabled
  93497. */
  93498. get: function () {
  93499. return this._attachedMesh;
  93500. },
  93501. set: function (value) {
  93502. this._attachedMesh = value;
  93503. this._rootMesh.setEnabled(value ? true : false);
  93504. this._attachedMeshChanged(value);
  93505. },
  93506. enumerable: true,
  93507. configurable: true
  93508. });
  93509. /**
  93510. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93511. * @param mesh The mesh to replace the default mesh of the gizmo
  93512. */
  93513. Gizmo.prototype.setCustomMesh = function (mesh) {
  93514. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  93515. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  93516. }
  93517. this._rootMesh.getChildMeshes().forEach(function (c) {
  93518. c.dispose();
  93519. });
  93520. mesh.parent = this._rootMesh;
  93521. this._customMeshSet = true;
  93522. };
  93523. Gizmo.prototype._attachedMeshChanged = function (value) {
  93524. };
  93525. /**
  93526. * @hidden
  93527. * Updates the gizmo to match the attached mesh's position/rotation
  93528. */
  93529. Gizmo.prototype._update = function () {
  93530. if (this.attachedMesh) {
  93531. if (this.updateGizmoRotationToMatchAttachedMesh) {
  93532. if (!this._rootMesh.rotationQuaternion) {
  93533. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  93534. }
  93535. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  93536. this._tempVector.copyFrom(this.attachedMesh.scaling);
  93537. if (this.attachedMesh.scaling.x < 0) {
  93538. this.attachedMesh.scaling.x *= -1;
  93539. }
  93540. if (this.attachedMesh.scaling.y < 0) {
  93541. this.attachedMesh.scaling.y *= -1;
  93542. }
  93543. if (this.attachedMesh.scaling.z < 0) {
  93544. this.attachedMesh.scaling.z *= -1;
  93545. }
  93546. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  93547. this.attachedMesh.scaling.copyFrom(this._tempVector);
  93548. this.attachedMesh.computeWorldMatrix();
  93549. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  93550. }
  93551. else if (this._rootMesh.rotationQuaternion) {
  93552. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  93553. }
  93554. if (this.updateGizmoPositionToMatchAttachedMesh) {
  93555. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  93556. }
  93557. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  93558. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  93559. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  93560. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  93561. }
  93562. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  93563. var dist = this._tempVector.length() * this.scaleRatio;
  93564. this._rootMesh.scaling.set(dist, dist, dist);
  93565. }
  93566. }
  93567. };
  93568. /**
  93569. * Disposes of the gizmo
  93570. */
  93571. Gizmo.prototype.dispose = function () {
  93572. this._rootMesh.dispose();
  93573. if (this._beforeRenderObserver) {
  93574. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  93575. }
  93576. };
  93577. return Gizmo;
  93578. }());
  93579. BABYLON.Gizmo = Gizmo;
  93580. })(BABYLON || (BABYLON = {}));
  93581. //# sourceMappingURL=babylon.gizmo.js.map
  93582. var BABYLON;
  93583. (function (BABYLON) {
  93584. /**
  93585. * Single axis drag gizmo
  93586. */
  93587. var AxisDragGizmo = /** @class */ (function (_super) {
  93588. __extends(AxisDragGizmo, _super);
  93589. /**
  93590. * Creates an AxisDragGizmo
  93591. * @param gizmoLayer The utility layer the gizmo will be added to
  93592. * @param dragAxis The axis which the gizmo will be able to drag on
  93593. * @param color The color of the gizmo
  93594. */
  93595. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  93596. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93597. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93598. var _this = _super.call(this, gizmoLayer) || this;
  93599. _this._pointerObserver = null;
  93600. /**
  93601. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93602. */
  93603. _this.snapDistance = 0;
  93604. /**
  93605. * Event that fires each time the gizmo snaps to a new location.
  93606. * * snapDistance is the the change in distance
  93607. */
  93608. _this.onSnapObservable = new BABYLON.Observable();
  93609. // Create Material
  93610. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93611. coloredMaterial.disableLighting = true;
  93612. coloredMaterial.emissiveColor = color;
  93613. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93614. hoverMaterial.disableLighting = true;
  93615. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93616. // Build mesh on root node
  93617. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93618. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  93619. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93620. arrowTail.color = coloredMaterial.emissiveColor;
  93621. arrow.addChild(arrowMesh);
  93622. arrow.addChild(arrowTail);
  93623. // Position arrow pointing in its drag axis
  93624. arrowMesh.scaling.scaleInPlace(0.05);
  93625. arrowMesh.material = coloredMaterial;
  93626. arrowMesh.rotation.x = Math.PI / 2;
  93627. arrowMesh.position.z += 0.3;
  93628. arrowTail.scaling.scaleInPlace(0.26);
  93629. arrowTail.rotation.x = Math.PI / 2;
  93630. arrowTail.material = coloredMaterial;
  93631. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93632. arrow.scaling.scaleInPlace(1 / 3);
  93633. _this._rootMesh.addChild(arrow);
  93634. var currentSnapDragDistance = 0;
  93635. var tmpVector = new BABYLON.Vector3();
  93636. var tmpSnapEvent = { snapDistance: 0 };
  93637. // Add drag behavior to handle events when the gizmo is dragged
  93638. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93639. _this.dragBehavior.moveAttached = false;
  93640. _this._rootMesh.addBehavior(_this.dragBehavior);
  93641. var localDelta = new BABYLON.Vector3();
  93642. var tmpMatrix = new BABYLON.Matrix();
  93643. _this.dragBehavior.onDragObservable.add(function (event) {
  93644. if (_this.attachedMesh) {
  93645. // Convert delta to local translation if it has a parent
  93646. if (_this.attachedMesh.parent) {
  93647. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93648. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  93649. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  93650. }
  93651. else {
  93652. localDelta.copyFrom(event.delta);
  93653. }
  93654. // Snapping logic
  93655. if (_this.snapDistance == 0) {
  93656. _this.attachedMesh.position.addInPlace(localDelta);
  93657. }
  93658. else {
  93659. currentSnapDragDistance += event.dragDistance;
  93660. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93661. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  93662. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93663. localDelta.normalizeToRef(tmpVector);
  93664. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  93665. _this.attachedMesh.position.addInPlace(tmpVector);
  93666. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93667. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93668. }
  93669. }
  93670. }
  93671. });
  93672. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93673. if (_this._customMeshSet) {
  93674. return;
  93675. }
  93676. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93677. var material = isHovered ? hoverMaterial : coloredMaterial;
  93678. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93679. m.material = material;
  93680. if (m.color) {
  93681. m.color = material.emissiveColor;
  93682. }
  93683. });
  93684. });
  93685. return _this;
  93686. }
  93687. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  93688. if (this.dragBehavior) {
  93689. this.dragBehavior.enabled = value ? true : false;
  93690. }
  93691. };
  93692. /**
  93693. * Disposes of the gizmo
  93694. */
  93695. AxisDragGizmo.prototype.dispose = function () {
  93696. this.onSnapObservable.clear();
  93697. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93698. this.dragBehavior.detach();
  93699. _super.prototype.dispose.call(this);
  93700. };
  93701. return AxisDragGizmo;
  93702. }(BABYLON.Gizmo));
  93703. BABYLON.AxisDragGizmo = AxisDragGizmo;
  93704. })(BABYLON || (BABYLON = {}));
  93705. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  93706. var BABYLON;
  93707. (function (BABYLON) {
  93708. /**
  93709. * Single axis scale gizmo
  93710. */
  93711. var AxisScaleGizmo = /** @class */ (function (_super) {
  93712. __extends(AxisScaleGizmo, _super);
  93713. /**
  93714. * Creates an AxisScaleGizmo
  93715. * @param gizmoLayer The utility layer the gizmo will be added to
  93716. * @param dragAxis The axis which the gizmo will be able to scale on
  93717. * @param color The color of the gizmo
  93718. */
  93719. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  93720. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93721. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93722. var _this = _super.call(this, gizmoLayer) || this;
  93723. _this._pointerObserver = null;
  93724. /**
  93725. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93726. */
  93727. _this.snapDistance = 0;
  93728. /**
  93729. * Event that fires each time the gizmo snaps to a new location.
  93730. * * snapDistance is the the change in distance
  93731. */
  93732. _this.onSnapObservable = new BABYLON.Observable();
  93733. /**
  93734. * If the scaling operation should be done on all axis (default: false)
  93735. */
  93736. _this.uniformScaling = false;
  93737. // Create Material
  93738. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93739. _this._coloredMaterial.disableLighting = true;
  93740. _this._coloredMaterial.emissiveColor = color;
  93741. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93742. hoverMaterial.disableLighting = true;
  93743. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93744. // Build mesh on root node
  93745. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93746. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  93747. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93748. arrowTail.color = _this._coloredMaterial.emissiveColor;
  93749. arrow.addChild(arrowMesh);
  93750. arrow.addChild(arrowTail);
  93751. // Position arrow pointing in its drag axis
  93752. arrowMesh.scaling.scaleInPlace(0.1);
  93753. arrowMesh.material = _this._coloredMaterial;
  93754. arrowMesh.rotation.x = Math.PI / 2;
  93755. arrowMesh.position.z += 0.3;
  93756. arrowTail.scaling.scaleInPlace(0.26);
  93757. arrowTail.rotation.x = Math.PI / 2;
  93758. arrowTail.material = _this._coloredMaterial;
  93759. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93760. _this._rootMesh.addChild(arrow);
  93761. arrow.scaling.scaleInPlace(1 / 3);
  93762. // Add drag behavior to handle events when the gizmo is dragged
  93763. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93764. _this.dragBehavior.moveAttached = false;
  93765. _this._rootMesh.addBehavior(_this.dragBehavior);
  93766. var currentSnapDragDistance = 0;
  93767. var tmpVector = new BABYLON.Vector3();
  93768. var tmpSnapEvent = { snapDistance: 0 };
  93769. _this.dragBehavior.onDragObservable.add(function (event) {
  93770. if (_this.attachedMesh) {
  93771. // Snapping logic
  93772. var snapped = false;
  93773. var dragSteps = 0;
  93774. if (_this.uniformScaling) {
  93775. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  93776. if (tmpVector.y < 0) {
  93777. tmpVector.scaleInPlace(-1);
  93778. }
  93779. }
  93780. else {
  93781. tmpVector.copyFrom(dragAxis);
  93782. }
  93783. if (_this.snapDistance == 0) {
  93784. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  93785. }
  93786. else {
  93787. currentSnapDragDistance += event.dragDistance;
  93788. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93789. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93790. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93791. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  93792. snapped = true;
  93793. }
  93794. else {
  93795. tmpVector.scaleInPlace(0);
  93796. }
  93797. }
  93798. _this.attachedMesh.scaling.addInPlace(tmpVector);
  93799. if (snapped) {
  93800. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93801. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93802. }
  93803. }
  93804. });
  93805. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93806. if (_this._customMeshSet) {
  93807. return;
  93808. }
  93809. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93810. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  93811. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93812. m.material = material;
  93813. if (m.color) {
  93814. m.color = material.emissiveColor;
  93815. }
  93816. });
  93817. });
  93818. return _this;
  93819. }
  93820. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  93821. if (this.dragBehavior) {
  93822. this.dragBehavior.enabled = value ? true : false;
  93823. }
  93824. };
  93825. /**
  93826. * Disposes of the gizmo
  93827. */
  93828. AxisScaleGizmo.prototype.dispose = function () {
  93829. this.onSnapObservable.clear();
  93830. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93831. this.dragBehavior.detach();
  93832. _super.prototype.dispose.call(this);
  93833. };
  93834. /**
  93835. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93836. * @param mesh The mesh to replace the default mesh of the gizmo
  93837. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  93838. */
  93839. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  93840. var _this = this;
  93841. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  93842. _super.prototype.setCustomMesh.call(this, mesh);
  93843. if (useGizmoMaterial) {
  93844. this._rootMesh.getChildMeshes().forEach(function (m) {
  93845. m.material = _this._coloredMaterial;
  93846. if (m.color) {
  93847. m.color = _this._coloredMaterial.emissiveColor;
  93848. }
  93849. });
  93850. this._customMeshSet = false;
  93851. }
  93852. };
  93853. return AxisScaleGizmo;
  93854. }(BABYLON.Gizmo));
  93855. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  93856. })(BABYLON || (BABYLON = {}));
  93857. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  93858. var BABYLON;
  93859. (function (BABYLON) {
  93860. /**
  93861. * Single plane rotation gizmo
  93862. */
  93863. var PlaneRotationGizmo = /** @class */ (function (_super) {
  93864. __extends(PlaneRotationGizmo, _super);
  93865. /**
  93866. * Creates a PlaneRotationGizmo
  93867. * @param gizmoLayer The utility layer the gizmo will be added to
  93868. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  93869. * @param color The color of the gizmo
  93870. */
  93871. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  93872. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93873. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93874. var _this = _super.call(this, gizmoLayer) || this;
  93875. _this._pointerObserver = null;
  93876. /**
  93877. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  93878. */
  93879. _this.snapDistance = 0;
  93880. /**
  93881. * Event that fires each time the gizmo snaps to a new location.
  93882. * * snapDistance is the the change in distance
  93883. */
  93884. _this.onSnapObservable = new BABYLON.Observable();
  93885. // Create Material
  93886. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93887. coloredMaterial.disableLighting = true;
  93888. coloredMaterial.emissiveColor = color;
  93889. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93890. hoverMaterial.disableLighting = true;
  93891. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93892. // Build mesh on root node
  93893. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93894. // Create circle out of lines
  93895. var tessellation = 20;
  93896. var radius = 0.8;
  93897. var points = new Array();
  93898. for (var i = 0; i < tessellation; i++) {
  93899. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  93900. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  93901. }
  93902. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  93903. rotationMesh.color = coloredMaterial.emissiveColor;
  93904. // Position arrow pointing in its drag axis
  93905. rotationMesh.scaling.scaleInPlace(0.26);
  93906. rotationMesh.material = coloredMaterial;
  93907. rotationMesh.rotation.x = Math.PI / 2;
  93908. parentMesh.addChild(rotationMesh);
  93909. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  93910. _this._rootMesh.addChild(parentMesh);
  93911. parentMesh.scaling.scaleInPlace(1 / 3);
  93912. // Add drag behavior to handle events when the gizmo is dragged
  93913. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  93914. _this.dragBehavior.moveAttached = false;
  93915. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  93916. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  93917. _this._rootMesh.addBehavior(_this.dragBehavior);
  93918. var lastDragPosition = new BABYLON.Vector3();
  93919. _this.dragBehavior.onDragStartObservable.add(function (e) {
  93920. if (_this.attachedMesh) {
  93921. lastDragPosition.copyFrom(e.dragPlanePoint);
  93922. }
  93923. });
  93924. var rotationMatrix = new BABYLON.Matrix();
  93925. var planeNormalTowardsCamera = new BABYLON.Vector3();
  93926. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  93927. var tmpSnapEvent = { snapDistance: 0 };
  93928. var currentSnapDragDistance = 0;
  93929. var tmpMatrix = new BABYLON.Matrix();
  93930. var tmpVector = new BABYLON.Vector3();
  93931. var amountToRotate = new BABYLON.Quaternion();
  93932. _this.dragBehavior.onDragObservable.add(function (event) {
  93933. if (_this.attachedMesh) {
  93934. if (!_this.attachedMesh.rotationQuaternion) {
  93935. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93936. }
  93937. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  93938. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  93939. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  93940. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  93941. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  93942. var angle = Math.atan2(cross.length(), dot);
  93943. planeNormalTowardsCamera.copyFrom(planeNormal);
  93944. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  93945. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93946. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  93947. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  93948. }
  93949. // Flip up vector depending on which side the camera is on
  93950. if (gizmoLayer.utilityLayerScene.activeCamera) {
  93951. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  93952. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  93953. planeNormalTowardsCamera.scaleInPlace(-1);
  93954. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  93955. }
  93956. }
  93957. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  93958. if (halfCircleSide)
  93959. angle = -angle;
  93960. // Snapping logic
  93961. var snapped = false;
  93962. if (_this.snapDistance != 0) {
  93963. currentSnapDragDistance += angle;
  93964. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93965. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93966. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93967. angle = _this.snapDistance * dragSteps;
  93968. snapped = true;
  93969. }
  93970. else {
  93971. angle = 0;
  93972. }
  93973. }
  93974. // If the mesh has a parent, convert needed world rotation to local rotation
  93975. tmpMatrix.reset();
  93976. if (_this.attachedMesh.parent) {
  93977. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93978. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  93979. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  93980. }
  93981. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  93982. var quaternionCoefficient = Math.sin(angle / 2);
  93983. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  93984. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  93985. if (tmpMatrix.determinant() > 0) {
  93986. amountToRotate.toEulerAnglesToRef(tmpVector);
  93987. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  93988. }
  93989. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93990. // Rotate selected mesh quaternion over fixed axis
  93991. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  93992. }
  93993. else {
  93994. // Rotate selected mesh quaternion over rotated axis
  93995. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  93996. }
  93997. lastDragPosition.copyFrom(event.dragPlanePoint);
  93998. if (snapped) {
  93999. tmpSnapEvent.snapDistance = angle;
  94000. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94001. }
  94002. }
  94003. });
  94004. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94005. if (_this._customMeshSet) {
  94006. return;
  94007. }
  94008. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94009. var material = isHovered ? hoverMaterial : coloredMaterial;
  94010. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94011. m.material = material;
  94012. if (m.color) {
  94013. m.color = material.emissiveColor;
  94014. }
  94015. });
  94016. });
  94017. return _this;
  94018. }
  94019. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  94020. if (this.dragBehavior) {
  94021. this.dragBehavior.enabled = value ? true : false;
  94022. }
  94023. };
  94024. /**
  94025. * Disposes of the gizmo
  94026. */
  94027. PlaneRotationGizmo.prototype.dispose = function () {
  94028. this.onSnapObservable.clear();
  94029. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94030. this.dragBehavior.detach();
  94031. _super.prototype.dispose.call(this);
  94032. };
  94033. return PlaneRotationGizmo;
  94034. }(BABYLON.Gizmo));
  94035. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  94036. })(BABYLON || (BABYLON = {}));
  94037. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  94038. var BABYLON;
  94039. (function (BABYLON) {
  94040. /**
  94041. * Gizmo that enables dragging a mesh along 3 axis
  94042. */
  94043. var PositionGizmo = /** @class */ (function (_super) {
  94044. __extends(PositionGizmo, _super);
  94045. /**
  94046. * Creates a PositionGizmo
  94047. * @param gizmoLayer The utility layer the gizmo will be added to
  94048. */
  94049. function PositionGizmo(gizmoLayer) {
  94050. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94051. var _this = _super.call(this, gizmoLayer) || this;
  94052. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94053. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94054. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94055. _this.attachedMesh = null;
  94056. return _this;
  94057. }
  94058. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  94059. set: function (mesh) {
  94060. if (this.xGizmo) {
  94061. this.xGizmo.attachedMesh = mesh;
  94062. this.yGizmo.attachedMesh = mesh;
  94063. this.zGizmo.attachedMesh = mesh;
  94064. }
  94065. },
  94066. enumerable: true,
  94067. configurable: true
  94068. });
  94069. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94070. get: function () {
  94071. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94072. },
  94073. set: function (value) {
  94074. if (this.xGizmo) {
  94075. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94076. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94077. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94078. }
  94079. },
  94080. enumerable: true,
  94081. configurable: true
  94082. });
  94083. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  94084. get: function () {
  94085. return this.xGizmo.snapDistance;
  94086. },
  94087. /**
  94088. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94089. */
  94090. set: function (value) {
  94091. if (this.xGizmo) {
  94092. this.xGizmo.snapDistance = value;
  94093. this.yGizmo.snapDistance = value;
  94094. this.zGizmo.snapDistance = value;
  94095. }
  94096. },
  94097. enumerable: true,
  94098. configurable: true
  94099. });
  94100. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  94101. get: function () {
  94102. return this.xGizmo.scaleRatio;
  94103. },
  94104. /**
  94105. * Ratio for the scale of the gizmo (Default: 1)
  94106. */
  94107. set: function (value) {
  94108. if (this.xGizmo) {
  94109. this.xGizmo.scaleRatio = value;
  94110. this.yGizmo.scaleRatio = value;
  94111. this.zGizmo.scaleRatio = value;
  94112. }
  94113. },
  94114. enumerable: true,
  94115. configurable: true
  94116. });
  94117. /**
  94118. * Disposes of the gizmo
  94119. */
  94120. PositionGizmo.prototype.dispose = function () {
  94121. this.xGizmo.dispose();
  94122. this.yGizmo.dispose();
  94123. this.zGizmo.dispose();
  94124. };
  94125. /**
  94126. * CustomMeshes are not supported by this gizmo
  94127. * @param mesh The mesh to replace the default mesh of the gizmo
  94128. */
  94129. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  94130. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  94131. };
  94132. return PositionGizmo;
  94133. }(BABYLON.Gizmo));
  94134. BABYLON.PositionGizmo = PositionGizmo;
  94135. })(BABYLON || (BABYLON = {}));
  94136. //# sourceMappingURL=babylon.positionGizmo.js.map
  94137. var BABYLON;
  94138. (function (BABYLON) {
  94139. /**
  94140. * Gizmo that enables rotating a mesh along 3 axis
  94141. */
  94142. var RotationGizmo = /** @class */ (function (_super) {
  94143. __extends(RotationGizmo, _super);
  94144. /**
  94145. * Creates a RotationGizmo
  94146. * @param gizmoLayer The utility layer the gizmo will be added to
  94147. */
  94148. function RotationGizmo(gizmoLayer) {
  94149. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94150. var _this = _super.call(this, gizmoLayer) || this;
  94151. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94152. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94153. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94154. _this.attachedMesh = null;
  94155. return _this;
  94156. }
  94157. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  94158. set: function (mesh) {
  94159. if (this.xGizmo) {
  94160. this.xGizmo.attachedMesh = mesh;
  94161. this.yGizmo.attachedMesh = mesh;
  94162. this.zGizmo.attachedMesh = mesh;
  94163. }
  94164. },
  94165. enumerable: true,
  94166. configurable: true
  94167. });
  94168. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94169. get: function () {
  94170. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94171. },
  94172. set: function (value) {
  94173. if (this.xGizmo) {
  94174. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94175. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94176. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94177. }
  94178. },
  94179. enumerable: true,
  94180. configurable: true
  94181. });
  94182. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  94183. get: function () {
  94184. return this.xGizmo.snapDistance;
  94185. },
  94186. /**
  94187. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94188. */
  94189. set: function (value) {
  94190. if (this.xGizmo) {
  94191. this.xGizmo.snapDistance = value;
  94192. this.yGizmo.snapDistance = value;
  94193. this.zGizmo.snapDistance = value;
  94194. }
  94195. },
  94196. enumerable: true,
  94197. configurable: true
  94198. });
  94199. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  94200. get: function () {
  94201. return this.xGizmo.scaleRatio;
  94202. },
  94203. /**
  94204. * Ratio for the scale of the gizmo (Default: 1)
  94205. */
  94206. set: function (value) {
  94207. if (this.xGizmo) {
  94208. this.xGizmo.scaleRatio = value;
  94209. this.yGizmo.scaleRatio = value;
  94210. this.zGizmo.scaleRatio = value;
  94211. }
  94212. },
  94213. enumerable: true,
  94214. configurable: true
  94215. });
  94216. /**
  94217. * Disposes of the gizmo
  94218. */
  94219. RotationGizmo.prototype.dispose = function () {
  94220. this.xGizmo.dispose();
  94221. this.yGizmo.dispose();
  94222. this.zGizmo.dispose();
  94223. };
  94224. /**
  94225. * CustomMeshes are not supported by this gizmo
  94226. * @param mesh The mesh to replace the default mesh of the gizmo
  94227. */
  94228. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  94229. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  94230. };
  94231. return RotationGizmo;
  94232. }(BABYLON.Gizmo));
  94233. BABYLON.RotationGizmo = RotationGizmo;
  94234. })(BABYLON || (BABYLON = {}));
  94235. //# sourceMappingURL=babylon.rotationGizmo.js.map
  94236. var BABYLON;
  94237. (function (BABYLON) {
  94238. /**
  94239. * Gizmo that enables scaling a mesh along 3 axis
  94240. */
  94241. var ScaleGizmo = /** @class */ (function (_super) {
  94242. __extends(ScaleGizmo, _super);
  94243. /**
  94244. * Creates a ScaleGizmo
  94245. * @param gizmoLayer The utility layer the gizmo will be added to
  94246. */
  94247. function ScaleGizmo(gizmoLayer) {
  94248. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94249. var _this = _super.call(this, gizmoLayer) || this;
  94250. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94251. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94252. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94253. // Create uniform scale gizmo
  94254. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  94255. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94256. _this._uniformGizmo.uniformScaling = true;
  94257. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  94258. octahedron.scaling.scaleInPlace(0.007);
  94259. _this._uniformGizmo.setCustomMesh(octahedron, true);
  94260. _this.attachedMesh = null;
  94261. return _this;
  94262. }
  94263. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  94264. set: function (mesh) {
  94265. if (this.xGizmo) {
  94266. this.xGizmo.attachedMesh = mesh;
  94267. this.yGizmo.attachedMesh = mesh;
  94268. this.zGizmo.attachedMesh = mesh;
  94269. this._uniformGizmo.attachedMesh = mesh;
  94270. }
  94271. },
  94272. enumerable: true,
  94273. configurable: true
  94274. });
  94275. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94276. get: function () {
  94277. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94278. },
  94279. set: function (value) {
  94280. if (this.xGizmo) {
  94281. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94282. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94283. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94284. }
  94285. },
  94286. enumerable: true,
  94287. configurable: true
  94288. });
  94289. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  94290. get: function () {
  94291. return this.xGizmo.snapDistance;
  94292. },
  94293. /**
  94294. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94295. */
  94296. set: function (value) {
  94297. if (this.xGizmo) {
  94298. this.xGizmo.snapDistance = value;
  94299. this.yGizmo.snapDistance = value;
  94300. this.zGizmo.snapDistance = value;
  94301. this._uniformGizmo.snapDistance = value;
  94302. }
  94303. },
  94304. enumerable: true,
  94305. configurable: true
  94306. });
  94307. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  94308. get: function () {
  94309. return this.xGizmo.scaleRatio;
  94310. },
  94311. /**
  94312. * Ratio for the scale of the gizmo (Default: 1)
  94313. */
  94314. set: function (value) {
  94315. if (this.xGizmo) {
  94316. this.xGizmo.scaleRatio = value;
  94317. this.yGizmo.scaleRatio = value;
  94318. this.zGizmo.scaleRatio = value;
  94319. this._uniformGizmo.scaleRatio = value;
  94320. }
  94321. },
  94322. enumerable: true,
  94323. configurable: true
  94324. });
  94325. /**
  94326. * Disposes of the gizmo
  94327. */
  94328. ScaleGizmo.prototype.dispose = function () {
  94329. this.xGizmo.dispose();
  94330. this.yGizmo.dispose();
  94331. this.zGizmo.dispose();
  94332. this._uniformGizmo.dispose();
  94333. };
  94334. return ScaleGizmo;
  94335. }(BABYLON.Gizmo));
  94336. BABYLON.ScaleGizmo = ScaleGizmo;
  94337. })(BABYLON || (BABYLON = {}));
  94338. //# sourceMappingURL=babylon.scaleGizmo.js.map
  94339. var BABYLON;
  94340. (function (BABYLON) {
  94341. /**
  94342. * Bounding box gizmo
  94343. */
  94344. var BoundingBoxGizmo = /** @class */ (function (_super) {
  94345. __extends(BoundingBoxGizmo, _super);
  94346. /**
  94347. * Creates an BoundingBoxGizmo
  94348. * @param gizmoLayer The utility layer the gizmo will be added to
  94349. * @param color The color of the gizmo
  94350. */
  94351. function BoundingBoxGizmo(color, gizmoLayer) {
  94352. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94353. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  94354. var _this = _super.call(this, gizmoLayer) || this;
  94355. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  94356. _this._renderObserver = null;
  94357. _this._pointerObserver = null;
  94358. _this._scaleDragSpeed = 0.2;
  94359. _this._tmpQuaternion = new BABYLON.Quaternion();
  94360. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94361. _this._tmpRotationMatrix = new BABYLON.Matrix();
  94362. /**
  94363. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  94364. */
  94365. _this.ignoreChildren = false;
  94366. /**
  94367. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  94368. */
  94369. _this.includeChildPredicate = null;
  94370. /**
  94371. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  94372. */
  94373. _this.rotationSphereSize = 0.1;
  94374. /**
  94375. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  94376. */
  94377. _this.scaleBoxSize = 0.1;
  94378. /**
  94379. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  94380. */
  94381. _this.fixedDragMeshScreenSize = false;
  94382. /**
  94383. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  94384. */
  94385. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  94386. /**
  94387. * Fired when a rotation sphere or scale box is dragged
  94388. */
  94389. _this.onDragStartObservable = new BABYLON.Observable();
  94390. /**
  94391. * Fired when a scale box is dragged
  94392. */
  94393. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  94394. /**
  94395. * Fired when a scale box drag is ended
  94396. */
  94397. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  94398. /**
  94399. * Fired when a rotation sphere is dragged
  94400. */
  94401. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  94402. /**
  94403. * Fired when a rotation sphere drag is ended
  94404. */
  94405. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  94406. /**
  94407. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  94408. */
  94409. _this.scalePivot = null;
  94410. _this._existingMeshScale = new BABYLON.Vector3();
  94411. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  94412. _this._updateScale = false;
  94413. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  94414. // Create Materials
  94415. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94416. coloredMaterial.disableLighting = true;
  94417. coloredMaterial.emissiveColor = color;
  94418. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94419. hoverColoredMaterial.disableLighting = true;
  94420. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94421. // Build bounding box out of lines
  94422. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94423. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  94424. var lines = [];
  94425. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  94426. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94427. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94428. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94429. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94430. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94431. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94432. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94433. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94434. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94435. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94436. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94437. lines.forEach(function (l) {
  94438. l.color = color;
  94439. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  94440. l.isPickable = false;
  94441. _this._lineBoundingBox.addChild(l);
  94442. });
  94443. _this._rootMesh.addChild(_this._lineBoundingBox);
  94444. // Create rotation spheres
  94445. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94446. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  94447. var _loop_1 = function (i_1) {
  94448. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  94449. sphere.rotationQuaternion = new BABYLON.Quaternion();
  94450. sphere.material = coloredMaterial;
  94451. // Drag behavior
  94452. _dragBehavior = new BABYLON.PointerDragBehavior({});
  94453. _dragBehavior.moveAttached = false;
  94454. _dragBehavior.updateDragPlane = false;
  94455. sphere.addBehavior(_dragBehavior);
  94456. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  94457. var totalTurnAmountOfDrag = 0;
  94458. _dragBehavior.onDragStartObservable.add(function (event) {
  94459. startingTurnDirection.copyFrom(sphere.forward);
  94460. totalTurnAmountOfDrag = 0;
  94461. });
  94462. _dragBehavior.onDragObservable.add(function (event) {
  94463. _this.onRotationSphereDragObservable.notifyObservers({});
  94464. if (_this.attachedMesh) {
  94465. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94466. var worldDragDirection = startingTurnDirection;
  94467. // Project the world right on to the drag plane
  94468. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  94469. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  94470. // project drag delta on to the resulting drag axis and rotate based on that
  94471. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  94472. // Make rotation relative to size of mesh.
  94473. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94474. // Rotate based on axis
  94475. if (!_this.attachedMesh.rotationQuaternion) {
  94476. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94477. }
  94478. if (!_this._anchorMesh.rotationQuaternion) {
  94479. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  94480. }
  94481. // Do not allow the object to turn more than a full circle
  94482. totalTurnAmountOfDrag += projectDist;
  94483. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  94484. if (i_1 >= 8) {
  94485. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  94486. }
  94487. else if (i_1 >= 4) {
  94488. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  94489. }
  94490. else {
  94491. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  94492. }
  94493. // Rotate around center of bounding box
  94494. _this._anchorMesh.addChild(_this.attachedMesh);
  94495. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  94496. _this._anchorMesh.removeChild(_this.attachedMesh);
  94497. }
  94498. _this.updateBoundingBox();
  94499. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94500. }
  94501. });
  94502. // Selection/deselection
  94503. _dragBehavior.onDragStartObservable.add(function () {
  94504. _this.onDragStartObservable.notifyObservers({});
  94505. _this._selectNode(sphere);
  94506. });
  94507. _dragBehavior.onDragEndObservable.add(function () {
  94508. _this.onRotationSphereDragEndObservable.notifyObservers({});
  94509. _this._selectNode(null);
  94510. });
  94511. this_1._rotateSpheresParent.addChild(sphere);
  94512. };
  94513. var this_1 = this, _dragBehavior;
  94514. for (var i_1 = 0; i_1 < 12; i_1++) {
  94515. _loop_1(i_1);
  94516. }
  94517. _this._rootMesh.addChild(_this._rotateSpheresParent);
  94518. // Create scale cubes
  94519. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94520. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  94521. for (var i = 0; i < 2; i++) {
  94522. for (var j = 0; j < 2; j++) {
  94523. var _loop_2 = function () {
  94524. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  94525. box.material = coloredMaterial;
  94526. // Dragging logic
  94527. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  94528. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94529. _dragBehavior.moveAttached = false;
  94530. box.addBehavior(_dragBehavior);
  94531. _dragBehavior.onDragObservable.add(function (event) {
  94532. _this.onScaleBoxDragObservable.notifyObservers({});
  94533. if (_this.attachedMesh) {
  94534. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94535. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94536. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  94537. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  94538. _this.updateBoundingBox();
  94539. if (_this.scalePivot) {
  94540. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  94541. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  94542. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  94543. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  94544. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  94545. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  94546. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  94547. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  94548. }
  94549. else {
  94550. // Scale from the position of the opposite corner
  94551. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  94552. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  94553. }
  94554. _this._anchorMesh.addChild(_this.attachedMesh);
  94555. _this._anchorMesh.scaling.addInPlace(deltaScale);
  94556. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  94557. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  94558. }
  94559. _this._anchorMesh.removeChild(_this.attachedMesh);
  94560. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94561. }
  94562. });
  94563. // Selection/deselection
  94564. _dragBehavior.onDragStartObservable.add(function () {
  94565. _this.onDragStartObservable.notifyObservers({});
  94566. _this._selectNode(box);
  94567. });
  94568. _dragBehavior.onDragEndObservable.add(function () {
  94569. _this.onScaleBoxDragEndObservable.notifyObservers({});
  94570. _this._selectNode(null);
  94571. });
  94572. this_2._scaleBoxesParent.addChild(box);
  94573. };
  94574. var this_2 = this, _dragBehavior;
  94575. for (var k = 0; k < 2; k++) {
  94576. _loop_2();
  94577. }
  94578. }
  94579. }
  94580. _this._rootMesh.addChild(_this._scaleBoxesParent);
  94581. // Hover color change
  94582. var pointerIds = new Array();
  94583. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94584. if (!pointerIds[pointerInfo.event.pointerId]) {
  94585. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  94586. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  94587. pointerIds[pointerInfo.event.pointerId] = mesh;
  94588. mesh.material = hoverColoredMaterial;
  94589. }
  94590. });
  94591. }
  94592. else {
  94593. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  94594. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  94595. delete pointerIds[pointerInfo.event.pointerId];
  94596. }
  94597. }
  94598. });
  94599. // Update bounding box positions
  94600. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  94601. // Only update the bouding box if scaling has changed
  94602. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  94603. _this.updateBoundingBox();
  94604. }
  94605. });
  94606. _this.updateBoundingBox();
  94607. return _this;
  94608. }
  94609. /** @hidden */
  94610. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  94611. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  94612. // Save old pivot and set pivot to 0,0,0
  94613. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  94614. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  94615. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  94616. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  94617. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94618. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94619. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94620. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  94621. }
  94622. }
  94623. BoundingBoxGizmo._PivotCached++;
  94624. };
  94625. /** @hidden */
  94626. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  94627. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  94628. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  94629. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94630. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94631. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94632. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  94633. }
  94634. this._PivotCached--;
  94635. };
  94636. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  94637. if (value) {
  94638. // Reset anchor mesh to match attached mesh's scale
  94639. // This is needed to avoid invalid box/sphere position on first drag
  94640. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  94641. this._anchorMesh.addChild(value);
  94642. this._anchorMesh.removeChild(value);
  94643. BoundingBoxGizmo._RestorePivotPoint(value);
  94644. this.updateBoundingBox();
  94645. }
  94646. };
  94647. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  94648. this._rotateSpheresParent.getChildMeshes()
  94649. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  94650. m.isVisible = (!selectedMesh || m == selectedMesh);
  94651. });
  94652. };
  94653. /**
  94654. * Updates the bounding box information for the Gizmo
  94655. */
  94656. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  94657. if (this.attachedMesh) {
  94658. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  94659. this._update();
  94660. // Rotate based on axis
  94661. if (!this.attachedMesh.rotationQuaternion) {
  94662. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  94663. }
  94664. if (!this._anchorMesh.rotationQuaternion) {
  94665. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  94666. }
  94667. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94668. // Store original position and reset mesh to origin before computing the bounding box
  94669. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94670. this._tmpVector.copyFrom(this.attachedMesh.position);
  94671. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  94672. this.attachedMesh.position.set(0, 0, 0);
  94673. // Update bounding dimensions/positions
  94674. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  94675. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  94676. // Update gizmo to match bounding box scaling and rotation
  94677. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  94678. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  94679. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  94680. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  94681. this._lineBoundingBox.computeWorldMatrix();
  94682. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  94683. // restore position/rotation values
  94684. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  94685. this.attachedMesh.position.copyFrom(this._tmpVector);
  94686. }
  94687. // Update rotation sphere locations
  94688. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  94689. for (var i = 0; i < 3; i++) {
  94690. for (var j = 0; j < 2; j++) {
  94691. for (var k = 0; k < 2; k++) {
  94692. var index = ((i * 4) + (j * 2)) + k;
  94693. if (i == 0) {
  94694. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94695. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94696. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94697. }
  94698. if (i == 1) {
  94699. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  94700. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94701. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94702. }
  94703. if (i == 2) {
  94704. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  94705. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94706. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94707. }
  94708. if (this.fixedDragMeshScreenSize) {
  94709. this._rootMesh.computeWorldMatrix();
  94710. this._rotateSpheresParent.computeWorldMatrix();
  94711. rotateSpheres[index].computeWorldMatrix();
  94712. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94713. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94714. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94715. }
  94716. else {
  94717. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  94718. }
  94719. }
  94720. }
  94721. }
  94722. // Update scale box locations
  94723. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  94724. for (var i = 0; i < 2; i++) {
  94725. for (var j = 0; j < 2; j++) {
  94726. for (var k = 0; k < 2; k++) {
  94727. var index = ((i * 4) + (j * 2)) + k;
  94728. if (scaleBoxes[index]) {
  94729. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94730. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94731. if (this.fixedDragMeshScreenSize) {
  94732. this._rootMesh.computeWorldMatrix();
  94733. this._scaleBoxesParent.computeWorldMatrix();
  94734. scaleBoxes[index].computeWorldMatrix();
  94735. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94736. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94737. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94738. }
  94739. else {
  94740. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  94741. }
  94742. }
  94743. }
  94744. }
  94745. }
  94746. if (this.attachedMesh) {
  94747. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  94748. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  94749. }
  94750. };
  94751. /**
  94752. * Enables rotation on the specified axis and disables rotation on the others
  94753. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  94754. */
  94755. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  94756. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  94757. if (i < 4) {
  94758. m.setEnabled(axis.indexOf("x") != -1);
  94759. }
  94760. else if (i < 8) {
  94761. m.setEnabled(axis.indexOf("y") != -1);
  94762. }
  94763. else {
  94764. m.setEnabled(axis.indexOf("z") != -1);
  94765. }
  94766. });
  94767. };
  94768. /**
  94769. * Disposes of the gizmo
  94770. */
  94771. BoundingBoxGizmo.prototype.dispose = function () {
  94772. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94773. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  94774. this._lineBoundingBox.dispose();
  94775. this._rotateSpheresParent.dispose();
  94776. this._scaleBoxesParent.dispose();
  94777. _super.prototype.dispose.call(this);
  94778. };
  94779. /**
  94780. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  94781. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  94782. * @returns the bounding box mesh with the passed in mesh as a child
  94783. */
  94784. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  94785. var makeNotPickable = function (root) {
  94786. root.isPickable = false;
  94787. root.getChildMeshes().forEach(function (c) {
  94788. makeNotPickable(c);
  94789. });
  94790. };
  94791. makeNotPickable(mesh);
  94792. // Reset position to get boudning box from origin with no rotation
  94793. if (!mesh.rotationQuaternion) {
  94794. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  94795. }
  94796. var oldPos = mesh.position.clone();
  94797. var oldRot = mesh.rotationQuaternion.clone();
  94798. mesh.rotationQuaternion.set(0, 0, 0, 1);
  94799. mesh.position.set(0, 0, 0);
  94800. // Update bounding dimensions/positions
  94801. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  94802. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  94803. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  94804. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  94805. // Restore original positions
  94806. mesh.addChild(box);
  94807. mesh.rotationQuaternion.copyFrom(oldRot);
  94808. mesh.position.copyFrom(oldPos);
  94809. // Reverse parenting
  94810. mesh.removeChild(box);
  94811. box.addChild(mesh);
  94812. box.visibility = 0;
  94813. return box;
  94814. };
  94815. /**
  94816. * CustomMeshes are not supported by this gizmo
  94817. * @param mesh The mesh to replace the default mesh of the gizmo
  94818. */
  94819. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  94820. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  94821. };
  94822. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  94823. // store/remove pivot point should only be applied during their outermost calls
  94824. BoundingBoxGizmo._PivotCached = 0;
  94825. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  94826. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  94827. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  94828. return BoundingBoxGizmo;
  94829. }(BABYLON.Gizmo));
  94830. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  94831. })(BABYLON || (BABYLON = {}));
  94832. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  94833. var BABYLON;
  94834. (function (BABYLON) {
  94835. /**
  94836. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  94837. */
  94838. var GizmoManager = /** @class */ (function () {
  94839. /**
  94840. * Instatiates a gizmo manager
  94841. * @param scene the scene to overlay the gizmos on top of
  94842. */
  94843. function GizmoManager(scene) {
  94844. var _this = this;
  94845. this.scene = scene;
  94846. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  94847. this._pointerObserver = null;
  94848. this._attachedMesh = null;
  94849. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  94850. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  94851. /**
  94852. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  94853. */
  94854. this.attachableMeshes = null;
  94855. /**
  94856. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  94857. */
  94858. this.usePointerToAttachGizmos = true;
  94859. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  94860. // Instatiate/dispose gizmos based on pointer actions
  94861. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  94862. if (!_this.usePointerToAttachGizmos) {
  94863. return;
  94864. }
  94865. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  94866. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  94867. var node = pointerInfo.pickInfo.pickedMesh;
  94868. if (_this.attachableMeshes == null) {
  94869. // Attach to the most parent node
  94870. while (node && node.parent != null) {
  94871. node = node.parent;
  94872. }
  94873. }
  94874. else {
  94875. // Attach to the parent node that is an attachableMesh
  94876. var found = false;
  94877. _this.attachableMeshes.forEach(function (mesh) {
  94878. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  94879. node = mesh;
  94880. found = true;
  94881. }
  94882. });
  94883. if (!found) {
  94884. node = null;
  94885. }
  94886. }
  94887. if (node instanceof BABYLON.AbstractMesh) {
  94888. _this.attachToMesh(node);
  94889. }
  94890. else {
  94891. _this.attachToMesh(null);
  94892. }
  94893. }
  94894. else {
  94895. _this.attachToMesh(null);
  94896. }
  94897. }
  94898. });
  94899. }
  94900. /**
  94901. * Attaches a set of gizmos to the specified mesh
  94902. * @param mesh The mesh the gizmo's should be attached to
  94903. */
  94904. GizmoManager.prototype.attachToMesh = function (mesh) {
  94905. if (this._attachedMesh) {
  94906. this._attachedMesh.removeBehavior(this._dragBehavior);
  94907. }
  94908. this._attachedMesh = mesh;
  94909. for (var key in this.gizmos) {
  94910. var gizmo = (this.gizmos[key]);
  94911. if (gizmo && this._gizmosEnabled[key]) {
  94912. gizmo.attachedMesh = mesh;
  94913. }
  94914. }
  94915. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  94916. this._attachedMesh.addBehavior(this._dragBehavior);
  94917. }
  94918. };
  94919. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  94920. get: function () {
  94921. return this._gizmosEnabled.positionGizmo;
  94922. },
  94923. /**
  94924. * If the position gizmo is enabled
  94925. */
  94926. set: function (value) {
  94927. if (value) {
  94928. if (!this.gizmos.positionGizmo) {
  94929. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  94930. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94931. }
  94932. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  94933. }
  94934. else if (this.gizmos.positionGizmo) {
  94935. this.gizmos.positionGizmo.attachedMesh = null;
  94936. }
  94937. this._gizmosEnabled.positionGizmo = value;
  94938. },
  94939. enumerable: true,
  94940. configurable: true
  94941. });
  94942. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  94943. get: function () {
  94944. return this._gizmosEnabled.rotationGizmo;
  94945. },
  94946. /**
  94947. * If the rotation gizmo is enabled
  94948. */
  94949. set: function (value) {
  94950. if (value) {
  94951. if (!this.gizmos.rotationGizmo) {
  94952. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  94953. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94954. }
  94955. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  94956. }
  94957. else if (this.gizmos.rotationGizmo) {
  94958. this.gizmos.rotationGizmo.attachedMesh = null;
  94959. }
  94960. this._gizmosEnabled.rotationGizmo = value;
  94961. },
  94962. enumerable: true,
  94963. configurable: true
  94964. });
  94965. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  94966. get: function () {
  94967. return this._gizmosEnabled.scaleGizmo;
  94968. },
  94969. /**
  94970. * If the scale gizmo is enabled
  94971. */
  94972. set: function (value) {
  94973. if (value) {
  94974. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  94975. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  94976. }
  94977. else if (this.gizmos.scaleGizmo) {
  94978. this.gizmos.scaleGizmo.attachedMesh = null;
  94979. }
  94980. this._gizmosEnabled.scaleGizmo = value;
  94981. },
  94982. enumerable: true,
  94983. configurable: true
  94984. });
  94985. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  94986. get: function () {
  94987. return this._gizmosEnabled.boundingBoxGizmo;
  94988. },
  94989. /**
  94990. * If the boundingBox gizmo is enabled
  94991. */
  94992. set: function (value) {
  94993. if (value) {
  94994. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  94995. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  94996. if (this._attachedMesh) {
  94997. this._attachedMesh.removeBehavior(this._dragBehavior);
  94998. this._attachedMesh.addBehavior(this._dragBehavior);
  94999. }
  95000. }
  95001. else if (this.gizmos.boundingBoxGizmo) {
  95002. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  95003. }
  95004. this._gizmosEnabled.boundingBoxGizmo = value;
  95005. },
  95006. enumerable: true,
  95007. configurable: true
  95008. });
  95009. /**
  95010. * Disposes of the gizmo manager
  95011. */
  95012. GizmoManager.prototype.dispose = function () {
  95013. this.scene.onPointerObservable.remove(this._pointerObserver);
  95014. for (var key in this.gizmos) {
  95015. var gizmo = (this.gizmos[key]);
  95016. if (gizmo) {
  95017. gizmo.dispose();
  95018. }
  95019. }
  95020. this._dragBehavior.detach();
  95021. };
  95022. return GizmoManager;
  95023. }());
  95024. BABYLON.GizmoManager = GizmoManager;
  95025. })(BABYLON || (BABYLON = {}));
  95026. //# sourceMappingURL=babylon.gizmoManager.js.map
  95027. var BABYLON;
  95028. (function (BABYLON) {
  95029. /**
  95030. * Defines a target to use with MorphTargetManager
  95031. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95032. */
  95033. var MorphTarget = /** @class */ (function () {
  95034. /**
  95035. * Creates a new MorphTarget
  95036. * @param name defines the name of the target
  95037. * @param influence defines the influence to use
  95038. */
  95039. function MorphTarget(
  95040. /** defines the name of the target */
  95041. name, influence, scene) {
  95042. if (influence === void 0) { influence = 0; }
  95043. if (scene === void 0) { scene = null; }
  95044. this.name = name;
  95045. /**
  95046. * Gets or sets the list of animations
  95047. */
  95048. this.animations = new Array();
  95049. this._positions = null;
  95050. this._normals = null;
  95051. this._tangents = null;
  95052. /**
  95053. * Observable raised when the influence changes
  95054. */
  95055. this.onInfluenceChanged = new BABYLON.Observable();
  95056. this._animationPropertiesOverride = null;
  95057. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95058. this.influence = influence;
  95059. }
  95060. Object.defineProperty(MorphTarget.prototype, "influence", {
  95061. /**
  95062. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  95063. */
  95064. get: function () {
  95065. return this._influence;
  95066. },
  95067. set: function (influence) {
  95068. if (this._influence === influence) {
  95069. return;
  95070. }
  95071. var previous = this._influence;
  95072. this._influence = influence;
  95073. if (this.onInfluenceChanged.hasObservers) {
  95074. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  95075. }
  95076. },
  95077. enumerable: true,
  95078. configurable: true
  95079. });
  95080. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  95081. /**
  95082. * Gets or sets the animation properties override
  95083. */
  95084. get: function () {
  95085. if (!this._animationPropertiesOverride && this._scene) {
  95086. return this._scene.animationPropertiesOverride;
  95087. }
  95088. return this._animationPropertiesOverride;
  95089. },
  95090. set: function (value) {
  95091. this._animationPropertiesOverride = value;
  95092. },
  95093. enumerable: true,
  95094. configurable: true
  95095. });
  95096. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  95097. /**
  95098. * Gets a boolean defining if the target contains position data
  95099. */
  95100. get: function () {
  95101. return !!this._positions;
  95102. },
  95103. enumerable: true,
  95104. configurable: true
  95105. });
  95106. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  95107. /**
  95108. * Gets a boolean defining if the target contains normal data
  95109. */
  95110. get: function () {
  95111. return !!this._normals;
  95112. },
  95113. enumerable: true,
  95114. configurable: true
  95115. });
  95116. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  95117. /**
  95118. * Gets a boolean defining if the target contains tangent data
  95119. */
  95120. get: function () {
  95121. return !!this._tangents;
  95122. },
  95123. enumerable: true,
  95124. configurable: true
  95125. });
  95126. /**
  95127. * Affects position data to this target
  95128. * @param data defines the position data to use
  95129. */
  95130. MorphTarget.prototype.setPositions = function (data) {
  95131. this._positions = data;
  95132. };
  95133. /**
  95134. * Gets the position data stored in this target
  95135. * @returns a FloatArray containing the position data (or null if not present)
  95136. */
  95137. MorphTarget.prototype.getPositions = function () {
  95138. return this._positions;
  95139. };
  95140. /**
  95141. * Affects normal data to this target
  95142. * @param data defines the normal data to use
  95143. */
  95144. MorphTarget.prototype.setNormals = function (data) {
  95145. this._normals = data;
  95146. };
  95147. /**
  95148. * Gets the normal data stored in this target
  95149. * @returns a FloatArray containing the normal data (or null if not present)
  95150. */
  95151. MorphTarget.prototype.getNormals = function () {
  95152. return this._normals;
  95153. };
  95154. /**
  95155. * Affects tangent data to this target
  95156. * @param data defines the tangent data to use
  95157. */
  95158. MorphTarget.prototype.setTangents = function (data) {
  95159. this._tangents = data;
  95160. };
  95161. /**
  95162. * Gets the tangent data stored in this target
  95163. * @returns a FloatArray containing the tangent data (or null if not present)
  95164. */
  95165. MorphTarget.prototype.getTangents = function () {
  95166. return this._tangents;
  95167. };
  95168. /**
  95169. * Serializes the current target into a Serialization object
  95170. * @returns the serialized object
  95171. */
  95172. MorphTarget.prototype.serialize = function () {
  95173. var serializationObject = {};
  95174. serializationObject.name = this.name;
  95175. serializationObject.influence = this.influence;
  95176. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  95177. if (this.hasNormals) {
  95178. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  95179. }
  95180. if (this.hasTangents) {
  95181. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  95182. }
  95183. // Animations
  95184. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  95185. return serializationObject;
  95186. };
  95187. // Statics
  95188. /**
  95189. * Creates a new target from serialized data
  95190. * @param serializationObject defines the serialized data to use
  95191. * @returns a new MorphTarget
  95192. */
  95193. MorphTarget.Parse = function (serializationObject) {
  95194. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  95195. result.setPositions(serializationObject.positions);
  95196. if (serializationObject.normals) {
  95197. result.setNormals(serializationObject.normals);
  95198. }
  95199. if (serializationObject.tangents) {
  95200. result.setTangents(serializationObject.tangents);
  95201. }
  95202. // Animations
  95203. if (serializationObject.animations) {
  95204. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  95205. var parsedAnimation = serializationObject.animations[animationIndex];
  95206. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  95207. }
  95208. }
  95209. return result;
  95210. };
  95211. /**
  95212. * Creates a MorphTarget from mesh data
  95213. * @param mesh defines the source mesh
  95214. * @param name defines the name to use for the new target
  95215. * @param influence defines the influence to attach to the target
  95216. * @returns a new MorphTarget
  95217. */
  95218. MorphTarget.FromMesh = function (mesh, name, influence) {
  95219. if (!name) {
  95220. name = mesh.name;
  95221. }
  95222. var result = new MorphTarget(name, influence, mesh.getScene());
  95223. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  95224. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95225. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  95226. }
  95227. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  95228. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  95229. }
  95230. return result;
  95231. };
  95232. return MorphTarget;
  95233. }());
  95234. BABYLON.MorphTarget = MorphTarget;
  95235. })(BABYLON || (BABYLON = {}));
  95236. //# sourceMappingURL=babylon.morphTarget.js.map
  95237. var BABYLON;
  95238. (function (BABYLON) {
  95239. /**
  95240. * This class is used to deform meshes using morphing between different targets
  95241. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95242. */
  95243. var MorphTargetManager = /** @class */ (function () {
  95244. /**
  95245. * Creates a new MorphTargetManager
  95246. * @param scene defines the current scene
  95247. */
  95248. function MorphTargetManager(scene) {
  95249. if (scene === void 0) { scene = null; }
  95250. this._targets = new Array();
  95251. this._targetObservable = new Array();
  95252. this._activeTargets = new BABYLON.SmartArray(16);
  95253. this._supportsNormals = false;
  95254. this._supportsTangents = false;
  95255. this._vertexCount = 0;
  95256. this._uniqueId = 0;
  95257. this._tempInfluences = new Array();
  95258. if (!scene) {
  95259. scene = BABYLON.Engine.LastCreatedScene;
  95260. }
  95261. this._scene = scene;
  95262. if (this._scene) {
  95263. this._scene.morphTargetManagers.push(this);
  95264. this._uniqueId = this._scene.getUniqueId();
  95265. }
  95266. }
  95267. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  95268. /**
  95269. * Gets the unique ID of this manager
  95270. */
  95271. get: function () {
  95272. return this._uniqueId;
  95273. },
  95274. enumerable: true,
  95275. configurable: true
  95276. });
  95277. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  95278. /**
  95279. * Gets the number of vertices handled by this manager
  95280. */
  95281. get: function () {
  95282. return this._vertexCount;
  95283. },
  95284. enumerable: true,
  95285. configurable: true
  95286. });
  95287. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  95288. /**
  95289. * Gets a boolean indicating if this manager supports morphing of normals
  95290. */
  95291. get: function () {
  95292. return this._supportsNormals;
  95293. },
  95294. enumerable: true,
  95295. configurable: true
  95296. });
  95297. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  95298. /**
  95299. * Gets a boolean indicating if this manager supports morphing of tangents
  95300. */
  95301. get: function () {
  95302. return this._supportsTangents;
  95303. },
  95304. enumerable: true,
  95305. configurable: true
  95306. });
  95307. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  95308. /**
  95309. * Gets the number of targets stored in this manager
  95310. */
  95311. get: function () {
  95312. return this._targets.length;
  95313. },
  95314. enumerable: true,
  95315. configurable: true
  95316. });
  95317. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  95318. /**
  95319. * Gets the number of influencers (ie. the number of targets with influences > 0)
  95320. */
  95321. get: function () {
  95322. return this._activeTargets.length;
  95323. },
  95324. enumerable: true,
  95325. configurable: true
  95326. });
  95327. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  95328. /**
  95329. * Gets the list of influences (one per target)
  95330. */
  95331. get: function () {
  95332. return this._influences;
  95333. },
  95334. enumerable: true,
  95335. configurable: true
  95336. });
  95337. /**
  95338. * Gets the active target at specified index. An active target is a target with an influence > 0
  95339. * @param index defines the index to check
  95340. * @returns the requested target
  95341. */
  95342. MorphTargetManager.prototype.getActiveTarget = function (index) {
  95343. return this._activeTargets.data[index];
  95344. };
  95345. /**
  95346. * Gets the target at specified index
  95347. * @param index defines the index to check
  95348. * @returns the requested target
  95349. */
  95350. MorphTargetManager.prototype.getTarget = function (index) {
  95351. return this._targets[index];
  95352. };
  95353. /**
  95354. * Add a new target to this manager
  95355. * @param target defines the target to add
  95356. */
  95357. MorphTargetManager.prototype.addTarget = function (target) {
  95358. var _this = this;
  95359. this._targets.push(target);
  95360. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  95361. _this._syncActiveTargets(needUpdate);
  95362. }));
  95363. this._syncActiveTargets(true);
  95364. };
  95365. /**
  95366. * Removes a target from the manager
  95367. * @param target defines the target to remove
  95368. */
  95369. MorphTargetManager.prototype.removeTarget = function (target) {
  95370. var index = this._targets.indexOf(target);
  95371. if (index >= 0) {
  95372. this._targets.splice(index, 1);
  95373. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  95374. this._syncActiveTargets(true);
  95375. }
  95376. };
  95377. /**
  95378. * Serializes the current manager into a Serialization object
  95379. * @returns the serialized object
  95380. */
  95381. MorphTargetManager.prototype.serialize = function () {
  95382. var serializationObject = {};
  95383. serializationObject.id = this.uniqueId;
  95384. serializationObject.targets = [];
  95385. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95386. var target = _a[_i];
  95387. serializationObject.targets.push(target.serialize());
  95388. }
  95389. return serializationObject;
  95390. };
  95391. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  95392. var influenceCount = 0;
  95393. this._activeTargets.reset();
  95394. this._supportsNormals = true;
  95395. this._supportsTangents = true;
  95396. this._vertexCount = 0;
  95397. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95398. var target = _a[_i];
  95399. this._activeTargets.push(target);
  95400. this._tempInfluences[influenceCount++] = target.influence;
  95401. var positions = target.getPositions();
  95402. if (positions) {
  95403. this._supportsNormals = this._supportsNormals && target.hasNormals;
  95404. this._supportsTangents = this._supportsTangents && target.hasTangents;
  95405. var vertexCount = positions.length / 3;
  95406. if (this._vertexCount === 0) {
  95407. this._vertexCount = vertexCount;
  95408. }
  95409. else if (this._vertexCount !== vertexCount) {
  95410. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  95411. return;
  95412. }
  95413. }
  95414. }
  95415. if (!this._influences || this._influences.length !== influenceCount) {
  95416. this._influences = new Float32Array(influenceCount);
  95417. }
  95418. for (var index = 0; index < influenceCount; index++) {
  95419. this._influences[index] = this._tempInfluences[index];
  95420. }
  95421. if (needUpdate) {
  95422. this.synchronize();
  95423. }
  95424. };
  95425. /**
  95426. * Syncrhonize the targets with all the meshes using this morph target manager
  95427. */
  95428. MorphTargetManager.prototype.synchronize = function () {
  95429. if (!this._scene) {
  95430. return;
  95431. }
  95432. // Flag meshes as dirty to resync with the active targets
  95433. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  95434. var mesh = _a[_i];
  95435. if (mesh.morphTargetManager === this) {
  95436. mesh._syncGeometryWithMorphTargetManager();
  95437. }
  95438. }
  95439. };
  95440. // Statics
  95441. /**
  95442. * Creates a new MorphTargetManager from serialized data
  95443. * @param serializationObject defines the serialized data
  95444. * @param scene defines the hosting scene
  95445. * @returns the new MorphTargetManager
  95446. */
  95447. MorphTargetManager.Parse = function (serializationObject, scene) {
  95448. var result = new MorphTargetManager(scene);
  95449. result._uniqueId = serializationObject.id;
  95450. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  95451. var targetData = _a[_i];
  95452. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  95453. }
  95454. return result;
  95455. };
  95456. return MorphTargetManager;
  95457. }());
  95458. BABYLON.MorphTargetManager = MorphTargetManager;
  95459. })(BABYLON || (BABYLON = {}));
  95460. //# sourceMappingURL=babylon.morphTargetManager.js.map
  95461. var BABYLON;
  95462. (function (BABYLON) {
  95463. var Octree = /** @class */ (function () {
  95464. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  95465. if (maxDepth === void 0) { maxDepth = 2; }
  95466. this.maxDepth = maxDepth;
  95467. this.dynamicContent = new Array();
  95468. this._maxBlockCapacity = maxBlockCapacity || 64;
  95469. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  95470. this._creationFunc = creationFunc;
  95471. }
  95472. // Methods
  95473. Octree.prototype.update = function (worldMin, worldMax, entries) {
  95474. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  95475. };
  95476. Octree.prototype.addMesh = function (entry) {
  95477. for (var index = 0; index < this.blocks.length; index++) {
  95478. var block = this.blocks[index];
  95479. block.addEntry(entry);
  95480. }
  95481. };
  95482. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  95483. this._selectionContent.reset();
  95484. for (var index = 0; index < this.blocks.length; index++) {
  95485. var block = this.blocks[index];
  95486. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  95487. }
  95488. if (allowDuplicate) {
  95489. this._selectionContent.concat(this.dynamicContent);
  95490. }
  95491. else {
  95492. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95493. }
  95494. return this._selectionContent;
  95495. };
  95496. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  95497. this._selectionContent.reset();
  95498. for (var index = 0; index < this.blocks.length; index++) {
  95499. var block = this.blocks[index];
  95500. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  95501. }
  95502. if (allowDuplicate) {
  95503. this._selectionContent.concat(this.dynamicContent);
  95504. }
  95505. else {
  95506. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95507. }
  95508. return this._selectionContent;
  95509. };
  95510. Octree.prototype.intersectsRay = function (ray) {
  95511. this._selectionContent.reset();
  95512. for (var index = 0; index < this.blocks.length; index++) {
  95513. var block = this.blocks[index];
  95514. block.intersectsRay(ray, this._selectionContent);
  95515. }
  95516. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95517. return this._selectionContent;
  95518. };
  95519. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  95520. target.blocks = new Array();
  95521. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  95522. // Segmenting space
  95523. for (var x = 0; x < 2; x++) {
  95524. for (var y = 0; y < 2; y++) {
  95525. for (var z = 0; z < 2; z++) {
  95526. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  95527. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  95528. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  95529. block.addEntries(entries);
  95530. target.blocks.push(block);
  95531. }
  95532. }
  95533. }
  95534. };
  95535. Octree.CreationFuncForMeshes = function (entry, block) {
  95536. var boundingInfo = entry.getBoundingInfo();
  95537. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  95538. block.entries.push(entry);
  95539. }
  95540. };
  95541. Octree.CreationFuncForSubMeshes = function (entry, block) {
  95542. var boundingInfo = entry.getBoundingInfo();
  95543. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  95544. block.entries.push(entry);
  95545. }
  95546. };
  95547. return Octree;
  95548. }());
  95549. BABYLON.Octree = Octree;
  95550. })(BABYLON || (BABYLON = {}));
  95551. //# sourceMappingURL=babylon.octree.js.map
  95552. var BABYLON;
  95553. (function (BABYLON) {
  95554. var OctreeBlock = /** @class */ (function () {
  95555. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  95556. this.entries = new Array();
  95557. this._boundingVectors = new Array();
  95558. this._capacity = capacity;
  95559. this._depth = depth;
  95560. this._maxDepth = maxDepth;
  95561. this._creationFunc = creationFunc;
  95562. this._minPoint = minPoint;
  95563. this._maxPoint = maxPoint;
  95564. this._boundingVectors.push(minPoint.clone());
  95565. this._boundingVectors.push(maxPoint.clone());
  95566. this._boundingVectors.push(minPoint.clone());
  95567. this._boundingVectors[2].x = maxPoint.x;
  95568. this._boundingVectors.push(minPoint.clone());
  95569. this._boundingVectors[3].y = maxPoint.y;
  95570. this._boundingVectors.push(minPoint.clone());
  95571. this._boundingVectors[4].z = maxPoint.z;
  95572. this._boundingVectors.push(maxPoint.clone());
  95573. this._boundingVectors[5].z = minPoint.z;
  95574. this._boundingVectors.push(maxPoint.clone());
  95575. this._boundingVectors[6].x = minPoint.x;
  95576. this._boundingVectors.push(maxPoint.clone());
  95577. this._boundingVectors[7].y = minPoint.y;
  95578. }
  95579. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  95580. // Property
  95581. get: function () {
  95582. return this._capacity;
  95583. },
  95584. enumerable: true,
  95585. configurable: true
  95586. });
  95587. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  95588. get: function () {
  95589. return this._minPoint;
  95590. },
  95591. enumerable: true,
  95592. configurable: true
  95593. });
  95594. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  95595. get: function () {
  95596. return this._maxPoint;
  95597. },
  95598. enumerable: true,
  95599. configurable: true
  95600. });
  95601. // Methods
  95602. OctreeBlock.prototype.addEntry = function (entry) {
  95603. if (this.blocks) {
  95604. for (var index = 0; index < this.blocks.length; index++) {
  95605. var block = this.blocks[index];
  95606. block.addEntry(entry);
  95607. }
  95608. return;
  95609. }
  95610. this._creationFunc(entry, this);
  95611. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  95612. this.createInnerBlocks();
  95613. }
  95614. };
  95615. OctreeBlock.prototype.addEntries = function (entries) {
  95616. for (var index = 0; index < entries.length; index++) {
  95617. var mesh = entries[index];
  95618. this.addEntry(mesh);
  95619. }
  95620. };
  95621. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  95622. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  95623. if (this.blocks) {
  95624. for (var index = 0; index < this.blocks.length; index++) {
  95625. var block = this.blocks[index];
  95626. block.select(frustumPlanes, selection, allowDuplicate);
  95627. }
  95628. return;
  95629. }
  95630. if (allowDuplicate) {
  95631. selection.concat(this.entries);
  95632. }
  95633. else {
  95634. selection.concatWithNoDuplicate(this.entries);
  95635. }
  95636. }
  95637. };
  95638. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  95639. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  95640. if (this.blocks) {
  95641. for (var index = 0; index < this.blocks.length; index++) {
  95642. var block = this.blocks[index];
  95643. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  95644. }
  95645. return;
  95646. }
  95647. if (allowDuplicate) {
  95648. selection.concat(this.entries);
  95649. }
  95650. else {
  95651. selection.concatWithNoDuplicate(this.entries);
  95652. }
  95653. }
  95654. };
  95655. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  95656. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  95657. if (this.blocks) {
  95658. for (var index = 0; index < this.blocks.length; index++) {
  95659. var block = this.blocks[index];
  95660. block.intersectsRay(ray, selection);
  95661. }
  95662. return;
  95663. }
  95664. selection.concatWithNoDuplicate(this.entries);
  95665. }
  95666. };
  95667. OctreeBlock.prototype.createInnerBlocks = function () {
  95668. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  95669. };
  95670. return OctreeBlock;
  95671. }());
  95672. BABYLON.OctreeBlock = OctreeBlock;
  95673. })(BABYLON || (BABYLON = {}));
  95674. //# sourceMappingURL=babylon.octreeBlock.js.map
  95675. var BABYLON;
  95676. (function (BABYLON) {
  95677. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  95678. if (maxCapacity === void 0) { maxCapacity = 64; }
  95679. if (maxDepth === void 0) { maxDepth = 2; }
  95680. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  95681. if (!component) {
  95682. component = new OctreeSceneComponent(this);
  95683. this._addComponent(component);
  95684. }
  95685. if (!this._selectionOctree) {
  95686. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  95687. }
  95688. var worldExtends = this.getWorldExtends();
  95689. // Update octree
  95690. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  95691. return this._selectionOctree;
  95692. };
  95693. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  95694. get: function () {
  95695. return this._selectionOctree;
  95696. },
  95697. enumerable: true,
  95698. configurable: true
  95699. });
  95700. /**
  95701. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  95702. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  95703. * @param maxCapacity defines the maximum size of each block (64 by default)
  95704. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  95705. * @returns the new octree
  95706. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  95707. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  95708. */
  95709. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  95710. if (maxCapacity === void 0) { maxCapacity = 64; }
  95711. if (maxDepth === void 0) { maxDepth = 2; }
  95712. var scene = this.getScene();
  95713. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  95714. if (!component) {
  95715. component = new OctreeSceneComponent(scene);
  95716. scene._addComponent(component);
  95717. }
  95718. if (!this._submeshesOctree) {
  95719. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  95720. }
  95721. this.computeWorldMatrix(true);
  95722. var boundingInfo = this.getBoundingInfo();
  95723. // Update octree
  95724. var bbox = boundingInfo.boundingBox;
  95725. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  95726. return this._submeshesOctree;
  95727. };
  95728. /**
  95729. * Defines the octree scene component responsible to manage any octrees
  95730. * in a given scene.
  95731. */
  95732. var OctreeSceneComponent = /** @class */ (function () {
  95733. /**
  95734. * Creates a new instance of the component for the given scene
  95735. * @param scene Defines the scene to register the component in
  95736. */
  95737. function OctreeSceneComponent(scene) {
  95738. /**
  95739. * The component name helpfull to identify the component in the list of scene components.
  95740. */
  95741. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  95742. /**
  95743. * Indicates if the meshes have been checked to make sure they are isEnabled()
  95744. */
  95745. this.checksIsEnabled = true;
  95746. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  95747. this.scene = scene;
  95748. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  95749. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  95750. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  95751. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  95752. }
  95753. /**
  95754. * Registers the component in a given scene
  95755. */
  95756. OctreeSceneComponent.prototype.register = function () {
  95757. var _this = this;
  95758. this.scene.onMeshRemovedObservable.add(function (mesh) {
  95759. var sceneOctree = _this.scene.selectionOctree;
  95760. if (sceneOctree !== undefined && sceneOctree !== null) {
  95761. var index = sceneOctree.dynamicContent.indexOf(mesh);
  95762. if (index !== -1) {
  95763. sceneOctree.dynamicContent.splice(index, 1);
  95764. }
  95765. }
  95766. });
  95767. this.scene.onMeshImportedObservable.add(function (mesh) {
  95768. var sceneOctree = _this.scene.selectionOctree;
  95769. if (sceneOctree !== undefined && sceneOctree !== null) {
  95770. sceneOctree.addMesh(mesh);
  95771. }
  95772. });
  95773. };
  95774. /**
  95775. * Return the list of active meshes
  95776. * @returns the list of active meshes
  95777. */
  95778. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  95779. if (this.scene._selectionOctree) {
  95780. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  95781. return selection;
  95782. }
  95783. return this.scene._getDefaultMeshCandidates();
  95784. };
  95785. /**
  95786. * Return the list of active sub meshes
  95787. * @param mesh The mesh to get the candidates sub meshes from
  95788. * @returns the list of active sub meshes
  95789. */
  95790. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  95791. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  95792. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  95793. return intersections;
  95794. }
  95795. return this.scene._getDefaultSubMeshCandidates(mesh);
  95796. };
  95797. /**
  95798. * Return the list of sub meshes intersecting with a given local ray
  95799. * @param mesh defines the mesh to find the submesh for
  95800. * @param localRay defines the ray in local space
  95801. * @returns the list of intersecting sub meshes
  95802. */
  95803. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  95804. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  95805. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  95806. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  95807. return intersections;
  95808. }
  95809. return this.scene._getDefaultSubMeshCandidates(mesh);
  95810. };
  95811. /**
  95812. * Return the list of sub meshes colliding with a collider
  95813. * @param mesh defines the mesh to find the submesh for
  95814. * @param collider defines the collider to evaluate the collision against
  95815. * @returns the list of colliding sub meshes
  95816. */
  95817. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  95818. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  95819. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  95820. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  95821. return intersections;
  95822. }
  95823. return this.scene._getDefaultSubMeshCandidates(mesh);
  95824. };
  95825. /**
  95826. * Rebuilds the elements related to this component in case of
  95827. * context lost for instance.
  95828. */
  95829. OctreeSceneComponent.prototype.rebuild = function () {
  95830. // Nothing to do here.
  95831. };
  95832. /**
  95833. * Disposes the component and the associated ressources.
  95834. */
  95835. OctreeSceneComponent.prototype.dispose = function () {
  95836. // Nothing to do here.
  95837. };
  95838. return OctreeSceneComponent;
  95839. }());
  95840. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  95841. })(BABYLON || (BABYLON = {}));
  95842. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  95843. var BABYLON;
  95844. (function (BABYLON) {
  95845. /**
  95846. * Postprocess used to generate anaglyphic rendering
  95847. */
  95848. var AnaglyphPostProcess = /** @class */ (function (_super) {
  95849. __extends(AnaglyphPostProcess, _super);
  95850. /**
  95851. * Creates a new AnaglyphPostProcess
  95852. * @param name defines postprocess name
  95853. * @param options defines creation options or target ratio scale
  95854. * @param rigCameras defines cameras using this postprocess
  95855. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  95856. * @param engine defines hosting engine
  95857. * @param reusable defines if the postprocess will be reused multiple times per frame
  95858. */
  95859. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  95860. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  95861. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95862. _this.onApplyObservable.add(function (effect) {
  95863. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  95864. });
  95865. return _this;
  95866. }
  95867. return AnaglyphPostProcess;
  95868. }(BABYLON.PostProcess));
  95869. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  95870. })(BABYLON || (BABYLON = {}));
  95871. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  95872. var BABYLON;
  95873. (function (BABYLON) {
  95874. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  95875. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95876. });
  95877. /**
  95878. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  95879. */
  95880. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  95881. __extends(AnaglyphArcRotateCamera, _super);
  95882. /**
  95883. * Creates a new AnaglyphArcRotateCamera
  95884. * @param name defines camera name
  95885. * @param alpha defines alpha angle (in radians)
  95886. * @param beta defines beta angle (in radians)
  95887. * @param radius defines radius
  95888. * @param target defines camera target
  95889. * @param interaxialDistance defines distance between each color axis
  95890. * @param scene defines the hosting scene
  95891. */
  95892. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  95893. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95894. _this.interaxialDistance = interaxialDistance;
  95895. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95896. return _this;
  95897. }
  95898. /**
  95899. * Gets camera class name
  95900. * @returns AnaglyphArcRotateCamera
  95901. */
  95902. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  95903. return "AnaglyphArcRotateCamera";
  95904. };
  95905. return AnaglyphArcRotateCamera;
  95906. }(BABYLON.ArcRotateCamera));
  95907. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  95908. })(BABYLON || (BABYLON = {}));
  95909. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  95910. var BABYLON;
  95911. (function (BABYLON) {
  95912. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  95913. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95914. });
  95915. /**
  95916. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  95917. */
  95918. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  95919. __extends(AnaglyphFreeCamera, _super);
  95920. /**
  95921. * Creates a new AnaglyphFreeCamera
  95922. * @param name defines camera name
  95923. * @param position defines initial position
  95924. * @param interaxialDistance defines distance between each color axis
  95925. * @param scene defines the hosting scene
  95926. */
  95927. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  95928. var _this = _super.call(this, name, position, scene) || this;
  95929. _this.interaxialDistance = interaxialDistance;
  95930. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95931. return _this;
  95932. }
  95933. /**
  95934. * Gets camera class name
  95935. * @returns AnaglyphFreeCamera
  95936. */
  95937. AnaglyphFreeCamera.prototype.getClassName = function () {
  95938. return "AnaglyphFreeCamera";
  95939. };
  95940. return AnaglyphFreeCamera;
  95941. }(BABYLON.FreeCamera));
  95942. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  95943. })(BABYLON || (BABYLON = {}));
  95944. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  95945. var BABYLON;
  95946. (function (BABYLON) {
  95947. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  95948. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95949. });
  95950. /**
  95951. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  95952. */
  95953. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  95954. __extends(AnaglyphGamepadCamera, _super);
  95955. /**
  95956. * Creates a new AnaglyphGamepadCamera
  95957. * @param name defines camera name
  95958. * @param position defines initial position
  95959. * @param interaxialDistance defines distance between each color axis
  95960. * @param scene defines the hosting scene
  95961. */
  95962. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  95963. var _this = _super.call(this, name, position, scene) || this;
  95964. _this.interaxialDistance = interaxialDistance;
  95965. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95966. return _this;
  95967. }
  95968. /**
  95969. * Gets camera class name
  95970. * @returns AnaglyphGamepadCamera
  95971. */
  95972. AnaglyphGamepadCamera.prototype.getClassName = function () {
  95973. return "AnaglyphGamepadCamera";
  95974. };
  95975. return AnaglyphGamepadCamera;
  95976. }(BABYLON.GamepadCamera));
  95977. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  95978. })(BABYLON || (BABYLON = {}));
  95979. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  95980. var BABYLON;
  95981. (function (BABYLON) {
  95982. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  95983. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95984. });
  95985. /**
  95986. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  95987. */
  95988. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  95989. __extends(AnaglyphUniversalCamera, _super);
  95990. /**
  95991. * Creates a new AnaglyphUniversalCamera
  95992. * @param name defines camera name
  95993. * @param position defines initial position
  95994. * @param interaxialDistance defines distance between each color axis
  95995. * @param scene defines the hosting scene
  95996. */
  95997. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  95998. var _this = _super.call(this, name, position, scene) || this;
  95999. _this.interaxialDistance = interaxialDistance;
  96000. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96001. return _this;
  96002. }
  96003. /**
  96004. * Gets camera class name
  96005. * @returns AnaglyphUniversalCamera
  96006. */
  96007. AnaglyphUniversalCamera.prototype.getClassName = function () {
  96008. return "AnaglyphUniversalCamera";
  96009. };
  96010. return AnaglyphUniversalCamera;
  96011. }(BABYLON.UniversalCamera));
  96012. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  96013. })(BABYLON || (BABYLON = {}));
  96014. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  96015. var BABYLON;
  96016. (function (BABYLON) {
  96017. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  96018. __extends(StereoscopicInterlacePostProcess, _super);
  96019. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  96020. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  96021. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96022. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96023. _this.onSizeChangedObservable.add(function () {
  96024. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96025. });
  96026. _this.onApplyObservable.add(function (effect) {
  96027. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  96028. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  96029. });
  96030. return _this;
  96031. }
  96032. return StereoscopicInterlacePostProcess;
  96033. }(BABYLON.PostProcess));
  96034. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  96035. })(BABYLON || (BABYLON = {}));
  96036. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  96037. var BABYLON;
  96038. (function (BABYLON) {
  96039. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  96040. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96041. });
  96042. /**
  96043. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  96044. */
  96045. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  96046. __extends(StereoscopicArcRotateCamera, _super);
  96047. /**
  96048. * Creates a new StereoscopicArcRotateCamera
  96049. * @param name defines camera name
  96050. * @param alpha defines alpha angle (in radians)
  96051. * @param beta defines beta angle (in radians)
  96052. * @param radius defines radius
  96053. * @param target defines camera target
  96054. * @param interaxialDistance defines distance between each color axis
  96055. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96056. * @param scene defines the hosting scene
  96057. */
  96058. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  96059. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96060. _this.interaxialDistance = interaxialDistance;
  96061. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96062. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96063. return _this;
  96064. }
  96065. /**
  96066. * Gets camera class name
  96067. * @returns StereoscopicArcRotateCamera
  96068. */
  96069. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  96070. return "StereoscopicArcRotateCamera";
  96071. };
  96072. return StereoscopicArcRotateCamera;
  96073. }(BABYLON.ArcRotateCamera));
  96074. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  96075. })(BABYLON || (BABYLON = {}));
  96076. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  96077. var BABYLON;
  96078. (function (BABYLON) {
  96079. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96080. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96081. });
  96082. /**
  96083. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  96084. */
  96085. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  96086. __extends(StereoscopicFreeCamera, _super);
  96087. /**
  96088. * Creates a new StereoscopicFreeCamera
  96089. * @param name defines camera name
  96090. * @param position defines initial position
  96091. * @param interaxialDistance defines distance between each color axis
  96092. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96093. * @param scene defines the hosting scene
  96094. */
  96095. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96096. var _this = _super.call(this, name, position, scene) || this;
  96097. _this.interaxialDistance = interaxialDistance;
  96098. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96099. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96100. return _this;
  96101. }
  96102. /**
  96103. * Gets camera class name
  96104. * @returns StereoscopicFreeCamera
  96105. */
  96106. StereoscopicFreeCamera.prototype.getClassName = function () {
  96107. return "StereoscopicFreeCamera";
  96108. };
  96109. return StereoscopicFreeCamera;
  96110. }(BABYLON.FreeCamera));
  96111. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  96112. })(BABYLON || (BABYLON = {}));
  96113. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  96114. var BABYLON;
  96115. (function (BABYLON) {
  96116. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  96117. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96118. });
  96119. /**
  96120. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  96121. */
  96122. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  96123. __extends(StereoscopicGamepadCamera, _super);
  96124. /**
  96125. * Creates a new StereoscopicGamepadCamera
  96126. * @param name defines camera name
  96127. * @param position defines initial position
  96128. * @param interaxialDistance defines distance between each color axis
  96129. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96130. * @param scene defines the hosting scene
  96131. */
  96132. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96133. var _this = _super.call(this, name, position, scene) || this;
  96134. _this.interaxialDistance = interaxialDistance;
  96135. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96136. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96137. return _this;
  96138. }
  96139. /**
  96140. * Gets camera class name
  96141. * @returns StereoscopicGamepadCamera
  96142. */
  96143. StereoscopicGamepadCamera.prototype.getClassName = function () {
  96144. return "StereoscopicGamepadCamera";
  96145. };
  96146. return StereoscopicGamepadCamera;
  96147. }(BABYLON.GamepadCamera));
  96148. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  96149. })(BABYLON || (BABYLON = {}));
  96150. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  96151. var BABYLON;
  96152. (function (BABYLON) {
  96153. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96154. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96155. });
  96156. /**
  96157. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  96158. */
  96159. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  96160. __extends(StereoscopicUniversalCamera, _super);
  96161. /**
  96162. * Creates a new StereoscopicUniversalCamera
  96163. * @param name defines camera name
  96164. * @param position defines initial position
  96165. * @param interaxialDistance defines distance between each color axis
  96166. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96167. * @param scene defines the hosting scene
  96168. */
  96169. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96170. var _this = _super.call(this, name, position, scene) || this;
  96171. _this.interaxialDistance = interaxialDistance;
  96172. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96173. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96174. return _this;
  96175. }
  96176. /**
  96177. * Gets camera class name
  96178. * @returns StereoscopicUniversalCamera
  96179. */
  96180. StereoscopicUniversalCamera.prototype.getClassName = function () {
  96181. return "StereoscopicUniversalCamera";
  96182. };
  96183. return StereoscopicUniversalCamera;
  96184. }(BABYLON.UniversalCamera));
  96185. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  96186. })(BABYLON || (BABYLON = {}));
  96187. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  96188. var BABYLON;
  96189. (function (BABYLON) {
  96190. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  96191. __extends(VRDistortionCorrectionPostProcess, _super);
  96192. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  96193. var _this = _super.call(this, name, "vrDistortionCorrection", [
  96194. 'LensCenter',
  96195. 'Scale',
  96196. 'ScaleIn',
  96197. 'HmdWarpParam'
  96198. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  96199. _this._isRightEye = isRightEye;
  96200. _this._distortionFactors = vrMetrics.distortionK;
  96201. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  96202. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  96203. _this.adaptScaleToCurrentViewport = true;
  96204. _this.onSizeChangedObservable.add(function () {
  96205. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  96206. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  96207. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  96208. });
  96209. _this.onApplyObservable.add(function (effect) {
  96210. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  96211. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  96212. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  96213. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  96214. });
  96215. return _this;
  96216. }
  96217. return VRDistortionCorrectionPostProcess;
  96218. }(BABYLON.PostProcess));
  96219. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  96220. })(BABYLON || (BABYLON = {}));
  96221. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  96222. var BABYLON;
  96223. (function (BABYLON) {
  96224. /**
  96225. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  96226. * Screen rotation is taken into account.
  96227. */
  96228. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  96229. function FreeCameraDeviceOrientationInput() {
  96230. var _this = this;
  96231. this._screenOrientationAngle = 0;
  96232. this._screenQuaternion = new BABYLON.Quaternion();
  96233. this._alpha = 0;
  96234. this._beta = 0;
  96235. this._gamma = 0;
  96236. this._orientationChanged = function () {
  96237. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  96238. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  96239. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  96240. };
  96241. this._deviceOrientation = function (evt) {
  96242. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  96243. _this._beta = evt.beta !== null ? evt.beta : 0;
  96244. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  96245. };
  96246. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  96247. this._orientationChanged();
  96248. }
  96249. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  96250. get: function () {
  96251. return this._camera;
  96252. },
  96253. set: function (camera) {
  96254. this._camera = camera;
  96255. if (this._camera != null && !this._camera.rotationQuaternion) {
  96256. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  96257. }
  96258. },
  96259. enumerable: true,
  96260. configurable: true
  96261. });
  96262. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96263. window.addEventListener("orientationchange", this._orientationChanged);
  96264. window.addEventListener("deviceorientation", this._deviceOrientation);
  96265. //In certain cases, the attach control is called AFTER orientation was changed,
  96266. //So this is needed.
  96267. this._orientationChanged();
  96268. };
  96269. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  96270. window.removeEventListener("orientationchange", this._orientationChanged);
  96271. window.removeEventListener("deviceorientation", this._deviceOrientation);
  96272. };
  96273. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  96274. //if no device orientation provided, don't update the rotation.
  96275. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  96276. if (!this._alpha)
  96277. return;
  96278. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  96279. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  96280. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  96281. //Mirror on XY Plane
  96282. this._camera.rotationQuaternion.z *= -1;
  96283. this._camera.rotationQuaternion.w *= -1;
  96284. };
  96285. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  96286. return "FreeCameraDeviceOrientationInput";
  96287. };
  96288. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  96289. return "deviceOrientation";
  96290. };
  96291. return FreeCameraDeviceOrientationInput;
  96292. }());
  96293. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  96294. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  96295. })(BABYLON || (BABYLON = {}));
  96296. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  96297. var BABYLON;
  96298. (function (BABYLON) {
  96299. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  96300. function ArcRotateCameraVRDeviceOrientationInput() {
  96301. this.alphaCorrection = 1;
  96302. this.betaCorrection = 1;
  96303. this.gammaCorrection = 1;
  96304. this._alpha = 0;
  96305. this._gamma = 0;
  96306. this._dirty = false;
  96307. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  96308. }
  96309. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96310. this.camera.attachControl(element, noPreventDefault);
  96311. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  96312. };
  96313. /** @hidden */
  96314. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  96315. if (evt.alpha !== null) {
  96316. this._alpha = +evt.alpha | 0;
  96317. }
  96318. if (evt.gamma !== null) {
  96319. this._gamma = +evt.gamma | 0;
  96320. }
  96321. this._dirty = true;
  96322. };
  96323. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  96324. if (this._dirty) {
  96325. this._dirty = false;
  96326. if (this._gamma < 0) {
  96327. this._gamma = 180 + this._gamma;
  96328. }
  96329. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  96330. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  96331. }
  96332. };
  96333. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  96334. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  96335. };
  96336. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  96337. return "ArcRotateCameraVRDeviceOrientationInput";
  96338. };
  96339. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  96340. return "VRDeviceOrientation";
  96341. };
  96342. return ArcRotateCameraVRDeviceOrientationInput;
  96343. }());
  96344. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  96345. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  96346. })(BABYLON || (BABYLON = {}));
  96347. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  96348. var BABYLON;
  96349. (function (BABYLON) {
  96350. var VRCameraMetrics = /** @class */ (function () {
  96351. function VRCameraMetrics() {
  96352. this.compensateDistortion = true;
  96353. }
  96354. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  96355. get: function () {
  96356. return this.hResolution / (2 * this.vResolution);
  96357. },
  96358. enumerable: true,
  96359. configurable: true
  96360. });
  96361. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  96362. get: function () {
  96363. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  96364. },
  96365. enumerable: true,
  96366. configurable: true
  96367. });
  96368. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  96369. get: function () {
  96370. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96371. var h = (4 * meters) / this.hScreenSize;
  96372. return BABYLON.Matrix.Translation(h, 0, 0);
  96373. },
  96374. enumerable: true,
  96375. configurable: true
  96376. });
  96377. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  96378. get: function () {
  96379. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96380. var h = (4 * meters) / this.hScreenSize;
  96381. return BABYLON.Matrix.Translation(-h, 0, 0);
  96382. },
  96383. enumerable: true,
  96384. configurable: true
  96385. });
  96386. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  96387. get: function () {
  96388. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  96389. },
  96390. enumerable: true,
  96391. configurable: true
  96392. });
  96393. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  96394. get: function () {
  96395. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  96396. },
  96397. enumerable: true,
  96398. configurable: true
  96399. });
  96400. VRCameraMetrics.GetDefault = function () {
  96401. var result = new VRCameraMetrics();
  96402. result.hResolution = 1280;
  96403. result.vResolution = 800;
  96404. result.hScreenSize = 0.149759993;
  96405. result.vScreenSize = 0.0935999975;
  96406. result.vScreenCenter = 0.0467999987;
  96407. result.eyeToScreenDistance = 0.0410000011;
  96408. result.lensSeparationDistance = 0.0635000020;
  96409. result.interpupillaryDistance = 0.0640000030;
  96410. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  96411. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  96412. result.postProcessScaleFactor = 1.714605507808412;
  96413. result.lensCenterOffset = 0.151976421;
  96414. return result;
  96415. };
  96416. return VRCameraMetrics;
  96417. }());
  96418. BABYLON.VRCameraMetrics = VRCameraMetrics;
  96419. })(BABYLON || (BABYLON = {}));
  96420. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  96421. var BABYLON;
  96422. (function (BABYLON) {
  96423. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  96424. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96425. });
  96426. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  96427. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96428. });
  96429. /**
  96430. * This represents a WebVR camera.
  96431. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  96432. * @example http://doc.babylonjs.com/how_to/webvr_camera
  96433. */
  96434. var WebVRFreeCamera = /** @class */ (function (_super) {
  96435. __extends(WebVRFreeCamera, _super);
  96436. /**
  96437. * Instantiates a WebVRFreeCamera.
  96438. * @param name The name of the WebVRFreeCamera
  96439. * @param position The starting anchor position for the camera
  96440. * @param scene The scene the camera belongs to
  96441. * @param webVROptions a set of customizable options for the webVRCamera
  96442. */
  96443. function WebVRFreeCamera(name, position, scene, webVROptions) {
  96444. if (webVROptions === void 0) { webVROptions = {}; }
  96445. var _this = _super.call(this, name, position, scene) || this;
  96446. _this.webVROptions = webVROptions;
  96447. /**
  96448. * @hidden
  96449. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  96450. */
  96451. _this._vrDevice = null;
  96452. /**
  96453. * The rawPose of the vrDevice.
  96454. */
  96455. _this.rawPose = null;
  96456. _this._specsVersion = "1.1";
  96457. _this._attached = false;
  96458. _this._descendants = [];
  96459. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  96460. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  96461. /** @hidden */
  96462. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  96463. _this._standingMatrix = null;
  96464. /**
  96465. * Represents device position in babylon space.
  96466. */
  96467. _this.devicePosition = BABYLON.Vector3.Zero();
  96468. /**
  96469. * Represents device rotation in babylon space.
  96470. */
  96471. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  96472. /**
  96473. * The scale of the device to be used when translating from device space to babylon space.
  96474. */
  96475. _this.deviceScaleFactor = 1;
  96476. _this._deviceToWorld = BABYLON.Matrix.Identity();
  96477. _this._worldToDevice = BABYLON.Matrix.Identity();
  96478. /**
  96479. * References to the webVR controllers for the vrDevice.
  96480. */
  96481. _this.controllers = [];
  96482. /**
  96483. * Emits an event when a controller is attached.
  96484. */
  96485. _this.onControllersAttachedObservable = new BABYLON.Observable();
  96486. /**
  96487. * Emits an event when a controller's mesh has been loaded;
  96488. */
  96489. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  96490. /**
  96491. * Emits an event when the HMD's pose has been updated.
  96492. */
  96493. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  96494. _this._poseSet = false;
  96495. /**
  96496. * If the rig cameras be used as parent instead of this camera.
  96497. */
  96498. _this.rigParenting = true;
  96499. _this._defaultHeight = undefined;
  96500. _this._htmlElementAttached = null;
  96501. _this._detachIfAttached = function () {
  96502. var vrDisplay = _this.getEngine().getVRDevice();
  96503. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  96504. _this.detachControl(_this._htmlElementAttached);
  96505. }
  96506. };
  96507. _this._workingVector = BABYLON.Vector3.Zero();
  96508. _this._oneVector = BABYLON.Vector3.One();
  96509. _this._workingMatrix = BABYLON.Matrix.Identity();
  96510. _this._tmpMatrix = new BABYLON.Matrix();
  96511. _this._cache.position = BABYLON.Vector3.Zero();
  96512. if (webVROptions.defaultHeight) {
  96513. _this._defaultHeight = webVROptions.defaultHeight;
  96514. _this.position.y = _this._defaultHeight;
  96515. }
  96516. _this.minZ = 0.1;
  96517. //legacy support - the compensation boolean was removed.
  96518. if (arguments.length === 5) {
  96519. _this.webVROptions = arguments[4];
  96520. }
  96521. // default webVR options
  96522. if (_this.webVROptions.trackPosition == undefined) {
  96523. _this.webVROptions.trackPosition = true;
  96524. }
  96525. if (_this.webVROptions.controllerMeshes == undefined) {
  96526. _this.webVROptions.controllerMeshes = true;
  96527. }
  96528. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  96529. _this.webVROptions.defaultLightingOnControllers = true;
  96530. }
  96531. _this.rotationQuaternion = new BABYLON.Quaternion();
  96532. if (_this.webVROptions && _this.webVROptions.positionScale) {
  96533. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  96534. }
  96535. //enable VR
  96536. var engine = _this.getEngine();
  96537. _this._onVREnabled = function (success) { if (success) {
  96538. _this.initControllers();
  96539. } };
  96540. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  96541. engine.initWebVR().add(function (event) {
  96542. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  96543. return;
  96544. }
  96545. _this._vrDevice = event.vrDisplay;
  96546. //reset the rig parameters.
  96547. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  96548. if (_this._attached) {
  96549. _this.getEngine().enableVR();
  96550. }
  96551. });
  96552. if (typeof (VRFrameData) !== "undefined")
  96553. _this._frameData = new VRFrameData();
  96554. /**
  96555. * The idea behind the following lines:
  96556. * objects that have the camera as parent should actually have the rig cameras as a parent.
  96557. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  96558. * the second will not show it correctly.
  96559. *
  96560. * To solve this - each object that has the camera as parent will be added to a protected array.
  96561. * When the rig camera renders, it will take this array and set all of those to be its children.
  96562. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  96563. * Amazing!
  96564. */
  96565. scene.onBeforeCameraRenderObservable.add(function (camera) {
  96566. if (camera.parent === _this && _this.rigParenting) {
  96567. _this._descendants = _this.getDescendants(true, function (n) {
  96568. // don't take the cameras or the controllers!
  96569. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  96570. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  96571. return !isController && !isRigCamera;
  96572. });
  96573. _this._descendants.forEach(function (node) {
  96574. node.parent = camera;
  96575. });
  96576. }
  96577. });
  96578. scene.onAfterCameraRenderObservable.add(function (camera) {
  96579. if (camera.parent === _this && _this.rigParenting) {
  96580. _this._descendants.forEach(function (node) {
  96581. node.parent = _this;
  96582. });
  96583. }
  96584. });
  96585. return _this;
  96586. }
  96587. /**
  96588. * Gets the device distance from the ground in meters.
  96589. * @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.
  96590. */
  96591. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  96592. if (this._standingMatrix) {
  96593. // Add standing matrix offset to get real offset from ground in room
  96594. this._standingMatrix.getTranslationToRef(this._workingVector);
  96595. return this._deviceRoomPosition.y + this._workingVector.y;
  96596. }
  96597. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  96598. return this._defaultHeight || 0;
  96599. };
  96600. /**
  96601. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  96602. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  96603. */
  96604. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  96605. var _this = this;
  96606. if (callback === void 0) { callback = function (bool) { }; }
  96607. // Use standing matrix if available
  96608. this.getEngine().initWebVRAsync().then(function (result) {
  96609. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  96610. callback(false);
  96611. }
  96612. else {
  96613. _this._standingMatrix = new BABYLON.Matrix();
  96614. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  96615. if (!_this.getScene().useRightHandedSystem) {
  96616. [2, 6, 8, 9, 14].forEach(function (num) {
  96617. if (_this._standingMatrix) {
  96618. _this._standingMatrix.m[num] *= -1;
  96619. }
  96620. });
  96621. }
  96622. callback(true);
  96623. }
  96624. });
  96625. };
  96626. /**
  96627. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  96628. * @returns A promise with a boolean set to if the standing matrix is supported.
  96629. */
  96630. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  96631. var _this = this;
  96632. return new Promise(function (res, rej) {
  96633. _this.useStandingMatrix(function (supported) {
  96634. res(supported);
  96635. });
  96636. });
  96637. };
  96638. /**
  96639. * Disposes the camera
  96640. */
  96641. WebVRFreeCamera.prototype.dispose = function () {
  96642. this._detachIfAttached();
  96643. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  96644. _super.prototype.dispose.call(this);
  96645. };
  96646. /**
  96647. * Gets a vrController by name.
  96648. * @param name The name of the controller to retreive
  96649. * @returns the controller matching the name specified or null if not found
  96650. */
  96651. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  96652. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  96653. var gp = _a[_i];
  96654. if (gp.hand === name) {
  96655. return gp;
  96656. }
  96657. }
  96658. return null;
  96659. };
  96660. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  96661. /**
  96662. * The controller corrisponding to the users left hand.
  96663. */
  96664. get: function () {
  96665. if (!this._leftController) {
  96666. this._leftController = this.getControllerByName("left");
  96667. }
  96668. return this._leftController;
  96669. },
  96670. enumerable: true,
  96671. configurable: true
  96672. });
  96673. ;
  96674. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  96675. /**
  96676. * The controller corrisponding to the users right hand.
  96677. */
  96678. get: function () {
  96679. if (!this._rightController) {
  96680. this._rightController = this.getControllerByName("right");
  96681. }
  96682. return this._rightController;
  96683. },
  96684. enumerable: true,
  96685. configurable: true
  96686. });
  96687. ;
  96688. /**
  96689. * Casts a ray forward from the vrCamera's gaze.
  96690. * @param length Length of the ray (default: 100)
  96691. * @returns the ray corrisponding to the gaze
  96692. */
  96693. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  96694. if (length === void 0) { length = 100; }
  96695. if (this.leftCamera) {
  96696. // Use left eye to avoid computation to compute center on every call
  96697. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  96698. }
  96699. else {
  96700. return _super.prototype.getForwardRay.call(this, length);
  96701. }
  96702. };
  96703. /**
  96704. * @hidden
  96705. * Updates the camera based on device's frame data
  96706. */
  96707. WebVRFreeCamera.prototype._checkInputs = function () {
  96708. if (this._vrDevice && this._vrDevice.isPresenting) {
  96709. this._vrDevice.getFrameData(this._frameData);
  96710. this.updateFromDevice(this._frameData.pose);
  96711. }
  96712. _super.prototype._checkInputs.call(this);
  96713. };
  96714. /**
  96715. * Updates the poseControlled values based on the input device pose.
  96716. * @param poseData Pose coming from the device
  96717. */
  96718. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  96719. if (poseData && poseData.orientation) {
  96720. this.rawPose = poseData;
  96721. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  96722. if (this.getScene().useRightHandedSystem) {
  96723. this._deviceRoomRotationQuaternion.z *= -1;
  96724. this._deviceRoomRotationQuaternion.w *= -1;
  96725. }
  96726. if (this.webVROptions.trackPosition && this.rawPose.position) {
  96727. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  96728. if (this.getScene().useRightHandedSystem) {
  96729. this._deviceRoomPosition.z *= -1;
  96730. }
  96731. }
  96732. this._poseSet = true;
  96733. }
  96734. };
  96735. /**
  96736. * WebVR's attach control will start broadcasting frames to the device.
  96737. * Note that in certain browsers (chrome for example) this function must be called
  96738. * within a user-interaction callback. Example:
  96739. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  96740. *
  96741. * @param element html element to attach the vrDevice to
  96742. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  96743. */
  96744. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  96745. _super.prototype.attachControl.call(this, element, noPreventDefault);
  96746. this._attached = true;
  96747. this._htmlElementAttached = element;
  96748. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  96749. if (this._vrDevice) {
  96750. this.getEngine().enableVR();
  96751. }
  96752. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96753. };
  96754. /**
  96755. * Detaches the camera from the html element and disables VR
  96756. *
  96757. * @param element html element to detach from
  96758. */
  96759. WebVRFreeCamera.prototype.detachControl = function (element) {
  96760. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  96761. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  96762. _super.prototype.detachControl.call(this, element);
  96763. this._attached = false;
  96764. this.getEngine().disableVR();
  96765. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96766. };
  96767. /**
  96768. * @returns the name of this class
  96769. */
  96770. WebVRFreeCamera.prototype.getClassName = function () {
  96771. return "WebVRFreeCamera";
  96772. };
  96773. /**
  96774. * Calls resetPose on the vrDisplay
  96775. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  96776. */
  96777. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  96778. //uses the vrDisplay's "resetPose()".
  96779. //pitch and roll won't be affected.
  96780. this._vrDevice.resetPose();
  96781. };
  96782. /**
  96783. * @hidden
  96784. * Updates the rig cameras (left and right eye)
  96785. */
  96786. WebVRFreeCamera.prototype._updateRigCameras = function () {
  96787. var camLeft = this._rigCameras[0];
  96788. var camRight = this._rigCameras[1];
  96789. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96790. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96791. camLeft.position.copyFrom(this._deviceRoomPosition);
  96792. camRight.position.copyFrom(this._deviceRoomPosition);
  96793. };
  96794. // Remove translation from 6dof headset if trackposition is set to false
  96795. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  96796. if (isViewMatrix === void 0) { isViewMatrix = false; }
  96797. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  96798. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  96799. if (!isViewMatrix) {
  96800. this._tmpMatrix.invert();
  96801. }
  96802. this._tmpMatrix.multiplyToRef(matrix, matrix);
  96803. }
  96804. };
  96805. /**
  96806. * @hidden
  96807. * Updates the cached values of the camera
  96808. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  96809. */
  96810. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  96811. var _this = this;
  96812. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  96813. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  96814. if (!this.updateCacheCalled) {
  96815. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  96816. this.updateCacheCalled = true;
  96817. this.update();
  96818. }
  96819. // Set working vector to the device position in room space rotated by the new rotation
  96820. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  96821. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  96822. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  96823. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  96824. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  96825. // Add translation from anchor position
  96826. this._deviceToWorld.getTranslationToRef(this._workingVector);
  96827. this._workingVector.addInPlace(this.position);
  96828. this._workingVector.subtractInPlace(this._cache.position);
  96829. this._deviceToWorld.setTranslation(this._workingVector);
  96830. // Set an inverted matrix to be used when updating the camera
  96831. this._deviceToWorld.invertToRef(this._worldToDevice);
  96832. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  96833. this.controllers.forEach(function (controller) {
  96834. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  96835. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  96836. controller.update();
  96837. });
  96838. }
  96839. if (!ignoreParentClass) {
  96840. _super.prototype._updateCache.call(this);
  96841. }
  96842. this.updateCacheCalled = false;
  96843. };
  96844. /**
  96845. * Updates the current device position and rotation in the babylon world
  96846. */
  96847. WebVRFreeCamera.prototype.update = function () {
  96848. // Get current device position in babylon world
  96849. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  96850. // Get current device rotation in babylon world
  96851. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  96852. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  96853. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  96854. if (this._poseSet) {
  96855. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  96856. }
  96857. _super.prototype.update.call(this);
  96858. };
  96859. /**
  96860. * @hidden
  96861. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  96862. * @returns an identity matrix
  96863. */
  96864. WebVRFreeCamera.prototype._getViewMatrix = function () {
  96865. return BABYLON.Matrix.Identity();
  96866. };
  96867. /**
  96868. * This function is called by the two RIG cameras.
  96869. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  96870. */
  96871. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  96872. var _this = this;
  96873. // Update the parent camera prior to using a child camera to avoid desynchronization
  96874. var parentCamera = this._cameraRigParams["parentCamera"];
  96875. parentCamera._updateCache();
  96876. //WebVR 1.1
  96877. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  96878. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  96879. if (!this.getScene().useRightHandedSystem) {
  96880. [2, 6, 8, 9, 14].forEach(function (num) {
  96881. _this._webvrViewMatrix.m[num] *= -1;
  96882. });
  96883. }
  96884. // update the camera rotation matrix
  96885. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  96886. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  96887. // Computing target and final matrix
  96888. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  96889. // should the view matrix be updated with scale and position offset?
  96890. if (parentCamera.deviceScaleFactor !== 1) {
  96891. this._webvrViewMatrix.invert();
  96892. // scale the position, if set
  96893. if (parentCamera.deviceScaleFactor) {
  96894. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  96895. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  96896. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  96897. }
  96898. this._webvrViewMatrix.invert();
  96899. }
  96900. // Remove translation from 6dof headset if trackposition is set to false
  96901. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  96902. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  96903. // Compute global position
  96904. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  96905. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  96906. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  96907. this._workingMatrix.getTranslationToRef(this._globalPosition);
  96908. this._markSyncedWithParent();
  96909. return this._webvrViewMatrix;
  96910. };
  96911. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  96912. var _this = this;
  96913. var parentCamera = this.parent;
  96914. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  96915. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  96916. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  96917. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  96918. //babylon compatible matrix
  96919. if (!this.getScene().useRightHandedSystem) {
  96920. [8, 9, 10, 11].forEach(function (num) {
  96921. _this._projectionMatrix.m[num] *= -1;
  96922. });
  96923. }
  96924. return this._projectionMatrix;
  96925. };
  96926. /**
  96927. * Initializes the controllers and their meshes
  96928. */
  96929. WebVRFreeCamera.prototype.initControllers = function () {
  96930. var _this = this;
  96931. this.controllers = [];
  96932. var manager = this.getScene().gamepadManager;
  96933. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  96934. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96935. var webVrController = gamepad;
  96936. if (webVrController.defaultModel) {
  96937. webVrController.defaultModel.setEnabled(false);
  96938. }
  96939. if (webVrController.hand === "right") {
  96940. _this._rightController = null;
  96941. }
  96942. if (webVrController.hand === "left") {
  96943. _this._leftController = null;
  96944. }
  96945. var controllerIndex = _this.controllers.indexOf(webVrController);
  96946. if (controllerIndex !== -1) {
  96947. _this.controllers.splice(controllerIndex, 1);
  96948. }
  96949. }
  96950. });
  96951. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  96952. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96953. var webVrController_1 = gamepad;
  96954. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  96955. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  96956. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  96957. if (_this.webVROptions.controllerMeshes) {
  96958. if (webVrController_1.defaultModel) {
  96959. webVrController_1.defaultModel.setEnabled(true);
  96960. }
  96961. else {
  96962. // Load the meshes
  96963. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  96964. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  96965. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  96966. if (_this.webVROptions.defaultLightingOnControllers) {
  96967. if (!_this._lightOnControllers) {
  96968. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  96969. }
  96970. var activateLightOnSubMeshes_1 = function (mesh, light) {
  96971. var children = mesh.getChildren();
  96972. if (children && children.length !== 0) {
  96973. children.forEach(function (mesh) {
  96974. light.includedOnlyMeshes.push(mesh);
  96975. activateLightOnSubMeshes_1(mesh, light);
  96976. });
  96977. }
  96978. };
  96979. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  96980. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  96981. }
  96982. });
  96983. }
  96984. }
  96985. webVrController_1.attachToPoseControlledCamera(_this);
  96986. // since this is async - sanity check. Is the controller already stored?
  96987. if (_this.controllers.indexOf(webVrController_1) === -1) {
  96988. //add to the controllers array
  96989. _this.controllers.push(webVrController_1);
  96990. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  96991. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  96992. // So we're overriding setting left & right manually to be sure
  96993. var firstViveWandDetected = false;
  96994. for (var i = 0; i < _this.controllers.length; i++) {
  96995. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96996. if (!firstViveWandDetected) {
  96997. firstViveWandDetected = true;
  96998. _this.controllers[i].hand = "left";
  96999. }
  97000. else {
  97001. _this.controllers[i].hand = "right";
  97002. }
  97003. }
  97004. }
  97005. //did we find enough controllers? Great! let the developer know.
  97006. if (_this.controllers.length >= 2) {
  97007. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  97008. }
  97009. }
  97010. }
  97011. });
  97012. };
  97013. return WebVRFreeCamera;
  97014. }(BABYLON.FreeCamera));
  97015. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  97016. })(BABYLON || (BABYLON = {}));
  97017. //# sourceMappingURL=babylon.webVRCamera.js.map
  97018. var BABYLON;
  97019. (function (BABYLON) {
  97020. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  97021. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  97022. });
  97023. // We're mainly based on the logic defined into the FreeCamera code
  97024. /**
  97025. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  97026. * being tilted forward or back and left or right.
  97027. */
  97028. var DeviceOrientationCamera = /** @class */ (function (_super) {
  97029. __extends(DeviceOrientationCamera, _super);
  97030. /**
  97031. * Creates a new device orientation camera
  97032. * @param name The name of the camera
  97033. * @param position The start position camera
  97034. * @param scene The scene the camera belongs to
  97035. */
  97036. function DeviceOrientationCamera(name, position, scene) {
  97037. var _this = _super.call(this, name, position, scene) || this;
  97038. _this._quaternionCache = new BABYLON.Quaternion();
  97039. _this.inputs.addDeviceOrientation();
  97040. return _this;
  97041. }
  97042. /**
  97043. * Gets the current instance class name ("DeviceOrientationCamera").
  97044. * This helps avoiding instanceof at run time.
  97045. * @returns the class name
  97046. */
  97047. DeviceOrientationCamera.prototype.getClassName = function () {
  97048. return "DeviceOrientationCamera";
  97049. };
  97050. /**
  97051. * @hidden
  97052. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  97053. */
  97054. DeviceOrientationCamera.prototype._checkInputs = function () {
  97055. _super.prototype._checkInputs.call(this);
  97056. this._quaternionCache.copyFrom(this.rotationQuaternion);
  97057. if (this._initialQuaternion) {
  97058. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97059. }
  97060. };
  97061. /**
  97062. * Reset the camera to its default orientation on the specified axis only.
  97063. * @param axis The axis to reset
  97064. */
  97065. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  97066. var _this = this;
  97067. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  97068. //can only work if this camera has a rotation quaternion already.
  97069. if (!this.rotationQuaternion)
  97070. return;
  97071. if (!this._initialQuaternion) {
  97072. this._initialQuaternion = new BABYLON.Quaternion();
  97073. }
  97074. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  97075. ['x', 'y', 'z'].forEach(function (axisName) {
  97076. if (!axis[axisName]) {
  97077. _this._initialQuaternion[axisName] = 0;
  97078. }
  97079. else {
  97080. _this._initialQuaternion[axisName] *= -1;
  97081. }
  97082. });
  97083. this._initialQuaternion.normalize();
  97084. //force rotation update
  97085. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97086. };
  97087. return DeviceOrientationCamera;
  97088. }(BABYLON.FreeCamera));
  97089. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  97090. })(BABYLON || (BABYLON = {}));
  97091. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  97092. var BABYLON;
  97093. (function (BABYLON) {
  97094. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97095. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97096. });
  97097. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  97098. __extends(VRDeviceOrientationFreeCamera, _super);
  97099. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97100. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97101. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97102. var _this = _super.call(this, name, position, scene) || this;
  97103. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97104. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97105. return _this;
  97106. }
  97107. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  97108. return "VRDeviceOrientationFreeCamera";
  97109. };
  97110. return VRDeviceOrientationFreeCamera;
  97111. }(BABYLON.DeviceOrientationCamera));
  97112. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  97113. })(BABYLON || (BABYLON = {}));
  97114. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  97115. var BABYLON;
  97116. (function (BABYLON) {
  97117. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97118. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  97119. });
  97120. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  97121. __extends(VRDeviceOrientationArcRotateCamera, _super);
  97122. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  97123. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97124. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97125. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97126. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97127. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97128. _this.inputs.addVRDeviceOrientation();
  97129. return _this;
  97130. }
  97131. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  97132. return "VRDeviceOrientationArcRotateCamera";
  97133. };
  97134. return VRDeviceOrientationArcRotateCamera;
  97135. }(BABYLON.ArcRotateCamera));
  97136. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  97137. })(BABYLON || (BABYLON = {}));
  97138. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  97139. var BABYLON;
  97140. (function (BABYLON) {
  97141. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  97142. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  97143. });
  97144. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  97145. __extends(VRDeviceOrientationGamepadCamera, _super);
  97146. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97147. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97148. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97149. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  97150. _this.inputs.addGamepad();
  97151. return _this;
  97152. }
  97153. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  97154. return "VRDeviceOrientationGamepadCamera";
  97155. };
  97156. return VRDeviceOrientationGamepadCamera;
  97157. }(BABYLON.VRDeviceOrientationFreeCamera));
  97158. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  97159. })(BABYLON || (BABYLON = {}));
  97160. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  97161. var BABYLON;
  97162. (function (BABYLON) {
  97163. var VRExperienceHelperGazer = /** @class */ (function () {
  97164. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  97165. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  97166. this.scene = scene;
  97167. /** @hidden */
  97168. this._pointerDownOnMeshAsked = false;
  97169. /** @hidden */
  97170. this._isActionableMesh = false;
  97171. /** @hidden */
  97172. this._teleportationRequestInitiated = false;
  97173. /** @hidden */
  97174. this._teleportationBackRequestInitiated = false;
  97175. /** @hidden */
  97176. this._rotationRightAsked = false;
  97177. /** @hidden */
  97178. this._rotationLeftAsked = false;
  97179. /** @hidden */
  97180. this._dpadPressed = true;
  97181. /** @hidden */
  97182. this._activePointer = false;
  97183. this._id = VRExperienceHelperGazer._idCounter++;
  97184. // Gaze tracker
  97185. if (!gazeTrackerToClone) {
  97186. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  97187. this._gazeTracker.bakeCurrentTransformIntoVertices();
  97188. this._gazeTracker.isPickable = false;
  97189. this._gazeTracker.isVisible = false;
  97190. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  97191. targetMat.specularColor = BABYLON.Color3.Black();
  97192. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97193. targetMat.backFaceCulling = false;
  97194. this._gazeTracker.material = targetMat;
  97195. }
  97196. else {
  97197. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  97198. }
  97199. }
  97200. /** @hidden */
  97201. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  97202. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  97203. };
  97204. /** @hidden */
  97205. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  97206. this._pointerDownOnMeshAsked = true;
  97207. if (this._currentHit) {
  97208. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  97209. }
  97210. };
  97211. /** @hidden */
  97212. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  97213. if (this._currentHit) {
  97214. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  97215. }
  97216. this._pointerDownOnMeshAsked = false;
  97217. };
  97218. /** @hidden */
  97219. VRExperienceHelperGazer.prototype._activatePointer = function () {
  97220. this._activePointer = true;
  97221. };
  97222. /** @hidden */
  97223. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  97224. this._activePointer = false;
  97225. };
  97226. /** @hidden */
  97227. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  97228. if (distance === void 0) { distance = 100; }
  97229. };
  97230. VRExperienceHelperGazer.prototype.dispose = function () {
  97231. this._interactionsEnabled = false;
  97232. this._teleportationEnabled = false;
  97233. if (this._gazeTracker) {
  97234. this._gazeTracker.dispose();
  97235. }
  97236. };
  97237. VRExperienceHelperGazer._idCounter = 0;
  97238. return VRExperienceHelperGazer;
  97239. }());
  97240. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  97241. __extends(VRExperienceHelperControllerGazer, _super);
  97242. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  97243. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  97244. _this.webVRController = webVRController;
  97245. // Laser pointer
  97246. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  97247. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  97248. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97249. laserPointerMaterial.alpha = 0.6;
  97250. _this._laserPointer.material = laserPointerMaterial;
  97251. _this._laserPointer.rotation.x = Math.PI / 2;
  97252. _this._laserPointer.position.z = -0.5;
  97253. _this._laserPointer.isVisible = false;
  97254. _this._laserPointer.isPickable = false;
  97255. if (!webVRController.mesh) {
  97256. // Create an empty mesh that is used prior to loading the high quality model
  97257. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  97258. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  97259. preloadPointerPose.rotation.x = -0.7;
  97260. preloadMesh.addChild(preloadPointerPose);
  97261. webVRController.attachToMesh(preloadMesh);
  97262. }
  97263. _this._setLaserPointerParent(webVRController.mesh);
  97264. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  97265. _this._setLaserPointerParent(mesh);
  97266. });
  97267. return _this;
  97268. }
  97269. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  97270. return this.webVRController.getForwardRay(length);
  97271. };
  97272. /** @hidden */
  97273. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  97274. _super.prototype._activatePointer.call(this);
  97275. this._laserPointer.isVisible = true;
  97276. };
  97277. /** @hidden */
  97278. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  97279. _super.prototype._deactivatePointer.call(this);
  97280. this._laserPointer.isVisible = false;
  97281. };
  97282. /** @hidden */
  97283. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  97284. this._laserPointer.material.emissiveColor = color;
  97285. };
  97286. /** @hidden */
  97287. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  97288. var makeNotPick = function (root) {
  97289. root.isPickable = false;
  97290. root.getChildMeshes().forEach(function (c) {
  97291. makeNotPick(c);
  97292. });
  97293. };
  97294. makeNotPick(mesh);
  97295. var childMeshes = mesh.getChildMeshes();
  97296. this.webVRController._pointingPoseNode = null;
  97297. for (var i = 0; i < childMeshes.length; i++) {
  97298. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  97299. mesh = childMeshes[i];
  97300. this.webVRController._pointingPoseNode = mesh;
  97301. break;
  97302. }
  97303. }
  97304. this._laserPointer.parent = mesh;
  97305. };
  97306. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  97307. if (distance === void 0) { distance = 100; }
  97308. this._laserPointer.scaling.y = distance;
  97309. this._laserPointer.position.z = -distance / 2;
  97310. };
  97311. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  97312. _super.prototype.dispose.call(this);
  97313. this._laserPointer.dispose();
  97314. if (this._meshAttachedObserver) {
  97315. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  97316. }
  97317. };
  97318. return VRExperienceHelperControllerGazer;
  97319. }(VRExperienceHelperGazer));
  97320. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  97321. __extends(VRExperienceHelperCameraGazer, _super);
  97322. function VRExperienceHelperCameraGazer(getCamera, scene) {
  97323. var _this = _super.call(this, scene) || this;
  97324. _this.getCamera = getCamera;
  97325. return _this;
  97326. }
  97327. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  97328. var camera = this.getCamera();
  97329. if (camera) {
  97330. return camera.getForwardRay(length);
  97331. }
  97332. else {
  97333. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  97334. }
  97335. };
  97336. return VRExperienceHelperCameraGazer;
  97337. }(VRExperienceHelperGazer));
  97338. /**
  97339. * Helps to quickly add VR support to an existing scene.
  97340. * See http://doc.babylonjs.com/how_to/webvr_helper
  97341. */
  97342. var VRExperienceHelper = /** @class */ (function () {
  97343. /**
  97344. * Instantiates a VRExperienceHelper.
  97345. * Helps to quickly add VR support to an existing scene.
  97346. * @param scene The scene the VRExperienceHelper belongs to.
  97347. * @param webVROptions Options to modify the vr experience helper's behavior.
  97348. */
  97349. function VRExperienceHelper(scene,
  97350. /** Options to modify the vr experience helper's behavior. */
  97351. webVROptions) {
  97352. if (webVROptions === void 0) { webVROptions = {}; }
  97353. var _this = this;
  97354. this.webVROptions = webVROptions;
  97355. // Can the system support WebVR, even if a headset isn't plugged in?
  97356. this._webVRsupported = false;
  97357. // If WebVR is supported, is a headset plugged in and are we ready to present?
  97358. this._webVRready = false;
  97359. // Are we waiting for the requestPresent callback to complete?
  97360. this._webVRrequesting = false;
  97361. // Are we presenting to the headset right now? (this is the vrDevice state)
  97362. this._webVRpresenting = false;
  97363. // Are we presenting in the fullscreen fallback?
  97364. this._fullscreenVRpresenting = false;
  97365. /**
  97366. * Observable raised when entering VR.
  97367. */
  97368. this.onEnteringVRObservable = new BABYLON.Observable();
  97369. /**
  97370. * Observable raised when exiting VR.
  97371. */
  97372. this.onExitingVRObservable = new BABYLON.Observable();
  97373. /**
  97374. * Observable raised when controller mesh is loaded.
  97375. */
  97376. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  97377. this._useCustomVRButton = false;
  97378. this._teleportationRequested = false;
  97379. this._teleportActive = false;
  97380. this._floorMeshesCollection = [];
  97381. this._rotationAllowed = true;
  97382. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  97383. this._isDefaultTeleportationTarget = true;
  97384. this._teleportationFillColor = "#444444";
  97385. this._teleportationBorderColor = "#FFFFFF";
  97386. this._rotationAngle = 0;
  97387. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  97388. this._padSensibilityUp = 0.65;
  97389. this._padSensibilityDown = 0.35;
  97390. this._leftController = null;
  97391. this._rightController = null;
  97392. /**
  97393. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  97394. */
  97395. this.onNewMeshSelected = new BABYLON.Observable();
  97396. /**
  97397. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  97398. */
  97399. this.onNewMeshPicked = new BABYLON.Observable();
  97400. /**
  97401. * Observable raised before camera teleportation
  97402. */
  97403. this.onBeforeCameraTeleport = new BABYLON.Observable();
  97404. /**
  97405. * Observable raised after camera teleportation
  97406. */
  97407. this.onAfterCameraTeleport = new BABYLON.Observable();
  97408. /**
  97409. * Observable raised when current selected mesh gets unselected
  97410. */
  97411. this.onSelectedMeshUnselected = new BABYLON.Observable();
  97412. /**
  97413. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  97414. */
  97415. this.teleportationEnabled = true;
  97416. this._teleportationInitialized = false;
  97417. this._interactionsEnabled = false;
  97418. this._interactionsRequested = false;
  97419. this._displayGaze = true;
  97420. this._displayLaserPointer = true;
  97421. /**
  97422. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  97423. */
  97424. this.updateGazeTrackerScale = true;
  97425. this._onResize = function () {
  97426. _this.moveButtonToBottomRight();
  97427. if (_this._fullscreenVRpresenting && _this._webVRready) {
  97428. _this.exitVR();
  97429. }
  97430. };
  97431. this._onFullscreenChange = function () {
  97432. if (document.fullscreen !== undefined) {
  97433. _this._fullscreenVRpresenting = document.fullscreen;
  97434. }
  97435. else if (document.mozFullScreen !== undefined) {
  97436. _this._fullscreenVRpresenting = document.mozFullScreen;
  97437. }
  97438. else if (document.webkitIsFullScreen !== undefined) {
  97439. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  97440. }
  97441. else if (document.msIsFullScreen !== undefined) {
  97442. _this._fullscreenVRpresenting = document.msIsFullScreen;
  97443. }
  97444. else if (document.msFullscreenElement !== undefined) {
  97445. _this._fullscreenVRpresenting = document.msFullscreenElement;
  97446. }
  97447. if (!_this._fullscreenVRpresenting && _this._canvas) {
  97448. _this.exitVR();
  97449. if (!_this._useCustomVRButton) {
  97450. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  97451. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  97452. }
  97453. }
  97454. };
  97455. this.beforeRender = function () {
  97456. if (_this._leftController && _this._leftController._activePointer) {
  97457. _this._castRayAndSelectObject(_this._leftController);
  97458. }
  97459. if (_this._rightController && _this._rightController._activePointer) {
  97460. _this._castRayAndSelectObject(_this._rightController);
  97461. }
  97462. if (_this._noControllerIsActive) {
  97463. _this._castRayAndSelectObject(_this._cameraGazer);
  97464. }
  97465. else {
  97466. _this._cameraGazer._gazeTracker.isVisible = false;
  97467. }
  97468. };
  97469. this._onNewGamepadConnected = function (gamepad) {
  97470. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  97471. if (gamepad.leftStick) {
  97472. gamepad.onleftstickchanged(function (stickValues) {
  97473. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  97474. // Listening to classic/xbox gamepad only if no VR controller is active
  97475. if ((!_this._leftController && !_this._rightController) ||
  97476. ((_this._leftController && !_this._leftController._activePointer) &&
  97477. (_this._rightController && !_this._rightController._activePointer))) {
  97478. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  97479. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  97480. }
  97481. }
  97482. });
  97483. }
  97484. if (gamepad.rightStick) {
  97485. gamepad.onrightstickchanged(function (stickValues) {
  97486. if (_this._teleportationInitialized) {
  97487. _this._checkRotate(stickValues, _this._cameraGazer);
  97488. }
  97489. });
  97490. }
  97491. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  97492. gamepad.onbuttondown(function (buttonPressed) {
  97493. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97494. _this._cameraGazer._selectionPointerDown();
  97495. }
  97496. });
  97497. gamepad.onbuttonup(function (buttonPressed) {
  97498. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97499. _this._cameraGazer._selectionPointerUp();
  97500. }
  97501. });
  97502. }
  97503. }
  97504. else {
  97505. var webVRController = gamepad;
  97506. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  97507. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  97508. _this._rightController = controller;
  97509. }
  97510. else {
  97511. _this._leftController = controller;
  97512. }
  97513. _this._tryEnableInteractionOnController(controller);
  97514. }
  97515. };
  97516. // 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
  97517. this._tryEnableInteractionOnController = function (controller) {
  97518. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  97519. _this._enableInteractionOnController(controller);
  97520. }
  97521. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  97522. _this._enableTeleportationOnController(controller);
  97523. }
  97524. };
  97525. this._onNewGamepadDisconnected = function (gamepad) {
  97526. if (gamepad instanceof BABYLON.WebVRController) {
  97527. if (gamepad.hand === "left" && _this._leftController != null) {
  97528. _this._leftController.dispose();
  97529. _this._leftController = null;
  97530. }
  97531. if (gamepad.hand === "right" && _this._rightController != null) {
  97532. _this._rightController.dispose();
  97533. _this._rightController = null;
  97534. }
  97535. }
  97536. };
  97537. this._workingVector = BABYLON.Vector3.Zero();
  97538. this._workingQuaternion = BABYLON.Quaternion.Identity();
  97539. this._workingMatrix = BABYLON.Matrix.Identity();
  97540. this._scene = scene;
  97541. this._canvas = scene.getEngine().getRenderingCanvas();
  97542. // Parse options
  97543. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  97544. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  97545. }
  97546. if (webVROptions.createDeviceOrientationCamera === undefined) {
  97547. webVROptions.createDeviceOrientationCamera = true;
  97548. }
  97549. if (webVROptions.laserToggle === undefined) {
  97550. webVROptions.laserToggle = true;
  97551. }
  97552. if (webVROptions.defaultHeight === undefined) {
  97553. webVROptions.defaultHeight = 1.7;
  97554. }
  97555. if (webVROptions.useCustomVRButton) {
  97556. this._useCustomVRButton = true;
  97557. if (webVROptions.customVRButton) {
  97558. this._btnVR = webVROptions.customVRButton;
  97559. }
  97560. }
  97561. if (webVROptions.rayLength) {
  97562. this._rayLength = webVROptions.rayLength;
  97563. }
  97564. this._defaultHeight = webVROptions.defaultHeight;
  97565. if (webVROptions.positionScale) {
  97566. this._rayLength *= webVROptions.positionScale;
  97567. this._defaultHeight *= webVROptions.positionScale;
  97568. }
  97569. this._hasEnteredVR = false;
  97570. // Set position
  97571. if (this._scene.activeCamera) {
  97572. this._position = this._scene.activeCamera.position.clone();
  97573. }
  97574. else {
  97575. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  97576. }
  97577. // Set non-vr camera
  97578. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  97579. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  97580. // Copy data from existing camera
  97581. if (this._scene.activeCamera) {
  97582. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  97583. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  97584. // Set rotation from previous camera
  97585. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  97586. var targetCamera = this._scene.activeCamera;
  97587. if (targetCamera.rotationQuaternion) {
  97588. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  97589. }
  97590. else {
  97591. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  97592. }
  97593. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  97594. }
  97595. }
  97596. this._scene.activeCamera = this._deviceOrientationCamera;
  97597. if (this._canvas) {
  97598. this._scene.activeCamera.attachControl(this._canvas);
  97599. }
  97600. }
  97601. else {
  97602. this._existingCamera = this._scene.activeCamera;
  97603. }
  97604. // Create VR cameras
  97605. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  97606. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  97607. }
  97608. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  97609. this._webVRCamera.useStandingMatrix();
  97610. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  97611. // Create default button
  97612. if (!this._useCustomVRButton) {
  97613. this._btnVR = document.createElement("BUTTON");
  97614. this._btnVR.className = "babylonVRicon";
  97615. this._btnVR.id = "babylonVRiconbtn";
  97616. this._btnVR.title = "Click to switch to VR";
  97617. 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) }";
  97618. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  97619. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  97620. // css += ".babylonVRicon.vrdisplaysupported { }";
  97621. // css += ".babylonVRicon.vrdisplayready { }";
  97622. // css += ".babylonVRicon.vrdisplayrequesting { }";
  97623. var style = document.createElement('style');
  97624. style.appendChild(document.createTextNode(css));
  97625. document.getElementsByTagName('head')[0].appendChild(style);
  97626. this.moveButtonToBottomRight();
  97627. }
  97628. // VR button click event
  97629. if (this._btnVR) {
  97630. this._btnVR.addEventListener("click", function () {
  97631. if (!_this.isInVRMode) {
  97632. _this.enterVR();
  97633. }
  97634. else {
  97635. _this.exitVR();
  97636. }
  97637. });
  97638. }
  97639. // Window events
  97640. window.addEventListener("resize", this._onResize);
  97641. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  97642. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  97643. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  97644. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  97645. document.onmsfullscreenchange = this._onFullscreenChange;
  97646. // Display vr button when headset is connected
  97647. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  97648. this.displayVRButton();
  97649. }
  97650. else {
  97651. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  97652. if (e.vrDisplay) {
  97653. _this.displayVRButton();
  97654. }
  97655. });
  97656. }
  97657. // Exiting VR mode using 'ESC' key on desktop
  97658. this._onKeyDown = function (event) {
  97659. if (event.keyCode === 27 && _this.isInVRMode) {
  97660. _this.exitVR();
  97661. }
  97662. };
  97663. document.addEventListener("keydown", this._onKeyDown);
  97664. // Exiting VR mode double tapping the touch screen
  97665. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  97666. if (_this.isInVRMode) {
  97667. _this.exitVR();
  97668. if (_this._fullscreenVRpresenting) {
  97669. _this._scene.getEngine().switchFullscreen(true);
  97670. }
  97671. }
  97672. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  97673. // Listen for WebVR display changes
  97674. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  97675. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  97676. this._onVRRequestPresentStart = function () {
  97677. _this._webVRrequesting = true;
  97678. _this.updateButtonVisibility();
  97679. };
  97680. this._onVRRequestPresentComplete = function (success) {
  97681. _this._webVRrequesting = false;
  97682. _this.updateButtonVisibility();
  97683. };
  97684. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  97685. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  97686. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  97687. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97688. scene.onDisposeObservable.add(function () {
  97689. _this.dispose();
  97690. });
  97691. // Gamepad connection events
  97692. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  97693. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  97694. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  97695. this.updateButtonVisibility();
  97696. //create easing functions
  97697. this._circleEase = new BABYLON.CircleEase();
  97698. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  97699. if (this.webVROptions.floorMeshes) {
  97700. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  97701. }
  97702. }
  97703. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  97704. /** Return this.onEnteringVRObservable
  97705. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  97706. */
  97707. get: function () {
  97708. return this.onEnteringVRObservable;
  97709. },
  97710. enumerable: true,
  97711. configurable: true
  97712. });
  97713. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  97714. /** Return this.onExitingVRObservable
  97715. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  97716. */
  97717. get: function () {
  97718. return this.onExitingVRObservable;
  97719. },
  97720. enumerable: true,
  97721. configurable: true
  97722. });
  97723. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  97724. /** Return this.onControllerMeshLoadedObservable
  97725. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  97726. */
  97727. get: function () {
  97728. return this.onControllerMeshLoadedObservable;
  97729. },
  97730. enumerable: true,
  97731. configurable: true
  97732. });
  97733. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  97734. /**
  97735. * The mesh used to display where the user is going to teleport.
  97736. */
  97737. get: function () {
  97738. return this._teleportationTarget;
  97739. },
  97740. /**
  97741. * Sets the mesh to be used to display where the user is going to teleport.
  97742. */
  97743. set: function (value) {
  97744. if (value) {
  97745. value.name = "teleportationTarget";
  97746. this._isDefaultTeleportationTarget = false;
  97747. this._teleportationTarget = value;
  97748. }
  97749. },
  97750. enumerable: true,
  97751. configurable: true
  97752. });
  97753. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  97754. /**
  97755. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  97756. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  97757. * See http://doc.babylonjs.com/resources/baking_transformations
  97758. */
  97759. get: function () {
  97760. return this._cameraGazer._gazeTracker;
  97761. },
  97762. set: function (value) {
  97763. if (value) {
  97764. // Dispose of existing meshes
  97765. if (this._cameraGazer._gazeTracker) {
  97766. this._cameraGazer._gazeTracker.dispose();
  97767. }
  97768. if (this._leftController && this._leftController._gazeTracker) {
  97769. this._leftController._gazeTracker.dispose();
  97770. }
  97771. if (this._rightController && this._rightController._gazeTracker) {
  97772. this._rightController._gazeTracker.dispose();
  97773. }
  97774. // Set and create gaze trackers on head and controllers
  97775. this._cameraGazer._gazeTracker = value;
  97776. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  97777. this._cameraGazer._gazeTracker.isPickable = false;
  97778. this._cameraGazer._gazeTracker.isVisible = false;
  97779. this._cameraGazer._gazeTracker.name = "gazeTracker";
  97780. if (this._leftController) {
  97781. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97782. }
  97783. if (this._rightController) {
  97784. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97785. }
  97786. }
  97787. },
  97788. enumerable: true,
  97789. configurable: true
  97790. });
  97791. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  97792. /**
  97793. * The gaze tracking mesh corresponding to the left controller
  97794. */
  97795. get: function () {
  97796. if (this._leftController) {
  97797. return this._leftController._gazeTracker;
  97798. }
  97799. return null;
  97800. },
  97801. enumerable: true,
  97802. configurable: true
  97803. });
  97804. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  97805. /**
  97806. * The gaze tracking mesh corresponding to the right controller
  97807. */
  97808. get: function () {
  97809. if (this._rightController) {
  97810. return this._rightController._gazeTracker;
  97811. }
  97812. return null;
  97813. },
  97814. enumerable: true,
  97815. configurable: true
  97816. });
  97817. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  97818. /**
  97819. * If the ray of the gaze should be displayed.
  97820. */
  97821. get: function () {
  97822. return this._displayGaze;
  97823. },
  97824. /**
  97825. * Sets if the ray of the gaze should be displayed.
  97826. */
  97827. set: function (value) {
  97828. this._displayGaze = value;
  97829. if (!value) {
  97830. this._cameraGazer._gazeTracker.isVisible = false;
  97831. if (this._leftController) {
  97832. this._leftController._gazeTracker.isVisible = false;
  97833. }
  97834. if (this._rightController) {
  97835. this._rightController._gazeTracker.isVisible = false;
  97836. }
  97837. }
  97838. },
  97839. enumerable: true,
  97840. configurable: true
  97841. });
  97842. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  97843. /**
  97844. * If the ray of the LaserPointer should be displayed.
  97845. */
  97846. get: function () {
  97847. return this._displayLaserPointer;
  97848. },
  97849. /**
  97850. * Sets if the ray of the LaserPointer should be displayed.
  97851. */
  97852. set: function (value) {
  97853. this._displayLaserPointer = value;
  97854. if (!value) {
  97855. if (this._rightController) {
  97856. this._rightController._deactivatePointer();
  97857. this._rightController._gazeTracker.isVisible = false;
  97858. }
  97859. if (this._leftController) {
  97860. this._leftController._deactivatePointer();
  97861. this._leftController._gazeTracker.isVisible = false;
  97862. }
  97863. }
  97864. else {
  97865. if (this._rightController) {
  97866. this._rightController._activatePointer();
  97867. }
  97868. if (this._leftController) {
  97869. this._leftController._activatePointer();
  97870. }
  97871. }
  97872. },
  97873. enumerable: true,
  97874. configurable: true
  97875. });
  97876. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  97877. /**
  97878. * The deviceOrientationCamera used as the camera when not in VR.
  97879. */
  97880. get: function () {
  97881. return this._deviceOrientationCamera;
  97882. },
  97883. enumerable: true,
  97884. configurable: true
  97885. });
  97886. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  97887. /**
  97888. * Based on the current WebVR support, returns the current VR camera used.
  97889. */
  97890. get: function () {
  97891. if (this._webVRready) {
  97892. return this._webVRCamera;
  97893. }
  97894. else {
  97895. return this._scene.activeCamera;
  97896. }
  97897. },
  97898. enumerable: true,
  97899. configurable: true
  97900. });
  97901. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  97902. /**
  97903. * The webVRCamera which is used when in VR.
  97904. */
  97905. get: function () {
  97906. return this._webVRCamera;
  97907. },
  97908. enumerable: true,
  97909. configurable: true
  97910. });
  97911. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  97912. /**
  97913. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  97914. */
  97915. get: function () {
  97916. return this._vrDeviceOrientationCamera;
  97917. },
  97918. enumerable: true,
  97919. configurable: true
  97920. });
  97921. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  97922. get: function () {
  97923. var result = this._cameraGazer._teleportationRequestInitiated
  97924. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  97925. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  97926. return result;
  97927. },
  97928. enumerable: true,
  97929. configurable: true
  97930. });
  97931. // Raised when one of the controller has loaded successfully its associated default mesh
  97932. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  97933. if (this._leftController && this._leftController.webVRController == webVRController) {
  97934. if (webVRController.mesh) {
  97935. this._leftController._setLaserPointerParent(webVRController.mesh);
  97936. }
  97937. }
  97938. if (this._rightController && this._rightController.webVRController == webVRController) {
  97939. if (webVRController.mesh) {
  97940. this._rightController._setLaserPointerParent(webVRController.mesh);
  97941. }
  97942. }
  97943. try {
  97944. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  97945. }
  97946. catch (err) {
  97947. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  97948. }
  97949. };
  97950. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  97951. /**
  97952. * Gets a value indicating if we are currently in VR mode.
  97953. */
  97954. get: function () {
  97955. return this._webVRpresenting || this._fullscreenVRpresenting;
  97956. },
  97957. enumerable: true,
  97958. configurable: true
  97959. });
  97960. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  97961. var vrDisplay = this._scene.getEngine().getVRDevice();
  97962. if (vrDisplay) {
  97963. var wasPresenting = this._webVRpresenting;
  97964. this._webVRpresenting = vrDisplay.isPresenting;
  97965. if (wasPresenting && !this._webVRpresenting)
  97966. this.exitVR();
  97967. }
  97968. else {
  97969. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  97970. }
  97971. this.updateButtonVisibility();
  97972. };
  97973. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  97974. this._webVRsupported = eventArgs.vrSupported;
  97975. this._webVRready = !!eventArgs.vrDisplay;
  97976. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  97977. this.updateButtonVisibility();
  97978. };
  97979. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  97980. if (this._canvas && !this._useCustomVRButton) {
  97981. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  97982. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  97983. }
  97984. };
  97985. VRExperienceHelper.prototype.displayVRButton = function () {
  97986. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  97987. document.body.appendChild(this._btnVR);
  97988. this._btnVRDisplayed = true;
  97989. }
  97990. };
  97991. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  97992. if (!this._btnVR || this._useCustomVRButton) {
  97993. return;
  97994. }
  97995. this._btnVR.className = "babylonVRicon";
  97996. if (this.isInVRMode) {
  97997. this._btnVR.className += " vrdisplaypresenting";
  97998. }
  97999. else {
  98000. if (this._webVRready)
  98001. this._btnVR.className += " vrdisplayready";
  98002. if (this._webVRsupported)
  98003. this._btnVR.className += " vrdisplaysupported";
  98004. if (this._webVRrequesting)
  98005. this._btnVR.className += " vrdisplayrequesting";
  98006. }
  98007. };
  98008. /**
  98009. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  98010. * Otherwise, will use the fullscreen API.
  98011. */
  98012. VRExperienceHelper.prototype.enterVR = function () {
  98013. if (this.onEnteringVRObservable) {
  98014. try {
  98015. this.onEnteringVRObservable.notifyObservers(this);
  98016. }
  98017. catch (err) {
  98018. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  98019. }
  98020. }
  98021. if (this._scene.activeCamera) {
  98022. this._position = this._scene.activeCamera.position.clone();
  98023. // make sure that we return to the last active camera
  98024. this._existingCamera = this._scene.activeCamera;
  98025. }
  98026. if (this._webVRrequesting)
  98027. return;
  98028. // If WebVR is supported and a headset is connected
  98029. if (this._webVRready) {
  98030. if (!this._webVRpresenting) {
  98031. this._webVRCamera.position = this._position;
  98032. this._scene.activeCamera = this._webVRCamera;
  98033. }
  98034. }
  98035. else if (this._vrDeviceOrientationCamera) {
  98036. this._vrDeviceOrientationCamera.position = this._position;
  98037. if (this._scene.activeCamera) {
  98038. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98039. }
  98040. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  98041. this._scene.getEngine().switchFullscreen(true);
  98042. this.updateButtonVisibility();
  98043. }
  98044. if (this._scene.activeCamera && this._canvas) {
  98045. this._scene.activeCamera.attachControl(this._canvas);
  98046. }
  98047. if (this._interactionsEnabled) {
  98048. this._scene.registerBeforeRender(this.beforeRender);
  98049. }
  98050. this._hasEnteredVR = true;
  98051. };
  98052. /**
  98053. * Attempt to exit VR, or fullscreen.
  98054. */
  98055. VRExperienceHelper.prototype.exitVR = function () {
  98056. if (this._hasEnteredVR) {
  98057. if (this.onExitingVRObservable) {
  98058. try {
  98059. this.onExitingVRObservable.notifyObservers(this);
  98060. }
  98061. catch (err) {
  98062. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  98063. }
  98064. }
  98065. if (this._webVRpresenting) {
  98066. this._scene.getEngine().disableVR();
  98067. }
  98068. if (this._scene.activeCamera) {
  98069. this._position = this._scene.activeCamera.position.clone();
  98070. }
  98071. if (this._deviceOrientationCamera) {
  98072. this._deviceOrientationCamera.position = this._position;
  98073. this._scene.activeCamera = this._deviceOrientationCamera;
  98074. if (this._canvas) {
  98075. this._scene.activeCamera.attachControl(this._canvas);
  98076. }
  98077. }
  98078. else if (this._existingCamera) {
  98079. this._existingCamera.position = this._position;
  98080. this._scene.activeCamera = this._existingCamera;
  98081. }
  98082. this.updateButtonVisibility();
  98083. if (this._interactionsEnabled) {
  98084. this._scene.unregisterBeforeRender(this.beforeRender);
  98085. this._cameraGazer._gazeTracker.isVisible = false;
  98086. if (this._leftController) {
  98087. this._leftController._gazeTracker.isVisible = false;
  98088. }
  98089. if (this._rightController) {
  98090. this._rightController._gazeTracker.isVisible = false;
  98091. }
  98092. }
  98093. // resize to update width and height when exiting vr exits fullscreen
  98094. this._scene.getEngine().resize();
  98095. this._hasEnteredVR = false;
  98096. }
  98097. };
  98098. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  98099. /**
  98100. * The position of the vr experience helper.
  98101. */
  98102. get: function () {
  98103. return this._position;
  98104. },
  98105. /**
  98106. * Sets the position of the vr experience helper.
  98107. */
  98108. set: function (value) {
  98109. this._position = value;
  98110. if (this._scene.activeCamera) {
  98111. this._scene.activeCamera.position = value;
  98112. }
  98113. },
  98114. enumerable: true,
  98115. configurable: true
  98116. });
  98117. /**
  98118. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  98119. */
  98120. VRExperienceHelper.prototype.enableInteractions = function () {
  98121. var _this = this;
  98122. if (!this._interactionsEnabled) {
  98123. this._interactionsRequested = true;
  98124. if (this._leftController) {
  98125. this._enableInteractionOnController(this._leftController);
  98126. }
  98127. if (this._rightController) {
  98128. this._enableInteractionOnController(this._rightController);
  98129. }
  98130. this.raySelectionPredicate = function (mesh) {
  98131. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  98132. };
  98133. this.meshSelectionPredicate = function (mesh) {
  98134. return true;
  98135. };
  98136. this._raySelectionPredicate = function (mesh) {
  98137. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  98138. && mesh.name.indexOf("teleportationTarget") === -1
  98139. && mesh.name.indexOf("torusTeleportation") === -1)) {
  98140. return _this.raySelectionPredicate(mesh);
  98141. }
  98142. return false;
  98143. };
  98144. this._interactionsEnabled = true;
  98145. }
  98146. };
  98147. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  98148. get: function () {
  98149. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  98150. },
  98151. enumerable: true,
  98152. configurable: true
  98153. });
  98154. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  98155. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  98156. if (this._floorMeshesCollection[i].id === mesh.id) {
  98157. return true;
  98158. }
  98159. }
  98160. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  98161. return true;
  98162. }
  98163. return false;
  98164. };
  98165. /**
  98166. * Adds a floor mesh to be used for teleportation.
  98167. * @param floorMesh the mesh to be used for teleportation.
  98168. */
  98169. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  98170. if (!this._floorMeshesCollection) {
  98171. return;
  98172. }
  98173. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  98174. return;
  98175. }
  98176. this._floorMeshesCollection.push(floorMesh);
  98177. };
  98178. /**
  98179. * Removes a floor mesh from being used for teleportation.
  98180. * @param floorMesh the mesh to be removed.
  98181. */
  98182. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  98183. if (!this._floorMeshesCollection) {
  98184. return;
  98185. }
  98186. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  98187. if (meshIndex !== -1) {
  98188. this._floorMeshesCollection.splice(meshIndex, 1);
  98189. }
  98190. };
  98191. /**
  98192. * Enables interactions and teleportation using the VR controllers and gaze.
  98193. * @param vrTeleportationOptions options to modify teleportation behavior.
  98194. */
  98195. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  98196. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  98197. if (!this._teleportationInitialized) {
  98198. this._teleportationRequested = true;
  98199. this.enableInteractions();
  98200. if (vrTeleportationOptions.floorMeshName) {
  98201. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  98202. }
  98203. if (vrTeleportationOptions.floorMeshes) {
  98204. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  98205. }
  98206. if (this._leftController != null) {
  98207. this._enableTeleportationOnController(this._leftController);
  98208. }
  98209. if (this._rightController != null) {
  98210. this._enableTeleportationOnController(this._rightController);
  98211. }
  98212. // Creates an image processing post process for the vignette not relying
  98213. // on the main scene configuration for image processing to reduce setup and spaces
  98214. // (gamma/linear) conflicts.
  98215. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  98216. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  98217. imageProcessingConfiguration.vignetteEnabled = true;
  98218. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  98219. this._webVRCamera.detachPostProcess(this._postProcessMove);
  98220. this._teleportationInitialized = true;
  98221. if (this._isDefaultTeleportationTarget) {
  98222. this._createTeleportationCircles();
  98223. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  98224. }
  98225. }
  98226. };
  98227. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  98228. var _this = this;
  98229. var controllerMesh = controller.webVRController.mesh;
  98230. if (controllerMesh) {
  98231. controller._interactionsEnabled = true;
  98232. controller._activatePointer();
  98233. if (this.webVROptions.laserToggle) {
  98234. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  98235. // Enabling / disabling laserPointer
  98236. if (_this._displayLaserPointer && stateObject.value === 1) {
  98237. if (controller._activePointer) {
  98238. controller._deactivatePointer();
  98239. }
  98240. else {
  98241. controller._activatePointer();
  98242. }
  98243. if (_this.displayGaze) {
  98244. controller._gazeTracker.isVisible = controller._activePointer;
  98245. }
  98246. }
  98247. });
  98248. }
  98249. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  98250. var gazer = controller;
  98251. if (_this._noControllerIsActive) {
  98252. gazer = _this._cameraGazer;
  98253. }
  98254. if (!gazer._pointerDownOnMeshAsked) {
  98255. if (stateObject.value > _this._padSensibilityUp) {
  98256. gazer._selectionPointerDown();
  98257. }
  98258. }
  98259. else if (stateObject.value < _this._padSensibilityDown) {
  98260. gazer._selectionPointerUp();
  98261. }
  98262. });
  98263. }
  98264. };
  98265. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  98266. // Dont teleport if another gaze already requested teleportation
  98267. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  98268. return;
  98269. }
  98270. if (!gazer._teleportationRequestInitiated) {
  98271. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  98272. gazer._activatePointer();
  98273. gazer._teleportationRequestInitiated = true;
  98274. }
  98275. }
  98276. else {
  98277. // Listening to the proper controller values changes to confirm teleportation
  98278. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  98279. if (this._teleportActive) {
  98280. this.teleportCamera(this._haloCenter);
  98281. }
  98282. gazer._teleportationRequestInitiated = false;
  98283. }
  98284. }
  98285. };
  98286. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  98287. // Only rotate when user is not currently selecting a teleportation location
  98288. if (gazer._teleportationRequestInitiated) {
  98289. return;
  98290. }
  98291. if (!gazer._rotationLeftAsked) {
  98292. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  98293. gazer._rotationLeftAsked = true;
  98294. if (this._rotationAllowed) {
  98295. this._rotateCamera(false);
  98296. }
  98297. }
  98298. }
  98299. else {
  98300. if (stateObject.x > -this._padSensibilityDown) {
  98301. gazer._rotationLeftAsked = false;
  98302. }
  98303. }
  98304. if (!gazer._rotationRightAsked) {
  98305. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  98306. gazer._rotationRightAsked = true;
  98307. if (this._rotationAllowed) {
  98308. this._rotateCamera(true);
  98309. }
  98310. }
  98311. }
  98312. else {
  98313. if (stateObject.x < this._padSensibilityDown) {
  98314. gazer._rotationRightAsked = false;
  98315. }
  98316. }
  98317. };
  98318. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  98319. // Only teleport backwards when user is not currently selecting a teleportation location
  98320. if (gazer._teleportationRequestInitiated) {
  98321. return;
  98322. }
  98323. // Teleport backwards
  98324. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  98325. if (!gazer._teleportationBackRequestInitiated) {
  98326. if (!this.currentVRCamera) {
  98327. return;
  98328. }
  98329. // Get rotation and position of the current camera
  98330. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  98331. var position = this.currentVRCamera.position;
  98332. // If the camera has device position, use that instead
  98333. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  98334. rotation = this.currentVRCamera.deviceRotationQuaternion;
  98335. position = this.currentVRCamera.devicePosition;
  98336. }
  98337. // Get matrix with only the y rotation of the device rotation
  98338. rotation.toEulerAnglesToRef(this._workingVector);
  98339. this._workingVector.z = 0;
  98340. this._workingVector.x = 0;
  98341. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  98342. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  98343. // Rotate backwards ray by device rotation to cast at the ground behind the user
  98344. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  98345. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  98346. var ray = new BABYLON.Ray(position, this._workingVector);
  98347. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98348. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  98349. this.teleportCamera(hit.pickedPoint);
  98350. }
  98351. gazer._teleportationBackRequestInitiated = true;
  98352. }
  98353. }
  98354. else {
  98355. gazer._teleportationBackRequestInitiated = false;
  98356. }
  98357. };
  98358. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  98359. var _this = this;
  98360. var controllerMesh = controller.webVRController.mesh;
  98361. if (controllerMesh) {
  98362. if (!controller._interactionsEnabled) {
  98363. this._enableInteractionOnController(controller);
  98364. }
  98365. controller._interactionsEnabled = true;
  98366. controller._teleportationEnabled = true;
  98367. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  98368. controller._dpadPressed = false;
  98369. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  98370. controller._dpadPressed = stateObject.pressed;
  98371. if (!controller._dpadPressed) {
  98372. controller._rotationLeftAsked = false;
  98373. controller._rotationRightAsked = false;
  98374. controller._teleportationBackRequestInitiated = false;
  98375. }
  98376. });
  98377. }
  98378. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  98379. if (_this.teleportationEnabled) {
  98380. _this._checkTeleportBackwards(stateObject, controller);
  98381. _this._checkTeleportWithRay(stateObject, controller);
  98382. }
  98383. _this._checkRotate(stateObject, controller);
  98384. });
  98385. }
  98386. };
  98387. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  98388. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  98389. this._teleportationTarget.isPickable = false;
  98390. var length = 512;
  98391. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  98392. dynamicTexture.hasAlpha = true;
  98393. var context = dynamicTexture.getContext();
  98394. var centerX = length / 2;
  98395. var centerY = length / 2;
  98396. var radius = 200;
  98397. context.beginPath();
  98398. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  98399. context.fillStyle = this._teleportationFillColor;
  98400. context.fill();
  98401. context.lineWidth = 10;
  98402. context.strokeStyle = this._teleportationBorderColor;
  98403. context.stroke();
  98404. context.closePath();
  98405. dynamicTexture.update();
  98406. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  98407. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  98408. this._teleportationTarget.material = teleportationCircleMaterial;
  98409. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  98410. torus.isPickable = false;
  98411. torus.parent = this._teleportationTarget;
  98412. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  98413. var keys = [];
  98414. keys.push({
  98415. frame: 0,
  98416. value: 0
  98417. });
  98418. keys.push({
  98419. frame: 30,
  98420. value: 0.4
  98421. });
  98422. keys.push({
  98423. frame: 60,
  98424. value: 0
  98425. });
  98426. animationInnerCircle.setKeys(keys);
  98427. var easingFunction = new BABYLON.SineEase();
  98428. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98429. animationInnerCircle.setEasingFunction(easingFunction);
  98430. torus.animations = [];
  98431. torus.animations.push(animationInnerCircle);
  98432. this._scene.beginAnimation(torus, 0, 60, true);
  98433. this._hideTeleportationTarget();
  98434. };
  98435. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  98436. this._teleportActive = true;
  98437. if (this._teleportationInitialized) {
  98438. this._teleportationTarget.isVisible = true;
  98439. if (this._isDefaultTeleportationTarget) {
  98440. this._teleportationTarget.getChildren()[0].isVisible = true;
  98441. }
  98442. }
  98443. };
  98444. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  98445. this._teleportActive = false;
  98446. if (this._teleportationInitialized) {
  98447. this._teleportationTarget.isVisible = false;
  98448. if (this._isDefaultTeleportationTarget) {
  98449. this._teleportationTarget.getChildren()[0].isVisible = false;
  98450. }
  98451. }
  98452. };
  98453. VRExperienceHelper.prototype._rotateCamera = function (right) {
  98454. var _this = this;
  98455. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98456. return;
  98457. }
  98458. if (right) {
  98459. this._rotationAngle++;
  98460. }
  98461. else {
  98462. this._rotationAngle--;
  98463. }
  98464. this.currentVRCamera.animations = [];
  98465. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  98466. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98467. var animationRotationKeys = [];
  98468. animationRotationKeys.push({
  98469. frame: 0,
  98470. value: this.currentVRCamera.rotationQuaternion
  98471. });
  98472. animationRotationKeys.push({
  98473. frame: 6,
  98474. value: target
  98475. });
  98476. animationRotation.setKeys(animationRotationKeys);
  98477. animationRotation.setEasingFunction(this._circleEase);
  98478. this.currentVRCamera.animations.push(animationRotation);
  98479. this._postProcessMove.animations = [];
  98480. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98481. var vignetteWeightKeys = [];
  98482. vignetteWeightKeys.push({
  98483. frame: 0,
  98484. value: 0
  98485. });
  98486. vignetteWeightKeys.push({
  98487. frame: 3,
  98488. value: 4
  98489. });
  98490. vignetteWeightKeys.push({
  98491. frame: 6,
  98492. value: 0
  98493. });
  98494. animationPP.setKeys(vignetteWeightKeys);
  98495. animationPP.setEasingFunction(this._circleEase);
  98496. this._postProcessMove.animations.push(animationPP);
  98497. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98498. var vignetteStretchKeys = [];
  98499. vignetteStretchKeys.push({
  98500. frame: 0,
  98501. value: 0
  98502. });
  98503. vignetteStretchKeys.push({
  98504. frame: 3,
  98505. value: 10
  98506. });
  98507. vignetteStretchKeys.push({
  98508. frame: 6,
  98509. value: 0
  98510. });
  98511. animationPP2.setKeys(vignetteStretchKeys);
  98512. animationPP2.setEasingFunction(this._circleEase);
  98513. this._postProcessMove.animations.push(animationPP2);
  98514. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98515. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98516. this._postProcessMove.samples = 4;
  98517. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98518. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  98519. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98520. });
  98521. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  98522. };
  98523. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  98524. if (hit.pickedPoint) {
  98525. if (gazer._teleportationRequestInitiated) {
  98526. this._displayTeleportationTarget();
  98527. this._haloCenter.copyFrom(hit.pickedPoint);
  98528. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  98529. }
  98530. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  98531. if (pickNormal) {
  98532. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  98533. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  98534. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  98535. }
  98536. this._teleportationTarget.position.y += 0.1;
  98537. }
  98538. };
  98539. /**
  98540. * Teleports the users feet to the desired location
  98541. * @param location The location where the user's feet should be placed
  98542. */
  98543. VRExperienceHelper.prototype.teleportCamera = function (location) {
  98544. var _this = this;
  98545. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98546. return;
  98547. }
  98548. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  98549. // offset of the headset from the anchor.
  98550. if (this.webVRCamera.leftCamera) {
  98551. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  98552. this._workingVector.subtractInPlace(this.webVRCamera.position);
  98553. location.subtractToRef(this._workingVector, this._workingVector);
  98554. }
  98555. else {
  98556. this._workingVector.copyFrom(location);
  98557. }
  98558. // Add height to account for user's height offset
  98559. if (this.isInVRMode) {
  98560. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  98561. }
  98562. else {
  98563. this._workingVector.y += this._defaultHeight;
  98564. }
  98565. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  98566. // Create animation from the camera's position to the new location
  98567. this.currentVRCamera.animations = [];
  98568. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98569. var animationCameraTeleportationKeys = [{
  98570. frame: 0,
  98571. value: this.currentVRCamera.position
  98572. },
  98573. {
  98574. frame: 11,
  98575. value: this._workingVector
  98576. }
  98577. ];
  98578. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  98579. animationCameraTeleportation.setEasingFunction(this._circleEase);
  98580. this.currentVRCamera.animations.push(animationCameraTeleportation);
  98581. this._postProcessMove.animations = [];
  98582. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98583. var vignetteWeightKeys = [];
  98584. vignetteWeightKeys.push({
  98585. frame: 0,
  98586. value: 0
  98587. });
  98588. vignetteWeightKeys.push({
  98589. frame: 5,
  98590. value: 8
  98591. });
  98592. vignetteWeightKeys.push({
  98593. frame: 11,
  98594. value: 0
  98595. });
  98596. animationPP.setKeys(vignetteWeightKeys);
  98597. this._postProcessMove.animations.push(animationPP);
  98598. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98599. var vignetteStretchKeys = [];
  98600. vignetteStretchKeys.push({
  98601. frame: 0,
  98602. value: 0
  98603. });
  98604. vignetteStretchKeys.push({
  98605. frame: 5,
  98606. value: 10
  98607. });
  98608. vignetteStretchKeys.push({
  98609. frame: 11,
  98610. value: 0
  98611. });
  98612. animationPP2.setKeys(vignetteStretchKeys);
  98613. this._postProcessMove.animations.push(animationPP2);
  98614. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98615. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98616. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98617. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  98618. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98619. });
  98620. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  98621. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  98622. });
  98623. this._hideTeleportationTarget();
  98624. };
  98625. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  98626. if (normal) {
  98627. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  98628. if (angle < Math.PI / 2) {
  98629. normal.scaleInPlace(-1);
  98630. }
  98631. }
  98632. return normal;
  98633. };
  98634. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  98635. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98636. return;
  98637. }
  98638. var ray = gazer._getForwardRay(this._rayLength);
  98639. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98640. if (hit) {
  98641. // Populate the contrllers mesh that can be used for drag/drop
  98642. if (gazer._laserPointer) {
  98643. hit.originMesh = gazer._laserPointer.parent;
  98644. }
  98645. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  98646. }
  98647. gazer._currentHit = hit;
  98648. // Moving the gazeTracker on the mesh face targetted
  98649. if (hit && hit.pickedPoint) {
  98650. if (this._displayGaze) {
  98651. var multiplier = 1;
  98652. gazer._gazeTracker.isVisible = true;
  98653. if (gazer._isActionableMesh) {
  98654. multiplier = 3;
  98655. }
  98656. if (this.updateGazeTrackerScale) {
  98657. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  98658. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  98659. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  98660. }
  98661. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  98662. // To avoid z-fighting
  98663. var deltaFighting = 0.002;
  98664. if (pickNormal) {
  98665. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  98666. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  98667. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  98668. }
  98669. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  98670. if (gazer._gazeTracker.position.x < 0) {
  98671. gazer._gazeTracker.position.x += deltaFighting;
  98672. }
  98673. else {
  98674. gazer._gazeTracker.position.x -= deltaFighting;
  98675. }
  98676. if (gazer._gazeTracker.position.y < 0) {
  98677. gazer._gazeTracker.position.y += deltaFighting;
  98678. }
  98679. else {
  98680. gazer._gazeTracker.position.y -= deltaFighting;
  98681. }
  98682. if (gazer._gazeTracker.position.z < 0) {
  98683. gazer._gazeTracker.position.z += deltaFighting;
  98684. }
  98685. else {
  98686. gazer._gazeTracker.position.z -= deltaFighting;
  98687. }
  98688. }
  98689. // Changing the size of the laser pointer based on the distance from the targetted point
  98690. gazer._updatePointerDistance(hit.distance);
  98691. }
  98692. else {
  98693. gazer._updatePointerDistance();
  98694. gazer._gazeTracker.isVisible = false;
  98695. }
  98696. if (hit && hit.pickedMesh) {
  98697. // The object selected is the floor, we're in a teleportation scenario
  98698. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  98699. // Moving the teleportation area to this targetted point
  98700. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  98701. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  98702. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98703. }
  98704. gazer._currentMeshSelected = null;
  98705. if (gazer._teleportationRequestInitiated) {
  98706. this._moveTeleportationSelectorTo(hit, gazer, ray);
  98707. }
  98708. return;
  98709. }
  98710. // If not, we're in a selection scenario
  98711. //this._teleportationAllowed = false;
  98712. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  98713. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  98714. this.onNewMeshPicked.notifyObservers(hit);
  98715. gazer._currentMeshSelected = hit.pickedMesh;
  98716. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  98717. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  98718. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  98719. gazer._isActionableMesh = true;
  98720. }
  98721. else {
  98722. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98723. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98724. gazer._isActionableMesh = false;
  98725. }
  98726. try {
  98727. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  98728. }
  98729. catch (err) {
  98730. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  98731. }
  98732. }
  98733. else {
  98734. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98735. gazer._currentMeshSelected = null;
  98736. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98737. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98738. }
  98739. }
  98740. }
  98741. else {
  98742. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98743. gazer._currentMeshSelected = null;
  98744. //this._teleportationAllowed = false;
  98745. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98746. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98747. }
  98748. };
  98749. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  98750. if (mesh) {
  98751. this.onSelectedMeshUnselected.notifyObservers(mesh);
  98752. }
  98753. };
  98754. /**
  98755. * Sets the color of the laser ray from the vr controllers.
  98756. * @param color new color for the ray.
  98757. */
  98758. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  98759. if (this._leftController) {
  98760. this._leftController._setLaserPointerColor(color);
  98761. }
  98762. if (this._rightController) {
  98763. this._rightController._setLaserPointerColor(color);
  98764. }
  98765. };
  98766. /**
  98767. * Sets the color of the ray from the vr headsets gaze.
  98768. * @param color new color for the ray.
  98769. */
  98770. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  98771. if (!this._cameraGazer._gazeTracker.material) {
  98772. return;
  98773. }
  98774. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  98775. if (this._leftController) {
  98776. this._leftController._gazeTracker.material.emissiveColor = color;
  98777. }
  98778. if (this._rightController) {
  98779. this._rightController._gazeTracker.material.emissiveColor = color;
  98780. }
  98781. };
  98782. /**
  98783. * Exits VR and disposes of the vr experience helper
  98784. */
  98785. VRExperienceHelper.prototype.dispose = function () {
  98786. if (this.isInVRMode) {
  98787. this.exitVR();
  98788. }
  98789. if (this._postProcessMove) {
  98790. this._postProcessMove.dispose();
  98791. }
  98792. if (this._webVRCamera) {
  98793. this._webVRCamera.dispose();
  98794. }
  98795. if (this._vrDeviceOrientationCamera) {
  98796. this._vrDeviceOrientationCamera.dispose();
  98797. }
  98798. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  98799. document.body.removeChild(this._btnVR);
  98800. }
  98801. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  98802. this._deviceOrientationCamera.dispose();
  98803. }
  98804. if (this._cameraGazer) {
  98805. this._cameraGazer.dispose();
  98806. }
  98807. if (this._leftController) {
  98808. this._leftController.dispose();
  98809. }
  98810. if (this._rightController) {
  98811. this._rightController.dispose();
  98812. }
  98813. if (this._teleportationTarget) {
  98814. this._teleportationTarget.dispose();
  98815. }
  98816. this._floorMeshesCollection = [];
  98817. document.removeEventListener("keydown", this._onKeyDown);
  98818. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98819. window.removeEventListener("resize", this._onResize);
  98820. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  98821. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  98822. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  98823. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  98824. document.onmsfullscreenchange = null;
  98825. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  98826. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  98827. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  98828. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98829. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  98830. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  98831. this._scene.unregisterBeforeRender(this.beforeRender);
  98832. };
  98833. /**
  98834. * Gets the name of the VRExperienceHelper class
  98835. * @returns "VRExperienceHelper"
  98836. */
  98837. VRExperienceHelper.prototype.getClassName = function () {
  98838. return "VRExperienceHelper";
  98839. };
  98840. return VRExperienceHelper;
  98841. }());
  98842. BABYLON.VRExperienceHelper = VRExperienceHelper;
  98843. })(BABYLON || (BABYLON = {}));
  98844. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  98845. // Mainly based on these 2 articles :
  98846. // 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
  98847. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  98848. var BABYLON;
  98849. (function (BABYLON) {
  98850. /**
  98851. * Defines the potential axis of a Joystick
  98852. */
  98853. var JoystickAxis;
  98854. (function (JoystickAxis) {
  98855. /** X axis */
  98856. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  98857. /** Y axis */
  98858. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  98859. /** Z axis */
  98860. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  98861. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  98862. /**
  98863. * Class used to define virtual joystick (used in touch mode)
  98864. */
  98865. var VirtualJoystick = /** @class */ (function () {
  98866. /**
  98867. * Creates a new virtual joystick
  98868. * @param leftJoystick defines that the joystick is for left hand (false by default)
  98869. */
  98870. function VirtualJoystick(leftJoystick) {
  98871. var _this = this;
  98872. if (leftJoystick) {
  98873. this._leftJoystick = true;
  98874. }
  98875. else {
  98876. this._leftJoystick = false;
  98877. }
  98878. VirtualJoystick._globalJoystickIndex++;
  98879. // By default left & right arrow keys are moving the X
  98880. // and up & down keys are moving the Y
  98881. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  98882. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  98883. this.reverseLeftRight = false;
  98884. this.reverseUpDown = false;
  98885. // collections of pointers
  98886. this._touches = new BABYLON.StringDictionary();
  98887. this.deltaPosition = BABYLON.Vector3.Zero();
  98888. this._joystickSensibility = 25;
  98889. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98890. this._onResize = function (evt) {
  98891. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98892. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98893. if (VirtualJoystick.vjCanvas) {
  98894. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  98895. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  98896. }
  98897. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  98898. };
  98899. // injecting a canvas element on top of the canvas 3D game
  98900. if (!VirtualJoystick.vjCanvas) {
  98901. window.addEventListener("resize", this._onResize, false);
  98902. VirtualJoystick.vjCanvas = document.createElement("canvas");
  98903. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98904. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98905. VirtualJoystick.vjCanvas.width = window.innerWidth;
  98906. VirtualJoystick.vjCanvas.height = window.innerHeight;
  98907. VirtualJoystick.vjCanvas.style.width = "100%";
  98908. VirtualJoystick.vjCanvas.style.height = "100%";
  98909. VirtualJoystick.vjCanvas.style.position = "absolute";
  98910. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  98911. VirtualJoystick.vjCanvas.style.top = "0px";
  98912. VirtualJoystick.vjCanvas.style.left = "0px";
  98913. VirtualJoystick.vjCanvas.style.zIndex = "5";
  98914. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  98915. // Support for jQuery PEP polyfill
  98916. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  98917. var context = VirtualJoystick.vjCanvas.getContext('2d');
  98918. if (!context) {
  98919. throw new Error("Unable to create canvas for virtual joystick");
  98920. }
  98921. VirtualJoystick.vjCanvasContext = context;
  98922. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  98923. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  98924. document.body.appendChild(VirtualJoystick.vjCanvas);
  98925. }
  98926. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  98927. this.pressed = false;
  98928. // default joystick color
  98929. this._joystickColor = "cyan";
  98930. this._joystickPointerID = -1;
  98931. // current joystick position
  98932. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  98933. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  98934. // origin joystick position
  98935. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  98936. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  98937. this._onPointerDownHandlerRef = function (evt) {
  98938. _this._onPointerDown(evt);
  98939. };
  98940. this._onPointerMoveHandlerRef = function (evt) {
  98941. _this._onPointerMove(evt);
  98942. };
  98943. this._onPointerUpHandlerRef = function (evt) {
  98944. _this._onPointerUp(evt);
  98945. };
  98946. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  98947. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  98948. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  98949. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  98950. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  98951. evt.preventDefault(); // Disables system menu
  98952. }, false);
  98953. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  98954. }
  98955. /**
  98956. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  98957. * @param newJoystickSensibility defines the new sensibility
  98958. */
  98959. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  98960. this._joystickSensibility = newJoystickSensibility;
  98961. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98962. };
  98963. VirtualJoystick.prototype._onPointerDown = function (e) {
  98964. var positionOnScreenCondition;
  98965. e.preventDefault();
  98966. if (this._leftJoystick === true) {
  98967. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  98968. }
  98969. else {
  98970. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  98971. }
  98972. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  98973. // First contact will be dedicated to the virtual joystick
  98974. this._joystickPointerID = e.pointerId;
  98975. this._joystickPointerStartPos.x = e.clientX;
  98976. this._joystickPointerStartPos.y = e.clientY;
  98977. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  98978. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  98979. this._deltaJoystickVector.x = 0;
  98980. this._deltaJoystickVector.y = 0;
  98981. this.pressed = true;
  98982. this._touches.add(e.pointerId.toString(), e);
  98983. }
  98984. else {
  98985. // You can only trigger the action buttons with a joystick declared
  98986. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  98987. this._action();
  98988. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  98989. }
  98990. }
  98991. };
  98992. VirtualJoystick.prototype._onPointerMove = function (e) {
  98993. // If the current pointer is the one associated to the joystick (first touch contact)
  98994. if (this._joystickPointerID == e.pointerId) {
  98995. this._joystickPointerPos.x = e.clientX;
  98996. this._joystickPointerPos.y = e.clientY;
  98997. this._deltaJoystickVector = this._joystickPointerPos.clone();
  98998. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  98999. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  99000. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  99001. switch (this._axisTargetedByLeftAndRight) {
  99002. case JoystickAxis.X:
  99003. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  99004. break;
  99005. case JoystickAxis.Y:
  99006. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  99007. break;
  99008. case JoystickAxis.Z:
  99009. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  99010. break;
  99011. }
  99012. var directionUpDown = this.reverseUpDown ? 1 : -1;
  99013. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  99014. switch (this._axisTargetedByUpAndDown) {
  99015. case JoystickAxis.X:
  99016. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  99017. break;
  99018. case JoystickAxis.Y:
  99019. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  99020. break;
  99021. case JoystickAxis.Z:
  99022. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  99023. break;
  99024. }
  99025. }
  99026. else {
  99027. var data = this._touches.get(e.pointerId.toString());
  99028. if (data) {
  99029. data.x = e.clientX;
  99030. data.y = e.clientY;
  99031. }
  99032. }
  99033. };
  99034. VirtualJoystick.prototype._onPointerUp = function (e) {
  99035. if (this._joystickPointerID == e.pointerId) {
  99036. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  99037. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  99038. this._joystickPointerID = -1;
  99039. this.pressed = false;
  99040. }
  99041. else {
  99042. var touch = this._touches.get(e.pointerId.toString());
  99043. if (touch) {
  99044. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99045. }
  99046. }
  99047. this._deltaJoystickVector.x = 0;
  99048. this._deltaJoystickVector.y = 0;
  99049. this._touches.remove(e.pointerId.toString());
  99050. };
  99051. /**
  99052. * Change the color of the virtual joystick
  99053. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  99054. */
  99055. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  99056. this._joystickColor = newColor;
  99057. };
  99058. /**
  99059. * Defines a callback to call when the joystick is touched
  99060. * @param action defines the callback
  99061. */
  99062. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  99063. this._action = action;
  99064. };
  99065. /**
  99066. * Defines which axis you'd like to control for left & right
  99067. * @param axis defines the axis to use
  99068. */
  99069. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  99070. switch (axis) {
  99071. case JoystickAxis.X:
  99072. case JoystickAxis.Y:
  99073. case JoystickAxis.Z:
  99074. this._axisTargetedByLeftAndRight = axis;
  99075. break;
  99076. default:
  99077. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99078. break;
  99079. }
  99080. };
  99081. /**
  99082. * Defines which axis you'd like to control for up & down
  99083. * @param axis defines the axis to use
  99084. */
  99085. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  99086. switch (axis) {
  99087. case JoystickAxis.X:
  99088. case JoystickAxis.Y:
  99089. case JoystickAxis.Z:
  99090. this._axisTargetedByUpAndDown = axis;
  99091. break;
  99092. default:
  99093. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99094. break;
  99095. }
  99096. };
  99097. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  99098. var _this = this;
  99099. if (this.pressed) {
  99100. this._touches.forEach(function (key, touch) {
  99101. if (touch.pointerId === _this._joystickPointerID) {
  99102. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  99103. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  99104. VirtualJoystick.vjCanvasContext.beginPath();
  99105. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99106. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99107. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  99108. VirtualJoystick.vjCanvasContext.stroke();
  99109. VirtualJoystick.vjCanvasContext.closePath();
  99110. VirtualJoystick.vjCanvasContext.beginPath();
  99111. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99112. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99113. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  99114. VirtualJoystick.vjCanvasContext.stroke();
  99115. VirtualJoystick.vjCanvasContext.closePath();
  99116. VirtualJoystick.vjCanvasContext.beginPath();
  99117. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99118. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  99119. VirtualJoystick.vjCanvasContext.stroke();
  99120. VirtualJoystick.vjCanvasContext.closePath();
  99121. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  99122. }
  99123. else {
  99124. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99125. VirtualJoystick.vjCanvasContext.beginPath();
  99126. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  99127. VirtualJoystick.vjCanvasContext.beginPath();
  99128. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  99129. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99130. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  99131. VirtualJoystick.vjCanvasContext.stroke();
  99132. VirtualJoystick.vjCanvasContext.closePath();
  99133. touch.prevX = touch.x;
  99134. touch.prevY = touch.y;
  99135. }
  99136. ;
  99137. });
  99138. }
  99139. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99140. };
  99141. /**
  99142. * Release internal HTML canvas
  99143. */
  99144. VirtualJoystick.prototype.releaseCanvas = function () {
  99145. if (VirtualJoystick.vjCanvas) {
  99146. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  99147. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  99148. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  99149. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  99150. window.removeEventListener("resize", this._onResize);
  99151. document.body.removeChild(VirtualJoystick.vjCanvas);
  99152. VirtualJoystick.vjCanvas = null;
  99153. }
  99154. };
  99155. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  99156. VirtualJoystick._globalJoystickIndex = 0;
  99157. return VirtualJoystick;
  99158. }());
  99159. BABYLON.VirtualJoystick = VirtualJoystick;
  99160. })(BABYLON || (BABYLON = {}));
  99161. //# sourceMappingURL=babylon.virtualJoystick.js.map
  99162. var BABYLON;
  99163. (function (BABYLON) {
  99164. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  99165. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  99166. });
  99167. // We're mainly based on the logic defined into the FreeCamera code
  99168. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  99169. __extends(VirtualJoysticksCamera, _super);
  99170. function VirtualJoysticksCamera(name, position, scene) {
  99171. var _this = _super.call(this, name, position, scene) || this;
  99172. _this.inputs.addVirtualJoystick();
  99173. return _this;
  99174. }
  99175. VirtualJoysticksCamera.prototype.getClassName = function () {
  99176. return "VirtualJoysticksCamera";
  99177. };
  99178. return VirtualJoysticksCamera;
  99179. }(BABYLON.FreeCamera));
  99180. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  99181. })(BABYLON || (BABYLON = {}));
  99182. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  99183. var BABYLON;
  99184. (function (BABYLON) {
  99185. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  99186. function FreeCameraVirtualJoystickInput() {
  99187. }
  99188. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  99189. return this._leftjoystick;
  99190. };
  99191. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  99192. return this._rightjoystick;
  99193. };
  99194. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  99195. if (this._leftjoystick) {
  99196. var camera = this.camera;
  99197. var speed = camera._computeLocalCameraSpeed() * 50;
  99198. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  99199. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  99200. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  99201. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  99202. if (!this._leftjoystick.pressed) {
  99203. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  99204. }
  99205. if (!this._rightjoystick.pressed) {
  99206. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  99207. }
  99208. }
  99209. };
  99210. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  99211. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  99212. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  99213. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  99214. this._leftjoystick.setJoystickSensibility(0.15);
  99215. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  99216. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  99217. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  99218. this._rightjoystick.reverseUpDown = true;
  99219. this._rightjoystick.setJoystickSensibility(0.05);
  99220. this._rightjoystick.setJoystickColor("yellow");
  99221. };
  99222. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  99223. this._leftjoystick.releaseCanvas();
  99224. this._rightjoystick.releaseCanvas();
  99225. };
  99226. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  99227. return "FreeCameraVirtualJoystickInput";
  99228. };
  99229. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  99230. return "virtualJoystick";
  99231. };
  99232. return FreeCameraVirtualJoystickInput;
  99233. }());
  99234. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  99235. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  99236. })(BABYLON || (BABYLON = {}));
  99237. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  99238. var BABYLON;
  99239. (function (BABYLON) {
  99240. var SimplificationSettings = /** @class */ (function () {
  99241. function SimplificationSettings(quality, distance, optimizeMesh) {
  99242. this.quality = quality;
  99243. this.distance = distance;
  99244. this.optimizeMesh = optimizeMesh;
  99245. }
  99246. return SimplificationSettings;
  99247. }());
  99248. BABYLON.SimplificationSettings = SimplificationSettings;
  99249. var SimplificationQueue = /** @class */ (function () {
  99250. function SimplificationQueue() {
  99251. this.running = false;
  99252. this._simplificationArray = [];
  99253. }
  99254. SimplificationQueue.prototype.addTask = function (task) {
  99255. this._simplificationArray.push(task);
  99256. };
  99257. SimplificationQueue.prototype.executeNext = function () {
  99258. var task = this._simplificationArray.pop();
  99259. if (task) {
  99260. this.running = true;
  99261. this.runSimplification(task);
  99262. }
  99263. else {
  99264. this.running = false;
  99265. }
  99266. };
  99267. SimplificationQueue.prototype.runSimplification = function (task) {
  99268. var _this = this;
  99269. if (task.parallelProcessing) {
  99270. //parallel simplifier
  99271. task.settings.forEach(function (setting) {
  99272. var simplifier = _this.getSimplifier(task);
  99273. simplifier.simplify(setting, function (newMesh) {
  99274. task.mesh.addLODLevel(setting.distance, newMesh);
  99275. newMesh.isVisible = true;
  99276. //check if it is the last
  99277. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  99278. //all done, run the success callback.
  99279. task.successCallback();
  99280. }
  99281. _this.executeNext();
  99282. });
  99283. });
  99284. }
  99285. else {
  99286. //single simplifier.
  99287. var simplifier = this.getSimplifier(task);
  99288. var runDecimation = function (setting, callback) {
  99289. simplifier.simplify(setting, function (newMesh) {
  99290. task.mesh.addLODLevel(setting.distance, newMesh);
  99291. newMesh.isVisible = true;
  99292. //run the next quality level
  99293. callback();
  99294. });
  99295. };
  99296. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  99297. runDecimation(task.settings[loop.index], function () {
  99298. loop.executeNext();
  99299. });
  99300. }, function () {
  99301. //execution ended, run the success callback.
  99302. if (task.successCallback) {
  99303. task.successCallback();
  99304. }
  99305. _this.executeNext();
  99306. });
  99307. }
  99308. };
  99309. SimplificationQueue.prototype.getSimplifier = function (task) {
  99310. switch (task.simplificationType) {
  99311. case SimplificationType.QUADRATIC:
  99312. default:
  99313. return new QuadraticErrorSimplification(task.mesh);
  99314. }
  99315. };
  99316. return SimplificationQueue;
  99317. }());
  99318. BABYLON.SimplificationQueue = SimplificationQueue;
  99319. /**
  99320. * The implemented types of simplification
  99321. * At the moment only Quadratic Error Decimation is implemented
  99322. */
  99323. var SimplificationType;
  99324. (function (SimplificationType) {
  99325. /** Quadratic error decimation */
  99326. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  99327. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  99328. var DecimationTriangle = /** @class */ (function () {
  99329. function DecimationTriangle(vertices) {
  99330. this.vertices = vertices;
  99331. this.error = new Array(4);
  99332. this.deleted = false;
  99333. this.isDirty = false;
  99334. this.deletePending = false;
  99335. this.borderFactor = 0;
  99336. }
  99337. return DecimationTriangle;
  99338. }());
  99339. BABYLON.DecimationTriangle = DecimationTriangle;
  99340. var DecimationVertex = /** @class */ (function () {
  99341. function DecimationVertex(position, id) {
  99342. this.position = position;
  99343. this.id = id;
  99344. this.isBorder = true;
  99345. this.q = new QuadraticMatrix();
  99346. this.triangleCount = 0;
  99347. this.triangleStart = 0;
  99348. this.originalOffsets = [];
  99349. }
  99350. DecimationVertex.prototype.updatePosition = function (newPosition) {
  99351. this.position.copyFrom(newPosition);
  99352. };
  99353. return DecimationVertex;
  99354. }());
  99355. BABYLON.DecimationVertex = DecimationVertex;
  99356. var QuadraticMatrix = /** @class */ (function () {
  99357. function QuadraticMatrix(data) {
  99358. this.data = new Array(10);
  99359. for (var i = 0; i < 10; ++i) {
  99360. if (data && data[i]) {
  99361. this.data[i] = data[i];
  99362. }
  99363. else {
  99364. this.data[i] = 0;
  99365. }
  99366. }
  99367. }
  99368. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  99369. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  99370. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  99371. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  99372. return det;
  99373. };
  99374. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  99375. for (var i = 0; i < 10; ++i) {
  99376. this.data[i] += matrix.data[i];
  99377. }
  99378. };
  99379. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  99380. for (var i = 0; i < 10; ++i) {
  99381. this.data[i] += data[i];
  99382. }
  99383. };
  99384. QuadraticMatrix.prototype.add = function (matrix) {
  99385. var m = new QuadraticMatrix();
  99386. for (var i = 0; i < 10; ++i) {
  99387. m.data[i] = this.data[i] + matrix.data[i];
  99388. }
  99389. return m;
  99390. };
  99391. QuadraticMatrix.FromData = function (a, b, c, d) {
  99392. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  99393. };
  99394. //returning an array to avoid garbage collection
  99395. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  99396. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  99397. };
  99398. return QuadraticMatrix;
  99399. }());
  99400. BABYLON.QuadraticMatrix = QuadraticMatrix;
  99401. var Reference = /** @class */ (function () {
  99402. function Reference(vertexId, triangleId) {
  99403. this.vertexId = vertexId;
  99404. this.triangleId = triangleId;
  99405. }
  99406. return Reference;
  99407. }());
  99408. BABYLON.Reference = Reference;
  99409. /**
  99410. * An implementation of the Quadratic Error simplification algorithm.
  99411. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  99412. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  99413. * @author RaananW
  99414. */
  99415. var QuadraticErrorSimplification = /** @class */ (function () {
  99416. function QuadraticErrorSimplification(_mesh) {
  99417. this._mesh = _mesh;
  99418. this.syncIterations = 5000;
  99419. this.aggressiveness = 7;
  99420. this.decimationIterations = 100;
  99421. this.boundingBoxEpsilon = BABYLON.Epsilon;
  99422. }
  99423. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  99424. var _this = this;
  99425. this.initDecimatedMesh();
  99426. //iterating through the submeshes array, one after the other.
  99427. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  99428. _this.initWithMesh(loop.index, function () {
  99429. _this.runDecimation(settings, loop.index, function () {
  99430. loop.executeNext();
  99431. });
  99432. }, settings.optimizeMesh);
  99433. }, function () {
  99434. setTimeout(function () {
  99435. successCallback(_this._reconstructedMesh);
  99436. }, 0);
  99437. });
  99438. };
  99439. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  99440. var _this = this;
  99441. var targetCount = ~~(this.triangles.length * settings.quality);
  99442. var deletedTriangles = 0;
  99443. var triangleCount = this.triangles.length;
  99444. var iterationFunction = function (iteration, callback) {
  99445. setTimeout(function () {
  99446. if (iteration % 5 === 0) {
  99447. _this.updateMesh(iteration === 0);
  99448. }
  99449. for (var i = 0; i < _this.triangles.length; ++i) {
  99450. _this.triangles[i].isDirty = false;
  99451. }
  99452. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  99453. var trianglesIterator = function (i) {
  99454. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  99455. var t = _this.triangles[tIdx];
  99456. if (!t)
  99457. return;
  99458. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  99459. return;
  99460. }
  99461. for (var j = 0; j < 3; ++j) {
  99462. if (t.error[j] < threshold) {
  99463. var deleted0 = [];
  99464. var deleted1 = [];
  99465. var v0 = t.vertices[j];
  99466. var v1 = t.vertices[(j + 1) % 3];
  99467. if (v0.isBorder || v1.isBorder)
  99468. continue;
  99469. var p = BABYLON.Vector3.Zero();
  99470. var n = BABYLON.Vector3.Zero();
  99471. var uv = BABYLON.Vector2.Zero();
  99472. var color = new BABYLON.Color4(0, 0, 0, 1);
  99473. _this.calculateError(v0, v1, p, n, uv, color);
  99474. var delTr = new Array();
  99475. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  99476. continue;
  99477. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  99478. continue;
  99479. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  99480. continue;
  99481. var uniqueArray = new Array();
  99482. delTr.forEach(function (deletedT) {
  99483. if (uniqueArray.indexOf(deletedT) === -1) {
  99484. deletedT.deletePending = true;
  99485. uniqueArray.push(deletedT);
  99486. }
  99487. });
  99488. if (uniqueArray.length % 2 !== 0) {
  99489. continue;
  99490. }
  99491. v0.q = v1.q.add(v0.q);
  99492. v0.updatePosition(p);
  99493. var tStart = _this.references.length;
  99494. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  99495. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  99496. var tCount = _this.references.length - tStart;
  99497. if (tCount <= v0.triangleCount) {
  99498. if (tCount) {
  99499. for (var c = 0; c < tCount; c++) {
  99500. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  99501. }
  99502. }
  99503. }
  99504. else {
  99505. v0.triangleStart = tStart;
  99506. }
  99507. v0.triangleCount = tCount;
  99508. break;
  99509. }
  99510. }
  99511. };
  99512. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  99513. }, 0);
  99514. };
  99515. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  99516. if (triangleCount - deletedTriangles <= targetCount)
  99517. loop.breakLoop();
  99518. else {
  99519. iterationFunction(loop.index, function () {
  99520. loop.executeNext();
  99521. });
  99522. }
  99523. }, function () {
  99524. setTimeout(function () {
  99525. //reconstruct this part of the mesh
  99526. _this.reconstructMesh(submeshIndex);
  99527. successCallback();
  99528. }, 0);
  99529. });
  99530. };
  99531. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  99532. var _this = this;
  99533. this.vertices = [];
  99534. this.triangles = [];
  99535. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99536. var indices = this._mesh.getIndices();
  99537. var submesh = this._mesh.subMeshes[submeshIndex];
  99538. var findInVertices = function (positionToSearch) {
  99539. if (optimizeMesh) {
  99540. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  99541. if (_this.vertices[ii].position.equals(positionToSearch)) {
  99542. return _this.vertices[ii];
  99543. }
  99544. }
  99545. }
  99546. return null;
  99547. };
  99548. var vertexReferences = [];
  99549. var vertexInit = function (i) {
  99550. if (!positionData) {
  99551. return;
  99552. }
  99553. var offset = i + submesh.verticesStart;
  99554. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  99555. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  99556. vertex.originalOffsets.push(offset);
  99557. if (vertex.id === _this.vertices.length) {
  99558. _this.vertices.push(vertex);
  99559. }
  99560. vertexReferences.push(vertex.id);
  99561. };
  99562. //var totalVertices = mesh.getTotalVertices();
  99563. var totalVertices = submesh.verticesCount;
  99564. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  99565. var indicesInit = function (i) {
  99566. if (!indices) {
  99567. return;
  99568. }
  99569. var offset = (submesh.indexStart / 3) + i;
  99570. var pos = (offset * 3);
  99571. var i0 = indices[pos + 0];
  99572. var i1 = indices[pos + 1];
  99573. var i2 = indices[pos + 2];
  99574. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  99575. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  99576. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  99577. var triangle = new DecimationTriangle([v0, v1, v2]);
  99578. triangle.originalOffset = pos;
  99579. _this.triangles.push(triangle);
  99580. };
  99581. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  99582. _this.init(callback);
  99583. });
  99584. });
  99585. };
  99586. QuadraticErrorSimplification.prototype.init = function (callback) {
  99587. var _this = this;
  99588. var triangleInit1 = function (i) {
  99589. var t = _this.triangles[i];
  99590. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  99591. for (var j = 0; j < 3; j++) {
  99592. 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))));
  99593. }
  99594. };
  99595. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  99596. var triangleInit2 = function (i) {
  99597. var t = _this.triangles[i];
  99598. for (var j = 0; j < 3; ++j) {
  99599. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  99600. }
  99601. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  99602. };
  99603. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  99604. callback();
  99605. });
  99606. });
  99607. };
  99608. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  99609. var newTriangles = [];
  99610. var i;
  99611. for (i = 0; i < this.vertices.length; ++i) {
  99612. this.vertices[i].triangleCount = 0;
  99613. }
  99614. var t;
  99615. var j;
  99616. for (i = 0; i < this.triangles.length; ++i) {
  99617. if (!this.triangles[i].deleted) {
  99618. t = this.triangles[i];
  99619. for (j = 0; j < 3; ++j) {
  99620. t.vertices[j].triangleCount = 1;
  99621. }
  99622. newTriangles.push(t);
  99623. }
  99624. }
  99625. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  99626. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  99627. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  99628. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  99629. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  99630. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  99631. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  99632. var vertexCount = 0;
  99633. for (i = 0; i < this.vertices.length; ++i) {
  99634. var vertex = this.vertices[i];
  99635. vertex.id = vertexCount;
  99636. if (vertex.triangleCount) {
  99637. vertex.originalOffsets.forEach(function (originalOffset) {
  99638. if (!normalData) {
  99639. return;
  99640. }
  99641. newPositionData.push(vertex.position.x);
  99642. newPositionData.push(vertex.position.y);
  99643. newPositionData.push(vertex.position.z);
  99644. newNormalData.push(normalData[originalOffset * 3]);
  99645. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  99646. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  99647. if (uvs && uvs.length) {
  99648. newUVsData.push(uvs[(originalOffset * 2)]);
  99649. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  99650. }
  99651. else if (colorsData && colorsData.length) {
  99652. newColorsData.push(colorsData[(originalOffset * 4)]);
  99653. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  99654. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  99655. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  99656. }
  99657. ++vertexCount;
  99658. });
  99659. }
  99660. }
  99661. var startingIndex = this._reconstructedMesh.getTotalIndices();
  99662. var startingVertex = this._reconstructedMesh.getTotalVertices();
  99663. var submeshesArray = this._reconstructedMesh.subMeshes;
  99664. this._reconstructedMesh.subMeshes = [];
  99665. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  99666. var originalIndices = this._mesh.getIndices();
  99667. for (i = 0; i < newTriangles.length; ++i) {
  99668. t = newTriangles[i]; //now get the new referencing point for each vertex
  99669. [0, 1, 2].forEach(function (idx) {
  99670. var id = originalIndices[t.originalOffset + idx];
  99671. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  99672. if (offset < 0)
  99673. offset = 0;
  99674. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  99675. });
  99676. }
  99677. //overwriting the old vertex buffers and indices.
  99678. this._reconstructedMesh.setIndices(newIndicesArray);
  99679. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  99680. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  99681. if (newUVsData.length > 0)
  99682. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  99683. if (newColorsData.length > 0)
  99684. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  99685. //create submesh
  99686. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  99687. if (submeshIndex > 0) {
  99688. this._reconstructedMesh.subMeshes = [];
  99689. submeshesArray.forEach(function (submesh) {
  99690. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  99691. });
  99692. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  99693. }
  99694. };
  99695. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  99696. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  99697. this._reconstructedMesh.material = this._mesh.material;
  99698. this._reconstructedMesh.parent = this._mesh.parent;
  99699. this._reconstructedMesh.isVisible = false;
  99700. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  99701. };
  99702. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  99703. for (var i = 0; i < vertex1.triangleCount; ++i) {
  99704. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  99705. if (t.deleted)
  99706. continue;
  99707. var s = this.references[vertex1.triangleStart + i].vertexId;
  99708. var v1 = t.vertices[(s + 1) % 3];
  99709. var v2 = t.vertices[(s + 2) % 3];
  99710. if ((v1 === vertex2 || v2 === vertex2)) {
  99711. deletedArray[i] = true;
  99712. delTr.push(t);
  99713. continue;
  99714. }
  99715. var d1 = v1.position.subtract(point);
  99716. d1 = d1.normalize();
  99717. var d2 = v2.position.subtract(point);
  99718. d2 = d2.normalize();
  99719. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  99720. return true;
  99721. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  99722. deletedArray[i] = false;
  99723. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  99724. return true;
  99725. }
  99726. return false;
  99727. };
  99728. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  99729. var newDeleted = deletedTriangles;
  99730. for (var i = 0; i < vertex.triangleCount; ++i) {
  99731. var ref = this.references[vertex.triangleStart + i];
  99732. var t = this.triangles[ref.triangleId];
  99733. if (t.deleted)
  99734. continue;
  99735. if (deletedArray[i] && t.deletePending) {
  99736. t.deleted = true;
  99737. newDeleted++;
  99738. continue;
  99739. }
  99740. t.vertices[ref.vertexId] = origVertex;
  99741. t.isDirty = true;
  99742. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  99743. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  99744. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  99745. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  99746. this.references.push(ref);
  99747. }
  99748. return newDeleted;
  99749. };
  99750. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  99751. for (var i = 0; i < this.vertices.length; ++i) {
  99752. var vCount = [];
  99753. var vId = [];
  99754. var v = this.vertices[i];
  99755. var j;
  99756. for (j = 0; j < v.triangleCount; ++j) {
  99757. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  99758. for (var ii = 0; ii < 3; ii++) {
  99759. var ofs = 0;
  99760. var vv = triangle.vertices[ii];
  99761. while (ofs < vCount.length) {
  99762. if (vId[ofs] === vv.id)
  99763. break;
  99764. ++ofs;
  99765. }
  99766. if (ofs === vCount.length) {
  99767. vCount.push(1);
  99768. vId.push(vv.id);
  99769. }
  99770. else {
  99771. vCount[ofs]++;
  99772. }
  99773. }
  99774. }
  99775. for (j = 0; j < vCount.length; ++j) {
  99776. if (vCount[j] === 1) {
  99777. this.vertices[vId[j]].isBorder = true;
  99778. }
  99779. else {
  99780. this.vertices[vId[j]].isBorder = false;
  99781. }
  99782. }
  99783. }
  99784. };
  99785. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  99786. if (identifyBorders === void 0) { identifyBorders = false; }
  99787. var i;
  99788. if (!identifyBorders) {
  99789. var newTrianglesVector = [];
  99790. for (i = 0; i < this.triangles.length; ++i) {
  99791. if (!this.triangles[i].deleted) {
  99792. newTrianglesVector.push(this.triangles[i]);
  99793. }
  99794. }
  99795. this.triangles = newTrianglesVector;
  99796. }
  99797. for (i = 0; i < this.vertices.length; ++i) {
  99798. this.vertices[i].triangleCount = 0;
  99799. this.vertices[i].triangleStart = 0;
  99800. }
  99801. var t;
  99802. var j;
  99803. var v;
  99804. for (i = 0; i < this.triangles.length; ++i) {
  99805. t = this.triangles[i];
  99806. for (j = 0; j < 3; ++j) {
  99807. v = t.vertices[j];
  99808. v.triangleCount++;
  99809. }
  99810. }
  99811. var tStart = 0;
  99812. for (i = 0; i < this.vertices.length; ++i) {
  99813. this.vertices[i].triangleStart = tStart;
  99814. tStart += this.vertices[i].triangleCount;
  99815. this.vertices[i].triangleCount = 0;
  99816. }
  99817. var newReferences = new Array(this.triangles.length * 3);
  99818. for (i = 0; i < this.triangles.length; ++i) {
  99819. t = this.triangles[i];
  99820. for (j = 0; j < 3; ++j) {
  99821. v = t.vertices[j];
  99822. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  99823. v.triangleCount++;
  99824. }
  99825. }
  99826. this.references = newReferences;
  99827. if (identifyBorders) {
  99828. this.identifyBorder();
  99829. }
  99830. };
  99831. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  99832. var x = point.x;
  99833. var y = point.y;
  99834. var z = point.z;
  99835. 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
  99836. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  99837. };
  99838. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  99839. var q = vertex1.q.add(vertex2.q);
  99840. var border = vertex1.isBorder && vertex2.isBorder;
  99841. var error = 0;
  99842. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  99843. if (qDet !== 0 && !border) {
  99844. if (!pointResult) {
  99845. pointResult = BABYLON.Vector3.Zero();
  99846. }
  99847. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  99848. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  99849. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  99850. error = this.vertexError(q, pointResult);
  99851. }
  99852. else {
  99853. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  99854. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  99855. var error1 = this.vertexError(q, vertex1.position);
  99856. var error2 = this.vertexError(q, vertex2.position);
  99857. var error3 = this.vertexError(q, p3);
  99858. error = Math.min(error1, error2, error3);
  99859. if (error === error1) {
  99860. if (pointResult) {
  99861. pointResult.copyFrom(vertex1.position);
  99862. }
  99863. }
  99864. else if (error === error2) {
  99865. if (pointResult) {
  99866. pointResult.copyFrom(vertex2.position);
  99867. }
  99868. }
  99869. else {
  99870. if (pointResult) {
  99871. pointResult.copyFrom(p3);
  99872. }
  99873. }
  99874. }
  99875. return error;
  99876. };
  99877. return QuadraticErrorSimplification;
  99878. }());
  99879. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  99880. })(BABYLON || (BABYLON = {}));
  99881. //# sourceMappingURL=babylon.meshSimplification.js.map
  99882. var BABYLON;
  99883. (function (BABYLON) {
  99884. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  99885. get: function () {
  99886. if (!this._simplificationQueue) {
  99887. this._simplificationQueue = new BABYLON.SimplificationQueue();
  99888. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  99889. if (!component) {
  99890. component = new SimplicationQueueSceneComponent(this);
  99891. this._addComponent(component);
  99892. }
  99893. }
  99894. return this._simplificationQueue;
  99895. },
  99896. set: function (value) {
  99897. this._simplificationQueue = value;
  99898. },
  99899. enumerable: true,
  99900. configurable: true
  99901. });
  99902. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  99903. if (parallelProcessing === void 0) { parallelProcessing = true; }
  99904. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  99905. this.getScene().simplificationQueue.addTask({
  99906. settings: settings,
  99907. parallelProcessing: parallelProcessing,
  99908. mesh: this,
  99909. simplificationType: simplificationType,
  99910. successCallback: successCallback
  99911. });
  99912. return this;
  99913. };
  99914. /**
  99915. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  99916. * created in a scene
  99917. */
  99918. var SimplicationQueueSceneComponent = /** @class */ (function () {
  99919. /**
  99920. * Creates a new instance of the component for the given scene
  99921. * @param scene Defines the scene to register the component in
  99922. */
  99923. function SimplicationQueueSceneComponent(scene) {
  99924. /**
  99925. * The component name helpfull to identify the component in the list of scene components.
  99926. */
  99927. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  99928. this.scene = scene;
  99929. }
  99930. /**
  99931. * Registers the component in a given scene
  99932. */
  99933. SimplicationQueueSceneComponent.prototype.register = function () {
  99934. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  99935. };
  99936. /**
  99937. * Rebuilds the elements related to this component in case of
  99938. * context lost for instance.
  99939. */
  99940. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  99941. // Nothing to do for this component
  99942. };
  99943. /**
  99944. * Disposes the component and the associated ressources
  99945. */
  99946. SimplicationQueueSceneComponent.prototype.dispose = function () {
  99947. // Nothing to do for this component
  99948. };
  99949. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  99950. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  99951. this.scene._simplificationQueue.executeNext();
  99952. }
  99953. };
  99954. return SimplicationQueueSceneComponent;
  99955. }());
  99956. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  99957. })(BABYLON || (BABYLON = {}));
  99958. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  99959. var BABYLON;
  99960. (function (BABYLON) {
  99961. var MeshLODLevel = /** @class */ (function () {
  99962. function MeshLODLevel(distance, mesh) {
  99963. this.distance = distance;
  99964. this.mesh = mesh;
  99965. }
  99966. return MeshLODLevel;
  99967. }());
  99968. BABYLON.MeshLODLevel = MeshLODLevel;
  99969. })(BABYLON || (BABYLON = {}));
  99970. //# sourceMappingURL=babylon.meshLODLevel.js.map
  99971. var BABYLON;
  99972. (function (BABYLON) {
  99973. /**
  99974. * Defines the root class used to create scene optimization to use with SceneOptimizer
  99975. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99976. */
  99977. var SceneOptimization = /** @class */ (function () {
  99978. /**
  99979. * Creates the SceneOptimization object
  99980. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99981. * @param desc defines the description associated with the optimization
  99982. */
  99983. function SceneOptimization(
  99984. /**
  99985. * Defines the priority of this optimization (0 by default which means first in the list)
  99986. */
  99987. priority) {
  99988. if (priority === void 0) { priority = 0; }
  99989. this.priority = priority;
  99990. }
  99991. /**
  99992. * Gets a string describing the action executed by the current optimization
  99993. * @returns description string
  99994. */
  99995. SceneOptimization.prototype.getDescription = function () {
  99996. return "";
  99997. };
  99998. /**
  99999. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100000. * @param scene defines the current scene where to apply this optimization
  100001. * @param optimizer defines the current optimizer
  100002. * @returns true if everything that can be done was applied
  100003. */
  100004. SceneOptimization.prototype.apply = function (scene, optimizer) {
  100005. return true;
  100006. };
  100007. ;
  100008. return SceneOptimization;
  100009. }());
  100010. BABYLON.SceneOptimization = SceneOptimization;
  100011. /**
  100012. * Defines an optimization used to reduce the size of render target textures
  100013. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100014. */
  100015. var TextureOptimization = /** @class */ (function (_super) {
  100016. __extends(TextureOptimization, _super);
  100017. /**
  100018. * Creates the TextureOptimization object
  100019. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100020. * @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
  100021. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100022. */
  100023. function TextureOptimization(
  100024. /**
  100025. * Defines the priority of this optimization (0 by default which means first in the list)
  100026. */
  100027. priority,
  100028. /**
  100029. * 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
  100030. */
  100031. maximumSize,
  100032. /**
  100033. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100034. */
  100035. step) {
  100036. if (priority === void 0) { priority = 0; }
  100037. if (maximumSize === void 0) { maximumSize = 1024; }
  100038. if (step === void 0) { step = 0.5; }
  100039. var _this = _super.call(this, priority) || this;
  100040. _this.priority = priority;
  100041. _this.maximumSize = maximumSize;
  100042. _this.step = step;
  100043. return _this;
  100044. }
  100045. /**
  100046. * Gets a string describing the action executed by the current optimization
  100047. * @returns description string
  100048. */
  100049. TextureOptimization.prototype.getDescription = function () {
  100050. return "Reducing render target texture size to " + this.maximumSize;
  100051. };
  100052. /**
  100053. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100054. * @param scene defines the current scene where to apply this optimization
  100055. * @param optimizer defines the current optimizer
  100056. * @returns true if everything that can be done was applied
  100057. */
  100058. TextureOptimization.prototype.apply = function (scene, optimizer) {
  100059. var allDone = true;
  100060. for (var index = 0; index < scene.textures.length; index++) {
  100061. var texture = scene.textures[index];
  100062. if (!texture.canRescale || texture.getContext) {
  100063. continue;
  100064. }
  100065. var currentSize = texture.getSize();
  100066. var maxDimension = Math.max(currentSize.width, currentSize.height);
  100067. if (maxDimension > this.maximumSize) {
  100068. texture.scale(this.step);
  100069. allDone = false;
  100070. }
  100071. }
  100072. return allDone;
  100073. };
  100074. return TextureOptimization;
  100075. }(SceneOptimization));
  100076. BABYLON.TextureOptimization = TextureOptimization;
  100077. /**
  100078. * Defines an optimization used to increase or decrease the rendering resolution
  100079. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100080. */
  100081. var HardwareScalingOptimization = /** @class */ (function (_super) {
  100082. __extends(HardwareScalingOptimization, _super);
  100083. /**
  100084. * Creates the HardwareScalingOptimization object
  100085. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100086. * @param maximumScale defines the maximum scale to use (2 by default)
  100087. * @param step defines the step to use between two passes (0.5 by default)
  100088. */
  100089. function HardwareScalingOptimization(
  100090. /**
  100091. * Defines the priority of this optimization (0 by default which means first in the list)
  100092. */
  100093. priority,
  100094. /**
  100095. * Defines the maximum scale to use (2 by default)
  100096. */
  100097. maximumScale,
  100098. /**
  100099. * Defines the step to use between two passes (0.5 by default)
  100100. */
  100101. step) {
  100102. if (priority === void 0) { priority = 0; }
  100103. if (maximumScale === void 0) { maximumScale = 2; }
  100104. if (step === void 0) { step = 0.25; }
  100105. var _this = _super.call(this, priority) || this;
  100106. _this.priority = priority;
  100107. _this.maximumScale = maximumScale;
  100108. _this.step = step;
  100109. _this._currentScale = -1;
  100110. _this._directionOffset = 1;
  100111. return _this;
  100112. }
  100113. /**
  100114. * Gets a string describing the action executed by the current optimization
  100115. * @return description string
  100116. */
  100117. HardwareScalingOptimization.prototype.getDescription = function () {
  100118. return "Setting hardware scaling level to " + this._currentScale;
  100119. };
  100120. /**
  100121. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100122. * @param scene defines the current scene where to apply this optimization
  100123. * @param optimizer defines the current optimizer
  100124. * @returns true if everything that can be done was applied
  100125. */
  100126. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  100127. if (this._currentScale === -1) {
  100128. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  100129. if (this._currentScale > this.maximumScale) {
  100130. this._directionOffset = -1;
  100131. }
  100132. }
  100133. this._currentScale += this._directionOffset * this.step;
  100134. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  100135. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  100136. };
  100137. ;
  100138. return HardwareScalingOptimization;
  100139. }(SceneOptimization));
  100140. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  100141. /**
  100142. * Defines an optimization used to remove shadows
  100143. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100144. */
  100145. var ShadowsOptimization = /** @class */ (function (_super) {
  100146. __extends(ShadowsOptimization, _super);
  100147. function ShadowsOptimization() {
  100148. return _super !== null && _super.apply(this, arguments) || this;
  100149. }
  100150. /**
  100151. * Gets a string describing the action executed by the current optimization
  100152. * @return description string
  100153. */
  100154. ShadowsOptimization.prototype.getDescription = function () {
  100155. return "Turning shadows on/off";
  100156. };
  100157. /**
  100158. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100159. * @param scene defines the current scene where to apply this optimization
  100160. * @param optimizer defines the current optimizer
  100161. * @returns true if everything that can be done was applied
  100162. */
  100163. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  100164. scene.shadowsEnabled = optimizer.isInImprovementMode;
  100165. return true;
  100166. };
  100167. ;
  100168. return ShadowsOptimization;
  100169. }(SceneOptimization));
  100170. BABYLON.ShadowsOptimization = ShadowsOptimization;
  100171. /**
  100172. * Defines an optimization used to turn post-processes off
  100173. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100174. */
  100175. var PostProcessesOptimization = /** @class */ (function (_super) {
  100176. __extends(PostProcessesOptimization, _super);
  100177. function PostProcessesOptimization() {
  100178. return _super !== null && _super.apply(this, arguments) || this;
  100179. }
  100180. /**
  100181. * Gets a string describing the action executed by the current optimization
  100182. * @return description string
  100183. */
  100184. PostProcessesOptimization.prototype.getDescription = function () {
  100185. return "Turning post-processes on/off";
  100186. };
  100187. /**
  100188. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100189. * @param scene defines the current scene where to apply this optimization
  100190. * @param optimizer defines the current optimizer
  100191. * @returns true if everything that can be done was applied
  100192. */
  100193. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  100194. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  100195. return true;
  100196. };
  100197. ;
  100198. return PostProcessesOptimization;
  100199. }(SceneOptimization));
  100200. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  100201. /**
  100202. * Defines an optimization used to turn lens flares off
  100203. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100204. */
  100205. var LensFlaresOptimization = /** @class */ (function (_super) {
  100206. __extends(LensFlaresOptimization, _super);
  100207. function LensFlaresOptimization() {
  100208. return _super !== null && _super.apply(this, arguments) || this;
  100209. }
  100210. /**
  100211. * Gets a string describing the action executed by the current optimization
  100212. * @return description string
  100213. */
  100214. LensFlaresOptimization.prototype.getDescription = function () {
  100215. return "Turning lens flares on/off";
  100216. };
  100217. /**
  100218. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100219. * @param scene defines the current scene where to apply this optimization
  100220. * @param optimizer defines the current optimizer
  100221. * @returns true if everything that can be done was applied
  100222. */
  100223. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  100224. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  100225. return true;
  100226. };
  100227. ;
  100228. return LensFlaresOptimization;
  100229. }(SceneOptimization));
  100230. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  100231. /**
  100232. * Defines an optimization based on user defined callback.
  100233. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100234. */
  100235. var CustomOptimization = /** @class */ (function (_super) {
  100236. __extends(CustomOptimization, _super);
  100237. function CustomOptimization() {
  100238. return _super !== null && _super.apply(this, arguments) || this;
  100239. }
  100240. /**
  100241. * Gets a string describing the action executed by the current optimization
  100242. * @returns description string
  100243. */
  100244. CustomOptimization.prototype.getDescription = function () {
  100245. if (this.onGetDescription) {
  100246. return this.onGetDescription();
  100247. }
  100248. return "Running user defined callback";
  100249. };
  100250. /**
  100251. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100252. * @param scene defines the current scene where to apply this optimization
  100253. * @param optimizer defines the current optimizer
  100254. * @returns true if everything that can be done was applied
  100255. */
  100256. CustomOptimization.prototype.apply = function (scene, optimizer) {
  100257. if (this.onApply) {
  100258. return this.onApply(scene, optimizer);
  100259. }
  100260. return true;
  100261. };
  100262. ;
  100263. return CustomOptimization;
  100264. }(SceneOptimization));
  100265. BABYLON.CustomOptimization = CustomOptimization;
  100266. /**
  100267. * Defines an optimization used to turn particles off
  100268. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100269. */
  100270. var ParticlesOptimization = /** @class */ (function (_super) {
  100271. __extends(ParticlesOptimization, _super);
  100272. function ParticlesOptimization() {
  100273. return _super !== null && _super.apply(this, arguments) || this;
  100274. }
  100275. /**
  100276. * Gets a string describing the action executed by the current optimization
  100277. * @return description string
  100278. */
  100279. ParticlesOptimization.prototype.getDescription = function () {
  100280. return "Turning particles on/off";
  100281. };
  100282. /**
  100283. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100284. * @param scene defines the current scene where to apply this optimization
  100285. * @param optimizer defines the current optimizer
  100286. * @returns true if everything that can be done was applied
  100287. */
  100288. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  100289. scene.particlesEnabled = optimizer.isInImprovementMode;
  100290. return true;
  100291. };
  100292. ;
  100293. return ParticlesOptimization;
  100294. }(SceneOptimization));
  100295. BABYLON.ParticlesOptimization = ParticlesOptimization;
  100296. /**
  100297. * Defines an optimization used to turn render targets off
  100298. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100299. */
  100300. var RenderTargetsOptimization = /** @class */ (function (_super) {
  100301. __extends(RenderTargetsOptimization, _super);
  100302. function RenderTargetsOptimization() {
  100303. return _super !== null && _super.apply(this, arguments) || this;
  100304. }
  100305. /**
  100306. * Gets a string describing the action executed by the current optimization
  100307. * @return description string
  100308. */
  100309. RenderTargetsOptimization.prototype.getDescription = function () {
  100310. return "Turning render targets off";
  100311. };
  100312. /**
  100313. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100314. * @param scene defines the current scene where to apply this optimization
  100315. * @param optimizer defines the current optimizer
  100316. * @returns true if everything that can be done was applied
  100317. */
  100318. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  100319. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  100320. return true;
  100321. };
  100322. ;
  100323. return RenderTargetsOptimization;
  100324. }(SceneOptimization));
  100325. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  100326. /**
  100327. * Defines an optimization used to merge meshes with compatible materials
  100328. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100329. */
  100330. var MergeMeshesOptimization = /** @class */ (function (_super) {
  100331. __extends(MergeMeshesOptimization, _super);
  100332. function MergeMeshesOptimization() {
  100333. var _this = _super !== null && _super.apply(this, arguments) || this;
  100334. _this._canBeMerged = function (abstractMesh) {
  100335. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  100336. return false;
  100337. }
  100338. var mesh = abstractMesh;
  100339. if (mesh.isDisposed()) {
  100340. return false;
  100341. }
  100342. if (!mesh.isVisible || !mesh.isEnabled()) {
  100343. return false;
  100344. }
  100345. if (mesh.instances.length > 0) {
  100346. return false;
  100347. }
  100348. if (mesh.skeleton || mesh.hasLODLevels) {
  100349. return false;
  100350. }
  100351. return true;
  100352. };
  100353. return _this;
  100354. }
  100355. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  100356. /**
  100357. * Gets or sets a boolean which defines if optimization octree has to be updated
  100358. */
  100359. get: function () {
  100360. return MergeMeshesOptimization._UpdateSelectionTree;
  100361. },
  100362. /**
  100363. * Gets or sets a boolean which defines if optimization octree has to be updated
  100364. */
  100365. set: function (value) {
  100366. MergeMeshesOptimization._UpdateSelectionTree = value;
  100367. },
  100368. enumerable: true,
  100369. configurable: true
  100370. });
  100371. /**
  100372. * Gets a string describing the action executed by the current optimization
  100373. * @return description string
  100374. */
  100375. MergeMeshesOptimization.prototype.getDescription = function () {
  100376. return "Merging similar meshes together";
  100377. };
  100378. /**
  100379. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100380. * @param scene defines the current scene where to apply this optimization
  100381. * @param optimizer defines the current optimizer
  100382. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  100383. * @returns true if everything that can be done was applied
  100384. */
  100385. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  100386. var globalPool = scene.meshes.slice(0);
  100387. var globalLength = globalPool.length;
  100388. for (var index = 0; index < globalLength; index++) {
  100389. var currentPool = new Array();
  100390. var current = globalPool[index];
  100391. // Checks
  100392. if (!this._canBeMerged(current)) {
  100393. continue;
  100394. }
  100395. currentPool.push(current);
  100396. // Find compatible meshes
  100397. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  100398. var otherMesh = globalPool[subIndex];
  100399. if (!this._canBeMerged(otherMesh)) {
  100400. continue;
  100401. }
  100402. if (otherMesh.material !== current.material) {
  100403. continue;
  100404. }
  100405. if (otherMesh.checkCollisions !== current.checkCollisions) {
  100406. continue;
  100407. }
  100408. currentPool.push(otherMesh);
  100409. globalLength--;
  100410. globalPool.splice(subIndex, 1);
  100411. subIndex--;
  100412. }
  100413. if (currentPool.length < 2) {
  100414. continue;
  100415. }
  100416. // Merge meshes
  100417. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  100418. }
  100419. // Call the octree system optimization if it is defined.
  100420. var sceneAsAny = scene;
  100421. if (sceneAsAny.createOrUpdateSelectionOctree) {
  100422. if (updateSelectionTree != undefined) {
  100423. if (updateSelectionTree) {
  100424. sceneAsAny.createOrUpdateSelectionOctree();
  100425. }
  100426. }
  100427. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  100428. sceneAsAny.createOrUpdateSelectionOctree();
  100429. }
  100430. }
  100431. return true;
  100432. };
  100433. ;
  100434. MergeMeshesOptimization._UpdateSelectionTree = false;
  100435. return MergeMeshesOptimization;
  100436. }(SceneOptimization));
  100437. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  100438. /**
  100439. * Defines a list of options used by SceneOptimizer
  100440. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100441. */
  100442. var SceneOptimizerOptions = /** @class */ (function () {
  100443. /**
  100444. * Creates a new list of options used by SceneOptimizer
  100445. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  100446. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  100447. */
  100448. function SceneOptimizerOptions(
  100449. /**
  100450. * Defines the target frame rate to reach (60 by default)
  100451. */
  100452. targetFrameRate,
  100453. /**
  100454. * Defines the interval between two checkes (2000ms by default)
  100455. */
  100456. trackerDuration) {
  100457. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  100458. if (trackerDuration === void 0) { trackerDuration = 2000; }
  100459. this.targetFrameRate = targetFrameRate;
  100460. this.trackerDuration = trackerDuration;
  100461. /**
  100462. * Gets the list of optimizations to apply
  100463. */
  100464. this.optimizations = new Array();
  100465. }
  100466. /**
  100467. * Add a new optimization
  100468. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  100469. * @returns the current SceneOptimizerOptions
  100470. */
  100471. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  100472. this.optimizations.push(optimization);
  100473. return this;
  100474. };
  100475. /**
  100476. * Add a new custom optimization
  100477. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  100478. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  100479. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100480. * @returns the current SceneOptimizerOptions
  100481. */
  100482. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  100483. if (priority === void 0) { priority = 0; }
  100484. var optimization = new CustomOptimization(priority);
  100485. optimization.onApply = onApply;
  100486. optimization.onGetDescription = onGetDescription;
  100487. this.optimizations.push(optimization);
  100488. return this;
  100489. };
  100490. /**
  100491. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  100492. * @param targetFrameRate defines the target frame rate (60 by default)
  100493. * @returns a SceneOptimizerOptions object
  100494. */
  100495. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  100496. var result = new SceneOptimizerOptions(targetFrameRate);
  100497. var priority = 0;
  100498. result.addOptimization(new MergeMeshesOptimization(priority));
  100499. result.addOptimization(new ShadowsOptimization(priority));
  100500. result.addOptimization(new LensFlaresOptimization(priority));
  100501. // Next priority
  100502. priority++;
  100503. result.addOptimization(new PostProcessesOptimization(priority));
  100504. result.addOptimization(new ParticlesOptimization(priority));
  100505. // Next priority
  100506. priority++;
  100507. result.addOptimization(new TextureOptimization(priority, 1024));
  100508. return result;
  100509. };
  100510. /**
  100511. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  100512. * @param targetFrameRate defines the target frame rate (60 by default)
  100513. * @returns a SceneOptimizerOptions object
  100514. */
  100515. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  100516. var result = new SceneOptimizerOptions(targetFrameRate);
  100517. var priority = 0;
  100518. result.addOptimization(new MergeMeshesOptimization(priority));
  100519. result.addOptimization(new ShadowsOptimization(priority));
  100520. result.addOptimization(new LensFlaresOptimization(priority));
  100521. // Next priority
  100522. priority++;
  100523. result.addOptimization(new PostProcessesOptimization(priority));
  100524. result.addOptimization(new ParticlesOptimization(priority));
  100525. // Next priority
  100526. priority++;
  100527. result.addOptimization(new TextureOptimization(priority, 512));
  100528. // Next priority
  100529. priority++;
  100530. result.addOptimization(new RenderTargetsOptimization(priority));
  100531. // Next priority
  100532. priority++;
  100533. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  100534. return result;
  100535. };
  100536. /**
  100537. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  100538. * @param targetFrameRate defines the target frame rate (60 by default)
  100539. * @returns a SceneOptimizerOptions object
  100540. */
  100541. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  100542. var result = new SceneOptimizerOptions(targetFrameRate);
  100543. var priority = 0;
  100544. result.addOptimization(new MergeMeshesOptimization(priority));
  100545. result.addOptimization(new ShadowsOptimization(priority));
  100546. result.addOptimization(new LensFlaresOptimization(priority));
  100547. // Next priority
  100548. priority++;
  100549. result.addOptimization(new PostProcessesOptimization(priority));
  100550. result.addOptimization(new ParticlesOptimization(priority));
  100551. // Next priority
  100552. priority++;
  100553. result.addOptimization(new TextureOptimization(priority, 256));
  100554. // Next priority
  100555. priority++;
  100556. result.addOptimization(new RenderTargetsOptimization(priority));
  100557. // Next priority
  100558. priority++;
  100559. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  100560. return result;
  100561. };
  100562. return SceneOptimizerOptions;
  100563. }());
  100564. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  100565. /**
  100566. * Class used to run optimizations in order to reach a target frame rate
  100567. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100568. */
  100569. var SceneOptimizer = /** @class */ (function () {
  100570. /**
  100571. * Creates a new SceneOptimizer
  100572. * @param scene defines the scene to work on
  100573. * @param options defines the options to use with the SceneOptimizer
  100574. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  100575. * @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)
  100576. */
  100577. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  100578. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  100579. if (improvementMode === void 0) { improvementMode = false; }
  100580. var _this = this;
  100581. this._isRunning = false;
  100582. this._currentPriorityLevel = 0;
  100583. this._targetFrameRate = 60;
  100584. this._trackerDuration = 2000;
  100585. this._currentFrameRate = 0;
  100586. this._improvementMode = false;
  100587. /**
  100588. * Defines an observable called when the optimizer reaches the target frame rate
  100589. */
  100590. this.onSuccessObservable = new BABYLON.Observable();
  100591. /**
  100592. * Defines an observable called when the optimizer enables an optimization
  100593. */
  100594. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  100595. /**
  100596. * Defines an observable called when the optimizer is not able to reach the target frame rate
  100597. */
  100598. this.onFailureObservable = new BABYLON.Observable();
  100599. if (!options) {
  100600. this._options = new SceneOptimizerOptions();
  100601. }
  100602. else {
  100603. this._options = options;
  100604. }
  100605. if (this._options.targetFrameRate) {
  100606. this._targetFrameRate = this._options.targetFrameRate;
  100607. }
  100608. if (this._options.trackerDuration) {
  100609. this._trackerDuration = this._options.trackerDuration;
  100610. }
  100611. if (autoGeneratePriorities) {
  100612. var priority = 0;
  100613. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  100614. var optim = _a[_i];
  100615. optim.priority = priority++;
  100616. }
  100617. }
  100618. this._improvementMode = improvementMode;
  100619. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100620. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  100621. _this._sceneDisposeObserver = null;
  100622. _this.dispose();
  100623. });
  100624. }
  100625. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  100626. /**
  100627. * Gets a boolean indicating if the optimizer is in improvement mode
  100628. */
  100629. get: function () {
  100630. return this._improvementMode;
  100631. },
  100632. enumerable: true,
  100633. configurable: true
  100634. });
  100635. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  100636. /**
  100637. * Gets the current priority level (0 at start)
  100638. */
  100639. get: function () {
  100640. return this._currentPriorityLevel;
  100641. },
  100642. enumerable: true,
  100643. configurable: true
  100644. });
  100645. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  100646. /**
  100647. * Gets the current frame rate checked by the SceneOptimizer
  100648. */
  100649. get: function () {
  100650. return this._currentFrameRate;
  100651. },
  100652. enumerable: true,
  100653. configurable: true
  100654. });
  100655. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  100656. /**
  100657. * Gets or sets the current target frame rate (60 by default)
  100658. */
  100659. get: function () {
  100660. return this._targetFrameRate;
  100661. },
  100662. /**
  100663. * Gets or sets the current target frame rate (60 by default)
  100664. */
  100665. set: function (value) {
  100666. this._targetFrameRate = value;
  100667. },
  100668. enumerable: true,
  100669. configurable: true
  100670. });
  100671. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  100672. /**
  100673. * Gets or sets the current interval between two checks (every 2000ms by default)
  100674. */
  100675. get: function () {
  100676. return this._trackerDuration;
  100677. },
  100678. /**
  100679. * Gets or sets the current interval between two checks (every 2000ms by default)
  100680. */
  100681. set: function (value) {
  100682. this._trackerDuration = value;
  100683. },
  100684. enumerable: true,
  100685. configurable: true
  100686. });
  100687. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  100688. /**
  100689. * Gets the list of active optimizations
  100690. */
  100691. get: function () {
  100692. return this._options.optimizations;
  100693. },
  100694. enumerable: true,
  100695. configurable: true
  100696. });
  100697. /**
  100698. * Stops the current optimizer
  100699. */
  100700. SceneOptimizer.prototype.stop = function () {
  100701. this._isRunning = false;
  100702. };
  100703. /**
  100704. * Reset the optimizer to initial step (current priority level = 0)
  100705. */
  100706. SceneOptimizer.prototype.reset = function () {
  100707. this._currentPriorityLevel = 0;
  100708. };
  100709. /**
  100710. * Start the optimizer. By default it will try to reach a specific framerate
  100711. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  100712. */
  100713. SceneOptimizer.prototype.start = function () {
  100714. var _this = this;
  100715. if (this._isRunning) {
  100716. return;
  100717. }
  100718. this._isRunning = true;
  100719. // Let's wait for the scene to be ready before running our check
  100720. this._scene.executeWhenReady(function () {
  100721. setTimeout(function () {
  100722. _this._checkCurrentState();
  100723. }, _this._trackerDuration);
  100724. });
  100725. };
  100726. SceneOptimizer.prototype._checkCurrentState = function () {
  100727. var _this = this;
  100728. if (!this._isRunning) {
  100729. return;
  100730. }
  100731. var scene = this._scene;
  100732. var options = this._options;
  100733. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  100734. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  100735. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  100736. this._isRunning = false;
  100737. this.onSuccessObservable.notifyObservers(this);
  100738. return;
  100739. }
  100740. // Apply current level of optimizations
  100741. var allDone = true;
  100742. var noOptimizationApplied = true;
  100743. for (var index = 0; index < options.optimizations.length; index++) {
  100744. var optimization = options.optimizations[index];
  100745. if (optimization.priority === this._currentPriorityLevel) {
  100746. noOptimizationApplied = false;
  100747. allDone = allDone && optimization.apply(scene, this);
  100748. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  100749. }
  100750. }
  100751. // If no optimization was applied, this is a failure :(
  100752. if (noOptimizationApplied) {
  100753. this._isRunning = false;
  100754. this.onFailureObservable.notifyObservers(this);
  100755. return;
  100756. }
  100757. // If all optimizations were done, move to next level
  100758. if (allDone) {
  100759. this._currentPriorityLevel++;
  100760. }
  100761. // Let's the system running for a specific amount of time before checking FPS
  100762. scene.executeWhenReady(function () {
  100763. setTimeout(function () {
  100764. _this._checkCurrentState();
  100765. }, _this._trackerDuration);
  100766. });
  100767. };
  100768. /**
  100769. * Release all resources
  100770. */
  100771. SceneOptimizer.prototype.dispose = function () {
  100772. this.stop();
  100773. this.onSuccessObservable.clear();
  100774. this.onFailureObservable.clear();
  100775. this.onNewOptimizationAppliedObservable.clear();
  100776. if (this._sceneDisposeObserver) {
  100777. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100778. }
  100779. };
  100780. /**
  100781. * Helper function to create a SceneOptimizer with one single line of code
  100782. * @param scene defines the scene to work on
  100783. * @param options defines the options to use with the SceneOptimizer
  100784. * @param onSuccess defines a callback to call on success
  100785. * @param onFailure defines a callback to call on failure
  100786. * @returns the new SceneOptimizer object
  100787. */
  100788. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  100789. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  100790. if (onSuccess) {
  100791. optimizer.onSuccessObservable.add(function () {
  100792. onSuccess();
  100793. });
  100794. }
  100795. if (onFailure) {
  100796. optimizer.onFailureObservable.add(function () {
  100797. onFailure();
  100798. });
  100799. }
  100800. optimizer.start();
  100801. return optimizer;
  100802. };
  100803. return SceneOptimizer;
  100804. }());
  100805. BABYLON.SceneOptimizer = SceneOptimizer;
  100806. })(BABYLON || (BABYLON = {}));
  100807. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  100808. var BABYLON;
  100809. (function (BABYLON) {
  100810. /**
  100811. * Gets the outline renderer associated with the scene
  100812. * @returns a OutlineRenderer
  100813. */
  100814. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  100815. if (!this._outlineRenderer) {
  100816. this._outlineRenderer = new OutlineRenderer(this);
  100817. }
  100818. return this._outlineRenderer;
  100819. };
  100820. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  100821. get: function () {
  100822. return this._renderOutline;
  100823. },
  100824. set: function (value) {
  100825. if (value) {
  100826. // Lazy Load the component.
  100827. this.getScene().getOutlineRenderer();
  100828. }
  100829. this._renderOutline = value;
  100830. },
  100831. enumerable: true,
  100832. configurable: true
  100833. });
  100834. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  100835. get: function () {
  100836. return this._renderOverlay;
  100837. },
  100838. set: function (value) {
  100839. if (value) {
  100840. // Lazy Load the component.
  100841. this.getScene().getOutlineRenderer();
  100842. }
  100843. this._renderOverlay = value;
  100844. },
  100845. enumerable: true,
  100846. configurable: true
  100847. });
  100848. /**
  100849. * This class is responsible to draw bothe outline/overlay of meshes.
  100850. * It should not be used directly but through the available method on mesh.
  100851. */
  100852. var OutlineRenderer = /** @class */ (function () {
  100853. /**
  100854. * Instantiates a new outline renderer. (There could be only one per scene).
  100855. * @param scene Defines the scene it belongs to
  100856. */
  100857. function OutlineRenderer(scene) {
  100858. /**
  100859. * The name of the component. Each component must have a unique name.
  100860. */
  100861. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  100862. /**
  100863. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  100864. */
  100865. this.zOffset = 1;
  100866. this.scene = scene;
  100867. this._engine = scene.getEngine();
  100868. this.scene._addComponent(this);
  100869. }
  100870. /**
  100871. * Register the component to one instance of a scene.
  100872. */
  100873. OutlineRenderer.prototype.register = function () {
  100874. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  100875. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  100876. };
  100877. /**
  100878. * Rebuilds the elements related to this component in case of
  100879. * context lost for instance.
  100880. */
  100881. OutlineRenderer.prototype.rebuild = function () {
  100882. // Nothing to do here.
  100883. };
  100884. /**
  100885. * Disposes the component and the associated ressources.
  100886. */
  100887. OutlineRenderer.prototype.dispose = function () {
  100888. // Nothing to do here.
  100889. };
  100890. /**
  100891. * Renders the outline in the canvas.
  100892. * @param subMesh Defines the sumesh to render
  100893. * @param batch Defines the batch of meshes in case of instances
  100894. * @param useOverlay Defines if the rendering is for the overlay or the outline
  100895. */
  100896. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  100897. var _this = this;
  100898. if (useOverlay === void 0) { useOverlay = false; }
  100899. var scene = this.scene;
  100900. var engine = scene.getEngine();
  100901. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100902. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  100903. return;
  100904. }
  100905. var mesh = subMesh.getRenderingMesh();
  100906. var material = subMesh.getMaterial();
  100907. if (!material || !scene.activeCamera) {
  100908. return;
  100909. }
  100910. engine.enableEffect(this._effect);
  100911. // Logarithmic depth
  100912. if (material.useLogarithmicDepth) {
  100913. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  100914. }
  100915. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  100916. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  100917. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  100918. // Bones
  100919. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100920. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100921. }
  100922. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  100923. // Alpha test
  100924. if (material && material.needAlphaTesting()) {
  100925. var alphaTexture = material.getAlphaTestTexture();
  100926. if (alphaTexture) {
  100927. this._effect.setTexture("diffuseSampler", alphaTexture);
  100928. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  100929. }
  100930. }
  100931. engine.setZOffset(-this.zOffset);
  100932. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  100933. engine.setZOffset(0);
  100934. };
  100935. /**
  100936. * Returns whether or not the outline renderer is ready for a given submesh.
  100937. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  100938. * @param subMesh Defines the submesh to check readyness for
  100939. * @param useInstances Defines wheter wee are trying to render instances or not
  100940. * @returns true if ready otherwise false
  100941. */
  100942. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  100943. var defines = [];
  100944. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  100945. var mesh = subMesh.getMesh();
  100946. var material = subMesh.getMaterial();
  100947. if (material) {
  100948. // Alpha test
  100949. if (material.needAlphaTesting()) {
  100950. defines.push("#define ALPHATEST");
  100951. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100952. attribs.push(BABYLON.VertexBuffer.UVKind);
  100953. defines.push("#define UV1");
  100954. }
  100955. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  100956. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100957. defines.push("#define UV2");
  100958. }
  100959. }
  100960. //Logarithmic depth
  100961. if (material.useLogarithmicDepth) {
  100962. defines.push("#define LOGARITHMICDEPTH");
  100963. }
  100964. }
  100965. // Bones
  100966. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100969. if (mesh.numBoneInfluencers > 4) {
  100970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100972. }
  100973. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100974. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  100975. }
  100976. else {
  100977. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100978. }
  100979. // Instances
  100980. if (useInstances) {
  100981. defines.push("#define INSTANCES");
  100982. attribs.push("world0");
  100983. attribs.push("world1");
  100984. attribs.push("world2");
  100985. attribs.push("world3");
  100986. }
  100987. // Get correct effect
  100988. var join = defines.join("\n");
  100989. if (this._cachedDefines !== join) {
  100990. this._cachedDefines = join;
  100991. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  100992. }
  100993. return this._effect.isReady();
  100994. };
  100995. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  100996. // Outline - step 1
  100997. this._savedDepthWrite = this._engine.getDepthWrite();
  100998. if (mesh.renderOutline) {
  100999. this._engine.setDepthWrite(false);
  101000. this.render(subMesh, batch);
  101001. this._engine.setDepthWrite(this._savedDepthWrite);
  101002. }
  101003. };
  101004. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  101005. // Outline - step 2
  101006. if (mesh.renderOutline && this._savedDepthWrite) {
  101007. this._engine.setDepthWrite(true);
  101008. this._engine.setColorWrite(false);
  101009. this.render(subMesh, batch);
  101010. this._engine.setColorWrite(true);
  101011. }
  101012. // Overlay
  101013. if (mesh.renderOverlay) {
  101014. var currentMode = this._engine.getAlphaMode();
  101015. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101016. this.render(subMesh, batch, true);
  101017. this._engine.setAlphaMode(currentMode);
  101018. }
  101019. };
  101020. return OutlineRenderer;
  101021. }());
  101022. BABYLON.OutlineRenderer = OutlineRenderer;
  101023. })(BABYLON || (BABYLON = {}));
  101024. //# sourceMappingURL=babylon.outlineRenderer.js.map
  101025. var BABYLON;
  101026. (function (BABYLON) {
  101027. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  101028. if (this._edgesRenderer) {
  101029. this._edgesRenderer.dispose();
  101030. this._edgesRenderer = null;
  101031. }
  101032. return this;
  101033. };
  101034. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101035. if (epsilon === void 0) { epsilon = 0.95; }
  101036. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101037. this.disableEdgesRendering();
  101038. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101039. return this;
  101040. };
  101041. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  101042. get: function () {
  101043. return this._edgesRenderer;
  101044. },
  101045. enumerable: true,
  101046. configurable: true
  101047. });
  101048. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101049. if (epsilon === void 0) { epsilon = 0.95; }
  101050. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101051. this.disableEdgesRendering();
  101052. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101053. return this;
  101054. };
  101055. /**
  101056. * FaceAdjacencies Helper class to generate edges
  101057. */
  101058. var FaceAdjacencies = /** @class */ (function () {
  101059. function FaceAdjacencies() {
  101060. this.edges = new Array();
  101061. this.edgesConnectedCount = 0;
  101062. }
  101063. return FaceAdjacencies;
  101064. }());
  101065. /**
  101066. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  101067. */
  101068. var EdgesRenderer = /** @class */ (function () {
  101069. /**
  101070. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  101071. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  101072. * @param source Mesh used to create edges
  101073. * @param epsilon sum of angles in adjacency to check for edge
  101074. * @param checkVerticesInsteadOfIndices
  101075. * @param generateEdgesLines - should generate Lines or only prepare resources.
  101076. */
  101077. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  101078. if (epsilon === void 0) { epsilon = 0.95; }
  101079. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101080. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  101081. var _this = this;
  101082. this.edgesWidthScalerForOrthographic = 1000.0;
  101083. this.edgesWidthScalerForPerspective = 50.0;
  101084. this._linesPositions = new Array();
  101085. this._linesNormals = new Array();
  101086. this._linesIndices = new Array();
  101087. this._buffers = {};
  101088. this._checkVerticesInsteadOfIndices = false;
  101089. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  101090. this.isEnabled = true;
  101091. this._source = source;
  101092. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  101093. this._epsilon = epsilon;
  101094. this._prepareRessources();
  101095. if (generateEdgesLines) {
  101096. this._generateEdgesLines();
  101097. }
  101098. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  101099. _this._rebuild();
  101100. });
  101101. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  101102. _this.dispose();
  101103. });
  101104. }
  101105. EdgesRenderer.prototype._prepareRessources = function () {
  101106. if (this._lineShader) {
  101107. return;
  101108. }
  101109. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  101110. attributes: ["position", "normal"],
  101111. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  101112. });
  101113. this._lineShader.disableDepthWrite = true;
  101114. this._lineShader.backFaceCulling = false;
  101115. };
  101116. /** @hidden */
  101117. EdgesRenderer.prototype._rebuild = function () {
  101118. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101119. if (buffer) {
  101120. buffer._rebuild();
  101121. }
  101122. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101123. if (buffer) {
  101124. buffer._rebuild();
  101125. }
  101126. var scene = this._source.getScene();
  101127. var engine = scene.getEngine();
  101128. this._ib = engine.createIndexBuffer(this._linesIndices);
  101129. };
  101130. /**
  101131. * Releases the required resources for the edges renderer
  101132. */
  101133. EdgesRenderer.prototype.dispose = function () {
  101134. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  101135. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  101136. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101137. if (buffer) {
  101138. buffer.dispose();
  101139. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  101140. }
  101141. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101142. if (buffer) {
  101143. buffer.dispose();
  101144. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  101145. }
  101146. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  101147. this._lineShader.dispose();
  101148. };
  101149. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  101150. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  101151. return 0;
  101152. }
  101153. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  101154. return 1;
  101155. }
  101156. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  101157. return 2;
  101158. }
  101159. return -1;
  101160. };
  101161. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  101162. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  101163. return 0;
  101164. }
  101165. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  101166. return 1;
  101167. }
  101168. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  101169. return 2;
  101170. }
  101171. return -1;
  101172. };
  101173. /**
  101174. * Checks if the pair of p0 and p1 is en edge
  101175. * @param faceIndex
  101176. * @param edge
  101177. * @param faceNormals
  101178. * @param p0
  101179. * @param p1
  101180. * @private
  101181. */
  101182. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101183. var needToCreateLine;
  101184. if (edge === undefined) {
  101185. needToCreateLine = true;
  101186. }
  101187. else {
  101188. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  101189. needToCreateLine = dotProduct < this._epsilon;
  101190. }
  101191. if (needToCreateLine) {
  101192. var offset = this._linesPositions.length / 3;
  101193. var normal = p0.subtract(p1);
  101194. normal.normalize();
  101195. // Positions
  101196. this._linesPositions.push(p0.x);
  101197. this._linesPositions.push(p0.y);
  101198. this._linesPositions.push(p0.z);
  101199. this._linesPositions.push(p0.x);
  101200. this._linesPositions.push(p0.y);
  101201. this._linesPositions.push(p0.z);
  101202. this._linesPositions.push(p1.x);
  101203. this._linesPositions.push(p1.y);
  101204. this._linesPositions.push(p1.z);
  101205. this._linesPositions.push(p1.x);
  101206. this._linesPositions.push(p1.y);
  101207. this._linesPositions.push(p1.z);
  101208. // Normals
  101209. this._linesNormals.push(p1.x);
  101210. this._linesNormals.push(p1.y);
  101211. this._linesNormals.push(p1.z);
  101212. this._linesNormals.push(-1);
  101213. this._linesNormals.push(p1.x);
  101214. this._linesNormals.push(p1.y);
  101215. this._linesNormals.push(p1.z);
  101216. this._linesNormals.push(1);
  101217. this._linesNormals.push(p0.x);
  101218. this._linesNormals.push(p0.y);
  101219. this._linesNormals.push(p0.z);
  101220. this._linesNormals.push(-1);
  101221. this._linesNormals.push(p0.x);
  101222. this._linesNormals.push(p0.y);
  101223. this._linesNormals.push(p0.z);
  101224. this._linesNormals.push(1);
  101225. // Indices
  101226. this._linesIndices.push(offset);
  101227. this._linesIndices.push(offset + 1);
  101228. this._linesIndices.push(offset + 2);
  101229. this._linesIndices.push(offset);
  101230. this._linesIndices.push(offset + 2);
  101231. this._linesIndices.push(offset + 3);
  101232. }
  101233. };
  101234. /**
  101235. * Generates lines edges from adjacencjes
  101236. * @private
  101237. */
  101238. EdgesRenderer.prototype._generateEdgesLines = function () {
  101239. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101240. var indices = this._source.getIndices();
  101241. if (!indices || !positions) {
  101242. return;
  101243. }
  101244. // First let's find adjacencies
  101245. var adjacencies = new Array();
  101246. var faceNormals = new Array();
  101247. var index;
  101248. var faceAdjacencies;
  101249. // Prepare faces
  101250. for (index = 0; index < indices.length; index += 3) {
  101251. faceAdjacencies = new FaceAdjacencies();
  101252. var p0Index = indices[index];
  101253. var p1Index = indices[index + 1];
  101254. var p2Index = indices[index + 2];
  101255. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  101256. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  101257. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  101258. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  101259. faceNormal.normalize();
  101260. faceNormals.push(faceNormal);
  101261. adjacencies.push(faceAdjacencies);
  101262. }
  101263. // Scan
  101264. for (index = 0; index < adjacencies.length; index++) {
  101265. faceAdjacencies = adjacencies[index];
  101266. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  101267. var otherFaceAdjacencies = adjacencies[otherIndex];
  101268. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  101269. break;
  101270. }
  101271. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  101272. continue;
  101273. }
  101274. var otherP0 = indices[otherIndex * 3];
  101275. var otherP1 = indices[otherIndex * 3 + 1];
  101276. var otherP2 = indices[otherIndex * 3 + 2];
  101277. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  101278. var otherEdgeIndex = 0;
  101279. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  101280. continue;
  101281. }
  101282. switch (edgeIndex) {
  101283. case 0:
  101284. if (this._checkVerticesInsteadOfIndices) {
  101285. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101286. }
  101287. else {
  101288. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  101289. }
  101290. break;
  101291. case 1:
  101292. if (this._checkVerticesInsteadOfIndices) {
  101293. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101294. }
  101295. else {
  101296. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  101297. }
  101298. break;
  101299. case 2:
  101300. if (this._checkVerticesInsteadOfIndices) {
  101301. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101302. }
  101303. else {
  101304. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  101305. }
  101306. break;
  101307. }
  101308. if (otherEdgeIndex === -1) {
  101309. continue;
  101310. }
  101311. faceAdjacencies.edges[edgeIndex] = otherIndex;
  101312. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  101313. faceAdjacencies.edgesConnectedCount++;
  101314. otherFaceAdjacencies.edgesConnectedCount++;
  101315. if (faceAdjacencies.edgesConnectedCount === 3) {
  101316. break;
  101317. }
  101318. }
  101319. }
  101320. }
  101321. // Create lines
  101322. for (index = 0; index < adjacencies.length; index++) {
  101323. // 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
  101324. var current = adjacencies[index];
  101325. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101326. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  101327. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  101328. }
  101329. // Merge into a single mesh
  101330. var engine = this._source.getScene().getEngine();
  101331. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101332. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101333. this._ib = engine.createIndexBuffer(this._linesIndices);
  101334. this._indicesCount = this._linesIndices.length;
  101335. };
  101336. /**
  101337. * Checks wether or not the edges renderer is ready to render.
  101338. * @return true if ready, otherwise false.
  101339. */
  101340. EdgesRenderer.prototype.isReady = function () {
  101341. return this._lineShader.isReady();
  101342. };
  101343. /**
  101344. * Renders the edges of the attached mesh,
  101345. */
  101346. EdgesRenderer.prototype.render = function () {
  101347. var scene = this._source.getScene();
  101348. if (!this.isReady() || !scene.activeCamera) {
  101349. return;
  101350. }
  101351. var engine = scene.getEngine();
  101352. this._lineShader._preBind();
  101353. if (this._source.edgesColor.a !== 1) {
  101354. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101355. }
  101356. else {
  101357. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  101358. }
  101359. // VBOs
  101360. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  101361. scene.resetCachedMaterial();
  101362. this._lineShader.setColor4("color", this._source.edgesColor);
  101363. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  101364. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  101365. }
  101366. else {
  101367. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  101368. }
  101369. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  101370. this._lineShader.bind(this._source.getWorldMatrix());
  101371. // Draw order
  101372. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  101373. this._lineShader.unbind();
  101374. };
  101375. return EdgesRenderer;
  101376. }());
  101377. BABYLON.EdgesRenderer = EdgesRenderer;
  101378. })(BABYLON || (BABYLON = {}));
  101379. //# sourceMappingURL=babylon.edgesRenderer.js.map
  101380. var BABYLON;
  101381. (function (BABYLON) {
  101382. /**
  101383. * FaceAdjacencies Helper class to generate edges
  101384. */
  101385. var FaceAdjacencies = /** @class */ (function () {
  101386. function FaceAdjacencies() {
  101387. this.edges = new Array();
  101388. this.edgesConnectedCount = 0;
  101389. }
  101390. return FaceAdjacencies;
  101391. }());
  101392. /**
  101393. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  101394. */
  101395. var LineEdgesRenderer = /** @class */ (function (_super) {
  101396. __extends(LineEdgesRenderer, _super);
  101397. /**
  101398. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  101399. * @param source LineMesh used to generate edges
  101400. * @param epsilon not important (specified angle for edge detection)
  101401. * @param checkVerticesInsteadOfIndices not important for LineMesh
  101402. */
  101403. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  101404. if (epsilon === void 0) { epsilon = 0.95; }
  101405. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101406. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  101407. _this._generateEdgesLines();
  101408. return _this;
  101409. }
  101410. /**
  101411. * Always create the edge since its a line so only important things are p0 and p1
  101412. * @param faceIndex not important for LineMesh
  101413. * @param edge not important for LineMesh
  101414. * @param faceNormals not important for LineMesh
  101415. * @param p0 beginnig of line
  101416. * @param p1 end of line
  101417. */
  101418. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101419. var offset = this._linesPositions.length / 3;
  101420. var normal = p0.subtract(p1);
  101421. normal.normalize();
  101422. // Positions
  101423. this._linesPositions.push(p0.x);
  101424. this._linesPositions.push(p0.y);
  101425. this._linesPositions.push(p0.z);
  101426. this._linesPositions.push(p0.x);
  101427. this._linesPositions.push(p0.y);
  101428. this._linesPositions.push(p0.z);
  101429. this._linesPositions.push(p1.x);
  101430. this._linesPositions.push(p1.y);
  101431. this._linesPositions.push(p1.z);
  101432. this._linesPositions.push(p1.x);
  101433. this._linesPositions.push(p1.y);
  101434. this._linesPositions.push(p1.z);
  101435. // Normals
  101436. this._linesNormals.push(p1.x);
  101437. this._linesNormals.push(p1.y);
  101438. this._linesNormals.push(p1.z);
  101439. this._linesNormals.push(-1);
  101440. this._linesNormals.push(p1.x);
  101441. this._linesNormals.push(p1.y);
  101442. this._linesNormals.push(p1.z);
  101443. this._linesNormals.push(1);
  101444. this._linesNormals.push(p0.x);
  101445. this._linesNormals.push(p0.y);
  101446. this._linesNormals.push(p0.z);
  101447. this._linesNormals.push(-1);
  101448. this._linesNormals.push(p0.x);
  101449. this._linesNormals.push(p0.y);
  101450. this._linesNormals.push(p0.z);
  101451. this._linesNormals.push(1);
  101452. // Indices
  101453. this._linesIndices.push(offset);
  101454. this._linesIndices.push(offset + 1);
  101455. this._linesIndices.push(offset + 2);
  101456. this._linesIndices.push(offset);
  101457. this._linesIndices.push(offset + 2);
  101458. this._linesIndices.push(offset + 3);
  101459. };
  101460. /**
  101461. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  101462. */
  101463. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  101464. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101465. var indices = this._source.getIndices();
  101466. if (!indices || !positions) {
  101467. return;
  101468. }
  101469. // First let's find adjacencies
  101470. var adjacencies = new Array();
  101471. var faceNormals = new Array();
  101472. var index;
  101473. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  101474. var currentAdjecancy = new FaceAdjacencies();
  101475. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  101476. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  101477. adjacencies.push(currentAdjecancy);
  101478. }
  101479. // Create lines
  101480. for (index = 0; index < adjacencies.length; index++) {
  101481. // 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
  101482. var current = adjacencies[index];
  101483. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101484. }
  101485. // Merge into a single mesh
  101486. var engine = this._source.getScene().getEngine();
  101487. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101488. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101489. this._ib = engine.createIndexBuffer(this._linesIndices);
  101490. this._indicesCount = this._linesIndices.length;
  101491. };
  101492. return LineEdgesRenderer;
  101493. }(BABYLON.EdgesRenderer));
  101494. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  101495. })(BABYLON || (BABYLON = {}));
  101496. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  101497. var BABYLON;
  101498. (function (BABYLON) {
  101499. // Adds the parser to the scene parsers.
  101500. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  101501. if (parsedData.effectLayers) {
  101502. if (!container.effectLayers) {
  101503. container.effectLayers = new Array();
  101504. }
  101505. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  101506. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  101507. container.effectLayers.push(effectLayer);
  101508. }
  101509. }
  101510. });
  101511. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  101512. var index = this.effectLayers.indexOf(toRemove);
  101513. if (index !== -1) {
  101514. this.effectLayers.splice(index, 1);
  101515. }
  101516. return index;
  101517. };
  101518. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  101519. this.effectLayers.push(newEffectLayer);
  101520. };
  101521. /**
  101522. * Defines the layer scene component responsible to manage any effect layers
  101523. * in a given scene.
  101524. */
  101525. var EffectLayerSceneComponent = /** @class */ (function () {
  101526. /**
  101527. * Creates a new instance of the component for the given scene
  101528. * @param scene Defines the scene to register the component in
  101529. */
  101530. function EffectLayerSceneComponent(scene) {
  101531. /**
  101532. * The component name helpfull to identify the component in the list of scene components.
  101533. */
  101534. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  101535. this._renderEffects = false;
  101536. this._needStencil = false;
  101537. this._previousStencilState = false;
  101538. this.scene = scene;
  101539. this._engine = scene.getEngine();
  101540. scene.effectLayers = new Array();
  101541. }
  101542. /**
  101543. * Registers the component in a given scene
  101544. */
  101545. EffectLayerSceneComponent.prototype.register = function () {
  101546. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  101547. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  101548. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  101549. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  101550. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  101551. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  101552. };
  101553. /**
  101554. * Rebuilds the elements related to this component in case of
  101555. * context lost for instance.
  101556. */
  101557. EffectLayerSceneComponent.prototype.rebuild = function () {
  101558. var layers = this.scene.effectLayers;
  101559. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  101560. var effectLayer = layers_1[_i];
  101561. effectLayer._rebuild();
  101562. }
  101563. };
  101564. /**
  101565. * Serializes the component data to the specified json object
  101566. * @param serializationObject The object to serialize to
  101567. */
  101568. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  101569. // Effect layers
  101570. serializationObject.effectLayers = [];
  101571. var layers = this.scene.effectLayers;
  101572. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  101573. var effectLayer = layers_2[_i];
  101574. if (effectLayer.serialize) {
  101575. serializationObject.effectLayers.push(effectLayer.serialize());
  101576. }
  101577. }
  101578. };
  101579. /**
  101580. * Adds all the element from the container to the scene
  101581. * @param container the container holding the elements
  101582. */
  101583. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  101584. var _this = this;
  101585. if (!container.effectLayers) {
  101586. return;
  101587. }
  101588. container.effectLayers.forEach(function (o) {
  101589. _this.scene.addEffectLayer(o);
  101590. });
  101591. };
  101592. /**
  101593. * Removes all the elements in the container from the scene
  101594. * @param container contains the elements to remove
  101595. */
  101596. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  101597. var _this = this;
  101598. if (!container.effectLayers) {
  101599. return;
  101600. }
  101601. container.effectLayers.forEach(function (o) {
  101602. _this.scene.removeEffectLayer(o);
  101603. });
  101604. };
  101605. /**
  101606. * Disposes the component and the associated ressources.
  101607. */
  101608. EffectLayerSceneComponent.prototype.dispose = function () {
  101609. var layers = this.scene.effectLayers;
  101610. while (layers.length) {
  101611. layers[0].dispose();
  101612. }
  101613. };
  101614. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  101615. var layers = this.scene.effectLayers;
  101616. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  101617. var layer = layers_3[_i];
  101618. if (!layer.hasMesh(mesh)) {
  101619. continue;
  101620. }
  101621. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  101622. var subMesh = _b[_a];
  101623. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  101624. return false;
  101625. }
  101626. }
  101627. }
  101628. return true;
  101629. };
  101630. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  101631. this._renderEffects = false;
  101632. this._needStencil = false;
  101633. var layers = this.scene.effectLayers;
  101634. if (layers && layers.length > 0) {
  101635. this._previousStencilState = this._engine.getStencilBuffer();
  101636. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  101637. var effectLayer = layers_4[_i];
  101638. if (effectLayer.shouldRender() &&
  101639. (!effectLayer.camera ||
  101640. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  101641. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  101642. this._renderEffects = true;
  101643. this._needStencil = this._needStencil || effectLayer.needStencil();
  101644. var renderTarget = effectLayer._mainTexture;
  101645. if (renderTarget._shouldRender()) {
  101646. this.scene.incrementRenderId();
  101647. renderTarget.render(false, false);
  101648. }
  101649. }
  101650. }
  101651. this.scene.incrementRenderId();
  101652. }
  101653. };
  101654. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  101655. // Activate effect Layer stencil
  101656. if (this._needStencil) {
  101657. this._engine.setStencilBuffer(true);
  101658. }
  101659. };
  101660. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  101661. // Restore effect Layer stencil
  101662. if (this._needStencil) {
  101663. this._engine.setStencilBuffer(this._previousStencilState);
  101664. }
  101665. };
  101666. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  101667. if (this._renderEffects) {
  101668. this._engine.setDepthBuffer(false);
  101669. var layers = this.scene.effectLayers;
  101670. for (var i = 0; i < layers.length; i++) {
  101671. var effectLayer = layers[i];
  101672. if (effectLayer.renderingGroupId === renderingGroupId) {
  101673. if (effectLayer.shouldRender()) {
  101674. effectLayer.render();
  101675. }
  101676. }
  101677. }
  101678. this._engine.setDepthBuffer(true);
  101679. }
  101680. };
  101681. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  101682. if (this._renderEffects) {
  101683. this._draw(-1);
  101684. }
  101685. };
  101686. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  101687. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  101688. this._draw(index);
  101689. }
  101690. };
  101691. return EffectLayerSceneComponent;
  101692. }());
  101693. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  101694. })(BABYLON || (BABYLON = {}));
  101695. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  101696. var __assign = (this && this.__assign) || function () {
  101697. __assign = Object.assign || function(t) {
  101698. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101699. s = arguments[i];
  101700. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101701. t[p] = s[p];
  101702. }
  101703. return t;
  101704. };
  101705. return __assign.apply(this, arguments);
  101706. };
  101707. var BABYLON;
  101708. (function (BABYLON) {
  101709. /**
  101710. * The effect layer Helps adding post process effect blended with the main pass.
  101711. *
  101712. * This can be for instance use to generate glow or higlight effects on the scene.
  101713. *
  101714. * The effect layer class can not be used directly and is intented to inherited from to be
  101715. * customized per effects.
  101716. */
  101717. var EffectLayer = /** @class */ (function () {
  101718. /**
  101719. * Instantiates a new effect Layer and references it in the scene.
  101720. * @param name The name of the layer
  101721. * @param scene The scene to use the layer in
  101722. */
  101723. function EffectLayer(
  101724. /** The Friendly of the effect in the scene */
  101725. name, scene) {
  101726. this._vertexBuffers = {};
  101727. this._maxSize = 0;
  101728. this._mainTextureDesiredSize = { width: 0, height: 0 };
  101729. this._shouldRender = true;
  101730. this._postProcesses = [];
  101731. this._textures = [];
  101732. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  101733. /**
  101734. * The clear color of the texture used to generate the glow map.
  101735. */
  101736. this.neutralColor = new BABYLON.Color4();
  101737. /**
  101738. * Specifies wether the highlight layer is enabled or not.
  101739. */
  101740. this.isEnabled = true;
  101741. /**
  101742. * An event triggered when the effect layer has been disposed.
  101743. */
  101744. this.onDisposeObservable = new BABYLON.Observable();
  101745. /**
  101746. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  101747. */
  101748. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  101749. /**
  101750. * An event triggered when the generated texture is being merged in the scene.
  101751. */
  101752. this.onBeforeComposeObservable = new BABYLON.Observable();
  101753. /**
  101754. * An event triggered when the generated texture has been merged in the scene.
  101755. */
  101756. this.onAfterComposeObservable = new BABYLON.Observable();
  101757. /**
  101758. * An event triggered when the efffect layer changes its size.
  101759. */
  101760. this.onSizeChangedObservable = new BABYLON.Observable();
  101761. this.name = name;
  101762. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101763. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  101764. if (!component) {
  101765. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  101766. this._scene._addComponent(component);
  101767. }
  101768. this._engine = this._scene.getEngine();
  101769. this._maxSize = this._engine.getCaps().maxTextureSize;
  101770. this._scene.effectLayers.push(this);
  101771. // Generate Buffers
  101772. this._generateIndexBuffer();
  101773. this._genrateVertexBuffer();
  101774. }
  101775. Object.defineProperty(EffectLayer.prototype, "camera", {
  101776. /**
  101777. * Gets the camera attached to the layer.
  101778. */
  101779. get: function () {
  101780. return this._effectLayerOptions.camera;
  101781. },
  101782. enumerable: true,
  101783. configurable: true
  101784. });
  101785. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  101786. /**
  101787. * Gets the rendering group id the layer should render in.
  101788. */
  101789. get: function () {
  101790. return this._effectLayerOptions.renderingGroupId;
  101791. },
  101792. enumerable: true,
  101793. configurable: true
  101794. });
  101795. /**
  101796. * Initializes the effect layer with the required options.
  101797. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  101798. */
  101799. EffectLayer.prototype._init = function (options) {
  101800. // Adapt options
  101801. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  101802. this._setMainTextureSize();
  101803. this._createMainTexture();
  101804. this._createTextureAndPostProcesses();
  101805. this._mergeEffect = this._createMergeEffect();
  101806. };
  101807. /**
  101808. * Generates the index buffer of the full screen quad blending to the main canvas.
  101809. */
  101810. EffectLayer.prototype._generateIndexBuffer = function () {
  101811. // Indices
  101812. var indices = [];
  101813. indices.push(0);
  101814. indices.push(1);
  101815. indices.push(2);
  101816. indices.push(0);
  101817. indices.push(2);
  101818. indices.push(3);
  101819. this._indexBuffer = this._engine.createIndexBuffer(indices);
  101820. };
  101821. /**
  101822. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  101823. */
  101824. EffectLayer.prototype._genrateVertexBuffer = function () {
  101825. // VBO
  101826. var vertices = [];
  101827. vertices.push(1, 1);
  101828. vertices.push(-1, 1);
  101829. vertices.push(-1, -1);
  101830. vertices.push(1, -1);
  101831. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  101832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  101833. };
  101834. /**
  101835. * Sets the main texture desired size which is the closest power of two
  101836. * of the engine canvas size.
  101837. */
  101838. EffectLayer.prototype._setMainTextureSize = function () {
  101839. if (this._effectLayerOptions.mainTextureFixedSize) {
  101840. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  101841. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  101842. }
  101843. else {
  101844. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  101845. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  101846. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  101847. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  101848. }
  101849. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  101850. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  101851. };
  101852. /**
  101853. * Creates the main texture for the effect layer.
  101854. */
  101855. EffectLayer.prototype._createMainTexture = function () {
  101856. var _this = this;
  101857. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  101858. width: this._mainTextureDesiredSize.width,
  101859. height: this._mainTextureDesiredSize.height
  101860. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  101861. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  101862. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101863. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101864. this._mainTexture.anisotropicFilteringLevel = 1;
  101865. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101866. this._mainTexture.renderParticles = false;
  101867. this._mainTexture.renderList = null;
  101868. this._mainTexture.ignoreCameraViewport = true;
  101869. // Custom render function
  101870. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  101871. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  101872. var index;
  101873. var engine = _this._scene.getEngine();
  101874. if (depthOnlySubMeshes.length) {
  101875. engine.setColorWrite(false);
  101876. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  101877. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  101878. }
  101879. engine.setColorWrite(true);
  101880. }
  101881. for (index = 0; index < opaqueSubMeshes.length; index++) {
  101882. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  101883. }
  101884. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  101885. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  101886. }
  101887. for (index = 0; index < transparentSubMeshes.length; index++) {
  101888. _this._renderSubMesh(transparentSubMeshes.data[index]);
  101889. }
  101890. };
  101891. this._mainTexture.onClearObservable.add(function (engine) {
  101892. engine.clear(_this.neutralColor, true, true, true);
  101893. });
  101894. };
  101895. /**
  101896. * Checks for the readiness of the element composing the layer.
  101897. * @param subMesh the mesh to check for
  101898. * @param useInstances specify wether or not to use instances to render the mesh
  101899. * @param emissiveTexture the associated emissive texture used to generate the glow
  101900. * @return true if ready otherwise, false
  101901. */
  101902. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  101903. var material = subMesh.getMaterial();
  101904. if (!material) {
  101905. return false;
  101906. }
  101907. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  101908. return false;
  101909. }
  101910. var defines = [];
  101911. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101912. var mesh = subMesh.getMesh();
  101913. var uv1 = false;
  101914. var uv2 = false;
  101915. // Alpha test
  101916. if (material && material.needAlphaTesting()) {
  101917. var alphaTexture = material.getAlphaTestTexture();
  101918. if (alphaTexture) {
  101919. defines.push("#define ALPHATEST");
  101920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101921. alphaTexture.coordinatesIndex === 1) {
  101922. defines.push("#define DIFFUSEUV2");
  101923. uv2 = true;
  101924. }
  101925. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101926. defines.push("#define DIFFUSEUV1");
  101927. uv1 = true;
  101928. }
  101929. }
  101930. }
  101931. // Emissive
  101932. if (emissiveTexture) {
  101933. defines.push("#define EMISSIVE");
  101934. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101935. emissiveTexture.coordinatesIndex === 1) {
  101936. defines.push("#define EMISSIVEUV2");
  101937. uv2 = true;
  101938. }
  101939. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101940. defines.push("#define EMISSIVEUV1");
  101941. uv1 = true;
  101942. }
  101943. }
  101944. if (uv1) {
  101945. attribs.push(BABYLON.VertexBuffer.UVKind);
  101946. defines.push("#define UV1");
  101947. }
  101948. if (uv2) {
  101949. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101950. defines.push("#define UV2");
  101951. }
  101952. // Bones
  101953. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101954. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101955. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101956. if (mesh.numBoneInfluencers > 4) {
  101957. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101958. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101959. }
  101960. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101961. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  101962. }
  101963. else {
  101964. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101965. }
  101966. // Morph targets
  101967. var manager = mesh.morphTargetManager;
  101968. var morphInfluencers = 0;
  101969. if (manager) {
  101970. if (manager.numInfluencers > 0) {
  101971. defines.push("#define MORPHTARGETS");
  101972. morphInfluencers = manager.numInfluencers;
  101973. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  101974. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  101975. }
  101976. }
  101977. // Instances
  101978. if (useInstances) {
  101979. defines.push("#define INSTANCES");
  101980. attribs.push("world0");
  101981. attribs.push("world1");
  101982. attribs.push("world2");
  101983. attribs.push("world3");
  101984. }
  101985. // Get correct effect
  101986. var join = defines.join("\n");
  101987. if (this._cachedDefines !== join) {
  101988. this._cachedDefines = join;
  101989. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  101990. }
  101991. return this._effectLayerMapGenerationEffect.isReady();
  101992. };
  101993. /**
  101994. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  101995. */
  101996. EffectLayer.prototype.render = function () {
  101997. var currentEffect = this._mergeEffect;
  101998. // Check
  101999. if (!currentEffect.isReady())
  102000. return;
  102001. for (var i = 0; i < this._postProcesses.length; i++) {
  102002. if (!this._postProcesses[i].isReady()) {
  102003. return;
  102004. }
  102005. }
  102006. var engine = this._scene.getEngine();
  102007. this.onBeforeComposeObservable.notifyObservers(this);
  102008. // Render
  102009. engine.enableEffect(currentEffect);
  102010. engine.setState(false);
  102011. // VBOs
  102012. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102013. // Cache
  102014. var previousAlphaMode = engine.getAlphaMode();
  102015. // Go Blend.
  102016. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  102017. // Blends the map on the main canvas.
  102018. this._internalRender(currentEffect);
  102019. // Restore Alpha
  102020. engine.setAlphaMode(previousAlphaMode);
  102021. this.onAfterComposeObservable.notifyObservers(this);
  102022. // Handle size changes.
  102023. var size = this._mainTexture.getSize();
  102024. this._setMainTextureSize();
  102025. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  102026. // Recreate RTT and post processes on size change.
  102027. this.onSizeChangedObservable.notifyObservers(this);
  102028. this._disposeTextureAndPostProcesses();
  102029. this._createMainTexture();
  102030. this._createTextureAndPostProcesses();
  102031. }
  102032. };
  102033. /**
  102034. * Determine if a given mesh will be used in the current effect.
  102035. * @param mesh mesh to test
  102036. * @returns true if the mesh will be used
  102037. */
  102038. EffectLayer.prototype.hasMesh = function (mesh) {
  102039. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  102040. return true;
  102041. }
  102042. return false;
  102043. };
  102044. /**
  102045. * Returns true if the layer contains information to display, otherwise false.
  102046. * @returns true if the glow layer should be rendered
  102047. */
  102048. EffectLayer.prototype.shouldRender = function () {
  102049. return this.isEnabled && this._shouldRender;
  102050. };
  102051. /**
  102052. * Returns true if the mesh should render, otherwise false.
  102053. * @param mesh The mesh to render
  102054. * @returns true if it should render otherwise false
  102055. */
  102056. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  102057. return true;
  102058. };
  102059. /**
  102060. * Returns true if the mesh should render, otherwise false.
  102061. * @param mesh The mesh to render
  102062. * @returns true if it should render otherwise false
  102063. */
  102064. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  102065. return true;
  102066. };
  102067. /**
  102068. * Renders the submesh passed in parameter to the generation map.
  102069. */
  102070. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  102071. var _this = this;
  102072. if (!this.shouldRender()) {
  102073. return;
  102074. }
  102075. var material = subMesh.getMaterial();
  102076. var mesh = subMesh.getRenderingMesh();
  102077. var scene = this._scene;
  102078. var engine = scene.getEngine();
  102079. if (!material) {
  102080. return;
  102081. }
  102082. // Do not block in blend mode.
  102083. if (material.needAlphaBlendingForMesh(mesh)) {
  102084. return;
  102085. }
  102086. // Culling
  102087. engine.setState(material.backFaceCulling);
  102088. // Managing instances
  102089. var batch = mesh._getInstancesRenderList(subMesh._id);
  102090. if (batch.mustReturn) {
  102091. return;
  102092. }
  102093. // Early Exit per mesh
  102094. if (!this._shouldRenderMesh(mesh)) {
  102095. return;
  102096. }
  102097. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  102098. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  102099. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  102100. engine.enableEffect(this._effectLayerMapGenerationEffect);
  102101. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  102102. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  102103. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  102104. // Alpha test
  102105. if (material && material.needAlphaTesting()) {
  102106. var alphaTexture = material.getAlphaTestTexture();
  102107. if (alphaTexture) {
  102108. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  102109. var textureMatrix = alphaTexture.getTextureMatrix();
  102110. if (textureMatrix) {
  102111. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  102112. }
  102113. }
  102114. }
  102115. // Glow emissive only
  102116. if (this._emissiveTextureAndColor.texture) {
  102117. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  102118. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  102119. }
  102120. // Bones
  102121. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  102122. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  102123. }
  102124. // Morph targets
  102125. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  102126. // Draw
  102127. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  102128. }
  102129. else {
  102130. // Need to reset refresh rate of the main map
  102131. this._mainTexture.resetRefreshCounter();
  102132. }
  102133. };
  102134. /**
  102135. * Rebuild the required buffers.
  102136. * @hidden Internal use only.
  102137. */
  102138. EffectLayer.prototype._rebuild = function () {
  102139. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102140. if (vb) {
  102141. vb._rebuild();
  102142. }
  102143. this._generateIndexBuffer();
  102144. };
  102145. /**
  102146. * Dispose only the render target textures and post process.
  102147. */
  102148. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  102149. this._mainTexture.dispose();
  102150. for (var i = 0; i < this._postProcesses.length; i++) {
  102151. if (this._postProcesses[i]) {
  102152. this._postProcesses[i].dispose();
  102153. }
  102154. }
  102155. this._postProcesses = [];
  102156. for (var i = 0; i < this._textures.length; i++) {
  102157. if (this._textures[i]) {
  102158. this._textures[i].dispose();
  102159. }
  102160. }
  102161. this._textures = [];
  102162. };
  102163. /**
  102164. * Dispose the highlight layer and free resources.
  102165. */
  102166. EffectLayer.prototype.dispose = function () {
  102167. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102168. if (vertexBuffer) {
  102169. vertexBuffer.dispose();
  102170. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102171. }
  102172. if (this._indexBuffer) {
  102173. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102174. this._indexBuffer = null;
  102175. }
  102176. // Clean textures and post processes
  102177. this._disposeTextureAndPostProcesses();
  102178. // Remove from scene
  102179. var index = this._scene.effectLayers.indexOf(this, 0);
  102180. if (index > -1) {
  102181. this._scene.effectLayers.splice(index, 1);
  102182. }
  102183. // Callback
  102184. this.onDisposeObservable.notifyObservers(this);
  102185. this.onDisposeObservable.clear();
  102186. this.onBeforeRenderMainTextureObservable.clear();
  102187. this.onBeforeComposeObservable.clear();
  102188. this.onAfterComposeObservable.clear();
  102189. this.onSizeChangedObservable.clear();
  102190. };
  102191. /**
  102192. * Gets the class name of the effect layer
  102193. * @returns the string with the class name of the effect layer
  102194. */
  102195. EffectLayer.prototype.getClassName = function () {
  102196. return "EffectLayer";
  102197. };
  102198. /**
  102199. * Creates an effect layer from parsed effect layer data
  102200. * @param parsedEffectLayer defines effect layer data
  102201. * @param scene defines the current scene
  102202. * @param rootUrl defines the root URL containing the effect layer information
  102203. * @returns a parsed effect Layer
  102204. */
  102205. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  102206. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  102207. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  102208. };
  102209. __decorate([
  102210. BABYLON.serialize()
  102211. ], EffectLayer.prototype, "name", void 0);
  102212. __decorate([
  102213. BABYLON.serializeAsColor4()
  102214. ], EffectLayer.prototype, "neutralColor", void 0);
  102215. __decorate([
  102216. BABYLON.serialize()
  102217. ], EffectLayer.prototype, "isEnabled", void 0);
  102218. __decorate([
  102219. BABYLON.serializeAsCameraReference()
  102220. ], EffectLayer.prototype, "camera", null);
  102221. __decorate([
  102222. BABYLON.serialize()
  102223. ], EffectLayer.prototype, "renderingGroupId", null);
  102224. return EffectLayer;
  102225. }());
  102226. BABYLON.EffectLayer = EffectLayer;
  102227. })(BABYLON || (BABYLON = {}));
  102228. //# sourceMappingURL=babylon.effectLayer.js.map
  102229. var BABYLON;
  102230. (function (BABYLON) {
  102231. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  102232. for (var index = 0; index < this.effectLayers.length; index++) {
  102233. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  102234. return this.effectLayers[index];
  102235. }
  102236. }
  102237. return null;
  102238. };
  102239. /**
  102240. * Special Glow Blur post process only blurring the alpha channel
  102241. * It enforces keeping the most luminous color in the color channel.
  102242. */
  102243. var GlowBlurPostProcess = /** @class */ (function (_super) {
  102244. __extends(GlowBlurPostProcess, _super);
  102245. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  102246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  102247. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  102248. _this.direction = direction;
  102249. _this.kernel = kernel;
  102250. _this.onApplyObservable.add(function (effect) {
  102251. effect.setFloat2("screenSize", _this.width, _this.height);
  102252. effect.setVector2("direction", _this.direction);
  102253. effect.setFloat("blurWidth", _this.kernel);
  102254. });
  102255. return _this;
  102256. }
  102257. return GlowBlurPostProcess;
  102258. }(BABYLON.PostProcess));
  102259. /**
  102260. * The highlight layer Helps adding a glow effect around a mesh.
  102261. *
  102262. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102263. * glowy meshes to your scene.
  102264. *
  102265. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  102266. */
  102267. var HighlightLayer = /** @class */ (function (_super) {
  102268. __extends(HighlightLayer, _super);
  102269. /**
  102270. * Instantiates a new highlight Layer and references it to the scene..
  102271. * @param name The name of the layer
  102272. * @param scene The scene to use the layer in
  102273. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  102274. */
  102275. function HighlightLayer(name, scene, options) {
  102276. var _this = _super.call(this, name, scene) || this;
  102277. _this.name = name;
  102278. /**
  102279. * Specifies whether or not the inner glow is ACTIVE in the layer.
  102280. */
  102281. _this.innerGlow = true;
  102282. /**
  102283. * Specifies whether or not the outer glow is ACTIVE in the layer.
  102284. */
  102285. _this.outerGlow = true;
  102286. /**
  102287. * An event triggered when the highlight layer is being blurred.
  102288. */
  102289. _this.onBeforeBlurObservable = new BABYLON.Observable();
  102290. /**
  102291. * An event triggered when the highlight layer has been blurred.
  102292. */
  102293. _this.onAfterBlurObservable = new BABYLON.Observable();
  102294. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  102295. _this._meshes = {};
  102296. _this._excludedMeshes = {};
  102297. _this.neutralColor = HighlightLayer.NeutralColor;
  102298. // Warn on stencil
  102299. if (!_this._engine.isStencilEnable) {
  102300. 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 }");
  102301. }
  102302. // Adapt options
  102303. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  102304. // Initialize the layer
  102305. _this._init({
  102306. alphaBlendingMode: _this._options.alphaBlendingMode,
  102307. camera: _this._options.camera,
  102308. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102309. mainTextureRatio: _this._options.mainTextureRatio,
  102310. renderingGroupId: _this._options.renderingGroupId
  102311. });
  102312. // Do not render as long as no meshes have been added
  102313. _this._shouldRender = false;
  102314. return _this;
  102315. }
  102316. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  102317. /**
  102318. * Gets the horizontal size of the blur.
  102319. */
  102320. get: function () {
  102321. return this._horizontalBlurPostprocess.kernel;
  102322. },
  102323. /**
  102324. * Specifies the horizontal size of the blur.
  102325. */
  102326. set: function (value) {
  102327. this._horizontalBlurPostprocess.kernel = value;
  102328. },
  102329. enumerable: true,
  102330. configurable: true
  102331. });
  102332. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  102333. /**
  102334. * Gets the vertical size of the blur.
  102335. */
  102336. get: function () {
  102337. return this._verticalBlurPostprocess.kernel;
  102338. },
  102339. /**
  102340. * Specifies the vertical size of the blur.
  102341. */
  102342. set: function (value) {
  102343. this._verticalBlurPostprocess.kernel = value;
  102344. },
  102345. enumerable: true,
  102346. configurable: true
  102347. });
  102348. /**
  102349. * Get the effect name of the layer.
  102350. * @return The effect name
  102351. */
  102352. HighlightLayer.prototype.getEffectName = function () {
  102353. return HighlightLayer.EffectName;
  102354. };
  102355. /**
  102356. * Create the merge effect. This is the shader use to blit the information back
  102357. * to the main canvas at the end of the scene rendering.
  102358. */
  102359. HighlightLayer.prototype._createMergeEffect = function () {
  102360. // Effect
  102361. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  102362. };
  102363. /**
  102364. * Creates the render target textures and post processes used in the highlight layer.
  102365. */
  102366. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  102367. var _this = this;
  102368. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  102369. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  102370. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102371. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102372. var textureType = 0;
  102373. if (this._engine.getCaps().textureHalfFloatRender) {
  102374. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102375. }
  102376. else {
  102377. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102378. }
  102379. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  102380. width: blurTextureWidth,
  102381. height: blurTextureHeight
  102382. }, this._scene, false, true, textureType);
  102383. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102384. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102385. this._blurTexture.anisotropicFilteringLevel = 16;
  102386. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  102387. this._blurTexture.renderParticles = false;
  102388. this._blurTexture.ignoreCameraViewport = true;
  102389. this._textures = [this._blurTexture];
  102390. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  102391. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102392. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  102393. effect.setTexture("textureSampler", _this._mainTexture);
  102394. });
  102395. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102396. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102397. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102398. });
  102399. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102400. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  102401. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102402. });
  102403. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102404. }
  102405. else {
  102406. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  102407. width: blurTextureWidth,
  102408. height: blurTextureHeight
  102409. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102410. this._horizontalBlurPostprocess.width = blurTextureWidth;
  102411. this._horizontalBlurPostprocess.height = blurTextureHeight;
  102412. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102413. effect.setTexture("textureSampler", _this._mainTexture);
  102414. });
  102415. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  102416. width: blurTextureWidth,
  102417. height: blurTextureHeight
  102418. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102419. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102420. }
  102421. this._mainTexture.onAfterUnbindObservable.add(function () {
  102422. _this.onBeforeBlurObservable.notifyObservers(_this);
  102423. var internalTexture = _this._blurTexture.getInternalTexture();
  102424. if (internalTexture) {
  102425. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  102426. }
  102427. _this.onAfterBlurObservable.notifyObservers(_this);
  102428. });
  102429. // Prevent autoClear.
  102430. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102431. };
  102432. /**
  102433. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102434. */
  102435. HighlightLayer.prototype.needStencil = function () {
  102436. return true;
  102437. };
  102438. /**
  102439. * Checks for the readiness of the element composing the layer.
  102440. * @param subMesh the mesh to check for
  102441. * @param useInstances specify wether or not to use instances to render the mesh
  102442. * @param emissiveTexture the associated emissive texture used to generate the glow
  102443. * @return true if ready otherwise, false
  102444. */
  102445. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  102446. var material = subMesh.getMaterial();
  102447. var mesh = subMesh.getRenderingMesh();
  102448. if (!material || !mesh || !this._meshes) {
  102449. return false;
  102450. }
  102451. var emissiveTexture = null;
  102452. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102453. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102454. emissiveTexture = material.emissiveTexture;
  102455. }
  102456. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102457. };
  102458. /**
  102459. * Implementation specific of rendering the generating effect on the main canvas.
  102460. * @param effect The effect used to render through
  102461. */
  102462. HighlightLayer.prototype._internalRender = function (effect) {
  102463. // Texture
  102464. effect.setTexture("textureSampler", this._blurTexture);
  102465. // Cache
  102466. var engine = this._engine;
  102467. var previousStencilBuffer = engine.getStencilBuffer();
  102468. var previousStencilFunction = engine.getStencilFunction();
  102469. var previousStencilMask = engine.getStencilMask();
  102470. var previousStencilOperationPass = engine.getStencilOperationPass();
  102471. var previousStencilOperationFail = engine.getStencilOperationFail();
  102472. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  102473. var previousStencilReference = engine.getStencilFunctionReference();
  102474. // Stencil operations
  102475. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  102476. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  102477. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  102478. // Draw order
  102479. engine.setStencilMask(0x00);
  102480. engine.setStencilBuffer(true);
  102481. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  102482. // 2 passes inner outer
  102483. if (this.outerGlow) {
  102484. effect.setFloat("offset", 0);
  102485. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  102486. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102487. }
  102488. if (this.innerGlow) {
  102489. effect.setFloat("offset", 1);
  102490. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  102491. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102492. }
  102493. // Restore Cache
  102494. engine.setStencilFunction(previousStencilFunction);
  102495. engine.setStencilMask(previousStencilMask);
  102496. engine.setStencilBuffer(previousStencilBuffer);
  102497. engine.setStencilOperationPass(previousStencilOperationPass);
  102498. engine.setStencilOperationFail(previousStencilOperationFail);
  102499. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  102500. engine.setStencilFunctionReference(previousStencilReference);
  102501. };
  102502. /**
  102503. * Returns true if the layer contains information to display, otherwise false.
  102504. */
  102505. HighlightLayer.prototype.shouldRender = function () {
  102506. if (_super.prototype.shouldRender.call(this)) {
  102507. return this._meshes ? true : false;
  102508. }
  102509. return false;
  102510. };
  102511. /**
  102512. * Returns true if the mesh should render, otherwise false.
  102513. * @param mesh The mesh to render
  102514. * @returns true if it should render otherwise false
  102515. */
  102516. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  102517. // Excluded Mesh
  102518. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  102519. return false;
  102520. }
  102521. ;
  102522. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102523. return false;
  102524. }
  102525. return true;
  102526. };
  102527. /**
  102528. * Sets the required values for both the emissive texture and and the main color.
  102529. */
  102530. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102531. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102532. if (highlightLayerMesh) {
  102533. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  102534. }
  102535. else {
  102536. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102537. }
  102538. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102539. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102540. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  102541. }
  102542. else {
  102543. this._emissiveTextureAndColor.texture = null;
  102544. }
  102545. };
  102546. /**
  102547. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  102548. * @param mesh The mesh to exclude from the highlight layer
  102549. */
  102550. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  102551. if (!this._excludedMeshes) {
  102552. return;
  102553. }
  102554. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  102555. if (!meshExcluded) {
  102556. this._excludedMeshes[mesh.uniqueId] = {
  102557. mesh: mesh,
  102558. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  102559. mesh.getEngine().setStencilBuffer(false);
  102560. }),
  102561. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  102562. mesh.getEngine().setStencilBuffer(true);
  102563. }),
  102564. };
  102565. }
  102566. };
  102567. /**
  102568. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  102569. * @param mesh The mesh to highlight
  102570. */
  102571. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  102572. if (!this._excludedMeshes) {
  102573. return;
  102574. }
  102575. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  102576. if (meshExcluded) {
  102577. if (meshExcluded.beforeRender) {
  102578. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  102579. }
  102580. if (meshExcluded.afterRender) {
  102581. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  102582. }
  102583. }
  102584. this._excludedMeshes[mesh.uniqueId] = null;
  102585. };
  102586. /**
  102587. * Determine if a given mesh will be highlighted by the current HighlightLayer
  102588. * @param mesh mesh to test
  102589. * @returns true if the mesh will be highlighted by the current HighlightLayer
  102590. */
  102591. HighlightLayer.prototype.hasMesh = function (mesh) {
  102592. if (!this._meshes) {
  102593. return false;
  102594. }
  102595. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102596. return false;
  102597. }
  102598. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  102599. };
  102600. /**
  102601. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  102602. * @param mesh The mesh to highlight
  102603. * @param color The color of the highlight
  102604. * @param glowEmissiveOnly Extract the glow from the emissive texture
  102605. */
  102606. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  102607. var _this = this;
  102608. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  102609. if (!this._meshes) {
  102610. return;
  102611. }
  102612. var meshHighlight = this._meshes[mesh.uniqueId];
  102613. if (meshHighlight) {
  102614. meshHighlight.color = color;
  102615. }
  102616. else {
  102617. this._meshes[mesh.uniqueId] = {
  102618. mesh: mesh,
  102619. color: color,
  102620. // Lambda required for capture due to Observable this context
  102621. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  102622. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  102623. _this._defaultStencilReference(mesh);
  102624. }
  102625. else {
  102626. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  102627. }
  102628. }),
  102629. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  102630. glowEmissiveOnly: glowEmissiveOnly
  102631. };
  102632. mesh.onDisposeObservable.add(function () {
  102633. _this._disposeMesh(mesh);
  102634. });
  102635. }
  102636. this._shouldRender = true;
  102637. };
  102638. /**
  102639. * Remove a mesh from the highlight layer in order to make it stop glowing.
  102640. * @param mesh The mesh to highlight
  102641. */
  102642. HighlightLayer.prototype.removeMesh = function (mesh) {
  102643. if (!this._meshes) {
  102644. return;
  102645. }
  102646. var meshHighlight = this._meshes[mesh.uniqueId];
  102647. if (meshHighlight) {
  102648. if (meshHighlight.observerHighlight) {
  102649. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  102650. }
  102651. if (meshHighlight.observerDefault) {
  102652. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  102653. }
  102654. delete this._meshes[mesh.uniqueId];
  102655. }
  102656. this._shouldRender = false;
  102657. for (var meshHighlightToCheck in this._meshes) {
  102658. if (this._meshes[meshHighlightToCheck]) {
  102659. this._shouldRender = true;
  102660. break;
  102661. }
  102662. }
  102663. };
  102664. /**
  102665. * Force the stencil to the normal expected value for none glowing parts
  102666. */
  102667. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  102668. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  102669. };
  102670. /**
  102671. * Free any resources and references associated to a mesh.
  102672. * Internal use
  102673. * @param mesh The mesh to free.
  102674. * @hidden
  102675. */
  102676. HighlightLayer.prototype._disposeMesh = function (mesh) {
  102677. this.removeMesh(mesh);
  102678. this.removeExcludedMesh(mesh);
  102679. };
  102680. /**
  102681. * Dispose the highlight layer and free resources.
  102682. */
  102683. HighlightLayer.prototype.dispose = function () {
  102684. if (this._meshes) {
  102685. // Clean mesh references
  102686. for (var id in this._meshes) {
  102687. var meshHighlight = this._meshes[id];
  102688. if (meshHighlight && meshHighlight.mesh) {
  102689. if (meshHighlight.observerHighlight) {
  102690. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  102691. }
  102692. if (meshHighlight.observerDefault) {
  102693. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  102694. }
  102695. }
  102696. }
  102697. this._meshes = null;
  102698. }
  102699. if (this._excludedMeshes) {
  102700. for (var id in this._excludedMeshes) {
  102701. var meshHighlight = this._excludedMeshes[id];
  102702. if (meshHighlight) {
  102703. if (meshHighlight.beforeRender) {
  102704. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  102705. }
  102706. if (meshHighlight.afterRender) {
  102707. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  102708. }
  102709. }
  102710. }
  102711. this._excludedMeshes = null;
  102712. }
  102713. _super.prototype.dispose.call(this);
  102714. };
  102715. /**
  102716. * Gets the class name of the effect layer
  102717. * @returns the string with the class name of the effect layer
  102718. */
  102719. HighlightLayer.prototype.getClassName = function () {
  102720. return "HighlightLayer";
  102721. };
  102722. /**
  102723. * Serializes this Highlight layer
  102724. * @returns a serialized Highlight layer object
  102725. */
  102726. HighlightLayer.prototype.serialize = function () {
  102727. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102728. serializationObject.customType = "BABYLON.HighlightLayer";
  102729. // Highlighted meshes
  102730. serializationObject.meshes = [];
  102731. if (this._meshes) {
  102732. for (var m in this._meshes) {
  102733. var mesh = this._meshes[m];
  102734. if (mesh) {
  102735. serializationObject.meshes.push({
  102736. glowEmissiveOnly: mesh.glowEmissiveOnly,
  102737. color: mesh.color.asArray(),
  102738. meshId: mesh.mesh.id
  102739. });
  102740. }
  102741. }
  102742. }
  102743. // Excluded meshes
  102744. serializationObject.excludedMeshes = [];
  102745. if (this._excludedMeshes) {
  102746. for (var e in this._excludedMeshes) {
  102747. var excludedMesh = this._excludedMeshes[e];
  102748. if (excludedMesh) {
  102749. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  102750. }
  102751. }
  102752. }
  102753. return serializationObject;
  102754. };
  102755. /**
  102756. * Creates a Highlight layer from parsed Highlight layer data
  102757. * @param parsedHightlightLayer defines the Highlight layer data
  102758. * @param scene defines the current scene
  102759. * @param rootUrl defines the root URL containing the Highlight layer information
  102760. * @returns a parsed Highlight layer
  102761. */
  102762. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  102763. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  102764. var index;
  102765. // Excluded meshes
  102766. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  102767. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  102768. if (mesh) {
  102769. hl.addExcludedMesh(mesh);
  102770. }
  102771. }
  102772. // Included meshes
  102773. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  102774. var highlightedMesh = parsedHightlightLayer.meshes[index];
  102775. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  102776. if (mesh) {
  102777. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  102778. }
  102779. }
  102780. return hl;
  102781. };
  102782. /**
  102783. * Effect Name of the highlight layer.
  102784. */
  102785. HighlightLayer.EffectName = "HighlightLayer";
  102786. /**
  102787. * The neutral color used during the preparation of the glow effect.
  102788. * This is black by default as the blend operation is a blend operation.
  102789. */
  102790. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  102791. /**
  102792. * Stencil value used for glowing meshes.
  102793. */
  102794. HighlightLayer.GlowingMeshStencilReference = 0x02;
  102795. /**
  102796. * Stencil value used for the other meshes in the scene.
  102797. */
  102798. HighlightLayer.NormalMeshStencilReference = 0x01;
  102799. __decorate([
  102800. BABYLON.serialize()
  102801. ], HighlightLayer.prototype, "innerGlow", void 0);
  102802. __decorate([
  102803. BABYLON.serialize()
  102804. ], HighlightLayer.prototype, "outerGlow", void 0);
  102805. __decorate([
  102806. BABYLON.serialize()
  102807. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  102808. __decorate([
  102809. BABYLON.serialize()
  102810. ], HighlightLayer.prototype, "blurVerticalSize", null);
  102811. __decorate([
  102812. BABYLON.serialize("options")
  102813. ], HighlightLayer.prototype, "_options", void 0);
  102814. return HighlightLayer;
  102815. }(BABYLON.EffectLayer));
  102816. BABYLON.HighlightLayer = HighlightLayer;
  102817. })(BABYLON || (BABYLON = {}));
  102818. //# sourceMappingURL=babylon.highlightLayer.js.map
  102819. var BABYLON;
  102820. (function (BABYLON) {
  102821. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  102822. for (var index = 0; index < this.effectLayers.length; index++) {
  102823. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  102824. return this.effectLayers[index];
  102825. }
  102826. }
  102827. return null;
  102828. };
  102829. /**
  102830. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  102831. *
  102832. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102833. * glowy meshes to your scene.
  102834. *
  102835. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  102836. */
  102837. var GlowLayer = /** @class */ (function (_super) {
  102838. __extends(GlowLayer, _super);
  102839. /**
  102840. * Instantiates a new glow Layer and references it to the scene.
  102841. * @param name The name of the layer
  102842. * @param scene The scene to use the layer in
  102843. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  102844. */
  102845. function GlowLayer(name, scene, options) {
  102846. var _this = _super.call(this, name, scene) || this;
  102847. _this._intensity = 1.0;
  102848. _this._includedOnlyMeshes = [];
  102849. _this._excludedMeshes = [];
  102850. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  102851. // Adapt options
  102852. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  102853. // Initialize the layer
  102854. _this._init({
  102855. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  102856. camera: _this._options.camera,
  102857. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102858. mainTextureRatio: _this._options.mainTextureRatio,
  102859. renderingGroupId: _this._options.renderingGroupId
  102860. });
  102861. return _this;
  102862. }
  102863. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  102864. /**
  102865. * Gets the kernel size of the blur.
  102866. */
  102867. get: function () {
  102868. return this._horizontalBlurPostprocess1.kernel;
  102869. },
  102870. /**
  102871. * Sets the kernel size of the blur.
  102872. */
  102873. set: function (value) {
  102874. this._horizontalBlurPostprocess1.kernel = value;
  102875. this._verticalBlurPostprocess1.kernel = value;
  102876. this._horizontalBlurPostprocess2.kernel = value;
  102877. this._verticalBlurPostprocess2.kernel = value;
  102878. },
  102879. enumerable: true,
  102880. configurable: true
  102881. });
  102882. Object.defineProperty(GlowLayer.prototype, "intensity", {
  102883. /**
  102884. * Gets the glow intensity.
  102885. */
  102886. get: function () {
  102887. return this._intensity;
  102888. },
  102889. /**
  102890. * Sets the glow intensity.
  102891. */
  102892. set: function (value) {
  102893. this._intensity = value;
  102894. },
  102895. enumerable: true,
  102896. configurable: true
  102897. });
  102898. /**
  102899. * Get the effect name of the layer.
  102900. * @return The effect name
  102901. */
  102902. GlowLayer.prototype.getEffectName = function () {
  102903. return GlowLayer.EffectName;
  102904. };
  102905. /**
  102906. * Create the merge effect. This is the shader use to blit the information back
  102907. * to the main canvas at the end of the scene rendering.
  102908. */
  102909. GlowLayer.prototype._createMergeEffect = function () {
  102910. // Effect
  102911. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  102912. };
  102913. /**
  102914. * Creates the render target textures and post processes used in the glow layer.
  102915. */
  102916. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  102917. var _this = this;
  102918. var blurTextureWidth = this._mainTextureDesiredSize.width;
  102919. var blurTextureHeight = this._mainTextureDesiredSize.height;
  102920. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102921. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102922. var textureType = 0;
  102923. if (this._engine.getCaps().textureHalfFloatRender) {
  102924. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102925. }
  102926. else {
  102927. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102928. }
  102929. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  102930. width: blurTextureWidth,
  102931. height: blurTextureHeight
  102932. }, this._scene, false, true, textureType);
  102933. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102934. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102935. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102936. this._blurTexture1.renderParticles = false;
  102937. this._blurTexture1.ignoreCameraViewport = true;
  102938. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  102939. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  102940. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  102941. width: blurTextureWidth2,
  102942. height: blurTextureHeight2
  102943. }, this._scene, false, true, textureType);
  102944. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102945. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102946. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102947. this._blurTexture2.renderParticles = false;
  102948. this._blurTexture2.ignoreCameraViewport = true;
  102949. this._textures = [this._blurTexture1, this._blurTexture2];
  102950. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102951. width: blurTextureWidth,
  102952. height: blurTextureHeight
  102953. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102954. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  102955. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  102956. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  102957. effect.setTexture("textureSampler", _this._mainTexture);
  102958. });
  102959. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102960. width: blurTextureWidth,
  102961. height: blurTextureHeight
  102962. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102963. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102964. width: blurTextureWidth2,
  102965. height: blurTextureHeight2
  102966. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102967. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  102968. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  102969. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  102970. effect.setTexture("textureSampler", _this._blurTexture1);
  102971. });
  102972. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102973. width: blurTextureWidth2,
  102974. height: blurTextureHeight2
  102975. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102976. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102977. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  102978. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102979. this._mainTexture.samples = this._options.mainTextureSamples;
  102980. this._mainTexture.onAfterUnbindObservable.add(function () {
  102981. var internalTexture = _this._blurTexture1.getInternalTexture();
  102982. if (internalTexture) {
  102983. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  102984. internalTexture = _this._blurTexture2.getInternalTexture();
  102985. if (internalTexture) {
  102986. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  102987. }
  102988. }
  102989. });
  102990. // Prevent autoClear.
  102991. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102992. };
  102993. /**
  102994. * Checks for the readiness of the element composing the layer.
  102995. * @param subMesh the mesh to check for
  102996. * @param useInstances specify wether or not to use instances to render the mesh
  102997. * @param emissiveTexture the associated emissive texture used to generate the glow
  102998. * @return true if ready otherwise, false
  102999. */
  103000. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  103001. var material = subMesh.getMaterial();
  103002. var mesh = subMesh.getRenderingMesh();
  103003. if (!material || !mesh) {
  103004. return false;
  103005. }
  103006. var emissiveTexture = material.emissiveTexture;
  103007. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  103008. };
  103009. /**
  103010. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  103011. */
  103012. GlowLayer.prototype.needStencil = function () {
  103013. return false;
  103014. };
  103015. /**
  103016. * Implementation specific of rendering the generating effect on the main canvas.
  103017. * @param effect The effect used to render through
  103018. */
  103019. GlowLayer.prototype._internalRender = function (effect) {
  103020. // Texture
  103021. effect.setTexture("textureSampler", this._blurTexture1);
  103022. effect.setTexture("textureSampler2", this._blurTexture2);
  103023. effect.setFloat("offset", this._intensity);
  103024. // Cache
  103025. var engine = this._engine;
  103026. var previousStencilBuffer = engine.getStencilBuffer();
  103027. // Draw order
  103028. engine.setStencilBuffer(false);
  103029. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103030. // Draw order
  103031. engine.setStencilBuffer(previousStencilBuffer);
  103032. };
  103033. /**
  103034. * Sets the required values for both the emissive texture and and the main color.
  103035. */
  103036. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103037. var textureLevel = 1.0;
  103038. if (this.customEmissiveTextureSelector) {
  103039. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  103040. }
  103041. else {
  103042. if (material) {
  103043. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103044. if (this._emissiveTextureAndColor.texture) {
  103045. textureLevel = this._emissiveTextureAndColor.texture.level;
  103046. }
  103047. }
  103048. else {
  103049. this._emissiveTextureAndColor.texture = null;
  103050. }
  103051. }
  103052. if (this.customEmissiveColorSelector) {
  103053. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  103054. }
  103055. else {
  103056. if (material.emissiveColor) {
  103057. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  103058. }
  103059. else {
  103060. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103061. }
  103062. }
  103063. };
  103064. /**
  103065. * Returns true if the mesh should render, otherwise false.
  103066. * @param mesh The mesh to render
  103067. * @returns true if it should render otherwise false
  103068. */
  103069. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  103070. return this.hasMesh(mesh);
  103071. };
  103072. /**
  103073. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  103074. * @param mesh The mesh to exclude from the glow layer
  103075. */
  103076. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  103077. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  103078. this._excludedMeshes.push(mesh.uniqueId);
  103079. }
  103080. };
  103081. /**
  103082. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  103083. * @param mesh The mesh to remove
  103084. */
  103085. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  103086. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  103087. if (index !== -1) {
  103088. this._excludedMeshes.splice(index, 1);
  103089. }
  103090. };
  103091. /**
  103092. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  103093. * @param mesh The mesh to include in the glow layer
  103094. */
  103095. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  103096. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  103097. this._includedOnlyMeshes.push(mesh.uniqueId);
  103098. }
  103099. };
  103100. /**
  103101. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  103102. * @param mesh The mesh to remove
  103103. */
  103104. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  103105. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  103106. if (index !== -1) {
  103107. this._includedOnlyMeshes.splice(index, 1);
  103108. }
  103109. };
  103110. /**
  103111. * Determine if a given mesh will be used in the glow layer
  103112. * @param mesh The mesh to test
  103113. * @returns true if the mesh will be highlighted by the current glow layer
  103114. */
  103115. GlowLayer.prototype.hasMesh = function (mesh) {
  103116. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103117. return false;
  103118. }
  103119. // Included Mesh
  103120. if (this._includedOnlyMeshes.length) {
  103121. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  103122. }
  103123. ;
  103124. // Excluded Mesh
  103125. if (this._excludedMeshes.length) {
  103126. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  103127. }
  103128. ;
  103129. return true;
  103130. };
  103131. /**
  103132. * Free any resources and references associated to a mesh.
  103133. * Internal use
  103134. * @param mesh The mesh to free.
  103135. * @hidden
  103136. */
  103137. GlowLayer.prototype._disposeMesh = function (mesh) {
  103138. this.removeIncludedOnlyMesh(mesh);
  103139. this.removeExcludedMesh(mesh);
  103140. };
  103141. /**
  103142. * Gets the class name of the effect layer
  103143. * @returns the string with the class name of the effect layer
  103144. */
  103145. GlowLayer.prototype.getClassName = function () {
  103146. return "GlowLayer";
  103147. };
  103148. /**
  103149. * Serializes this glow layer
  103150. * @returns a serialized glow layer object
  103151. */
  103152. GlowLayer.prototype.serialize = function () {
  103153. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103154. serializationObject.customType = "BABYLON.GlowLayer";
  103155. var index;
  103156. // Included meshes
  103157. serializationObject.includedMeshes = [];
  103158. if (this._includedOnlyMeshes.length) {
  103159. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  103160. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  103161. if (mesh) {
  103162. serializationObject.includedMeshes.push(mesh.id);
  103163. }
  103164. }
  103165. }
  103166. // Excluded meshes
  103167. serializationObject.excludedMeshes = [];
  103168. if (this._excludedMeshes.length) {
  103169. for (index = 0; index < this._excludedMeshes.length; index++) {
  103170. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  103171. if (mesh) {
  103172. serializationObject.excludedMeshes.push(mesh.id);
  103173. }
  103174. }
  103175. }
  103176. return serializationObject;
  103177. };
  103178. /**
  103179. * Creates a Glow Layer from parsed glow layer data
  103180. * @param parsedGlowLayer defines glow layer data
  103181. * @param scene defines the current scene
  103182. * @param rootUrl defines the root URL containing the glow layer information
  103183. * @returns a parsed Glow Layer
  103184. */
  103185. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  103186. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  103187. var index;
  103188. // Excluded meshes
  103189. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  103190. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  103191. if (mesh) {
  103192. gl.addExcludedMesh(mesh);
  103193. }
  103194. }
  103195. // Included meshes
  103196. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  103197. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  103198. if (mesh) {
  103199. gl.addIncludedOnlyMesh(mesh);
  103200. }
  103201. }
  103202. return gl;
  103203. };
  103204. /**
  103205. * Effect Name of the layer.
  103206. */
  103207. GlowLayer.EffectName = "GlowLayer";
  103208. /**
  103209. * The default blur kernel size used for the glow.
  103210. */
  103211. GlowLayer.DefaultBlurKernelSize = 32;
  103212. /**
  103213. * The default texture size ratio used for the glow.
  103214. */
  103215. GlowLayer.DefaultTextureRatio = 0.5;
  103216. __decorate([
  103217. BABYLON.serialize()
  103218. ], GlowLayer.prototype, "blurKernelSize", null);
  103219. __decorate([
  103220. BABYLON.serialize()
  103221. ], GlowLayer.prototype, "intensity", null);
  103222. __decorate([
  103223. BABYLON.serialize("options")
  103224. ], GlowLayer.prototype, "_options", void 0);
  103225. return GlowLayer;
  103226. }(BABYLON.EffectLayer));
  103227. BABYLON.GlowLayer = GlowLayer;
  103228. })(BABYLON || (BABYLON = {}));
  103229. //# sourceMappingURL=babylon.glowLayer.js.map
  103230. var BABYLON;
  103231. (function (BABYLON) {
  103232. /**
  103233. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  103234. */
  103235. var AssetTaskState;
  103236. (function (AssetTaskState) {
  103237. /**
  103238. * Initialization
  103239. */
  103240. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  103241. /**
  103242. * Running
  103243. */
  103244. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  103245. /**
  103246. * Done
  103247. */
  103248. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  103249. /**
  103250. * Error
  103251. */
  103252. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  103253. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  103254. /**
  103255. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  103256. */
  103257. var AbstractAssetTask = /** @class */ (function () {
  103258. /**
  103259. * Creates a new {BABYLON.AssetsManager}
  103260. * @param name defines the name of the task
  103261. */
  103262. function AbstractAssetTask(
  103263. /**
  103264. * Task name
  103265. */ name) {
  103266. this.name = name;
  103267. this._isCompleted = false;
  103268. this._taskState = AssetTaskState.INIT;
  103269. }
  103270. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  103271. /**
  103272. * Get if the task is completed
  103273. */
  103274. get: function () {
  103275. return this._isCompleted;
  103276. },
  103277. enumerable: true,
  103278. configurable: true
  103279. });
  103280. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  103281. /**
  103282. * Gets the current state of the task
  103283. */
  103284. get: function () {
  103285. return this._taskState;
  103286. },
  103287. enumerable: true,
  103288. configurable: true
  103289. });
  103290. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  103291. /**
  103292. * Gets the current error object (if task is in error)
  103293. */
  103294. get: function () {
  103295. return this._errorObject;
  103296. },
  103297. enumerable: true,
  103298. configurable: true
  103299. });
  103300. /**
  103301. * Internal only
  103302. * @hidden
  103303. */
  103304. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  103305. if (this._errorObject) {
  103306. return;
  103307. }
  103308. this._errorObject = {
  103309. message: message,
  103310. exception: exception
  103311. };
  103312. };
  103313. /**
  103314. * Execute the current task
  103315. * @param scene defines the scene where you want your assets to be loaded
  103316. * @param onSuccess is a callback called when the task is successfully executed
  103317. * @param onError is a callback called if an error occurs
  103318. */
  103319. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103320. var _this = this;
  103321. this._taskState = AssetTaskState.RUNNING;
  103322. this.runTask(scene, function () {
  103323. _this.onDoneCallback(onSuccess, onError);
  103324. }, function (msg, exception) {
  103325. _this.onErrorCallback(onError, msg, exception);
  103326. });
  103327. };
  103328. /**
  103329. * Execute the current task
  103330. * @param scene defines the scene where you want your assets to be loaded
  103331. * @param onSuccess is a callback called when the task is successfully executed
  103332. * @param onError is a callback called if an error occurs
  103333. */
  103334. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103335. throw new Error("runTask is not implemented");
  103336. };
  103337. /**
  103338. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  103339. * This can be used with failed tasks that have the reason for failure fixed.
  103340. */
  103341. AbstractAssetTask.prototype.reset = function () {
  103342. this._taskState = AssetTaskState.INIT;
  103343. };
  103344. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  103345. this._taskState = AssetTaskState.ERROR;
  103346. this._errorObject = {
  103347. message: message,
  103348. exception: exception
  103349. };
  103350. if (this.onError) {
  103351. this.onError(this, message, exception);
  103352. }
  103353. onError();
  103354. };
  103355. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  103356. try {
  103357. this._taskState = AssetTaskState.DONE;
  103358. this._isCompleted = true;
  103359. if (this.onSuccess) {
  103360. this.onSuccess(this);
  103361. }
  103362. onSuccess();
  103363. }
  103364. catch (e) {
  103365. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  103366. }
  103367. };
  103368. return AbstractAssetTask;
  103369. }());
  103370. BABYLON.AbstractAssetTask = AbstractAssetTask;
  103371. /**
  103372. * Class used to share progress information about assets loading
  103373. */
  103374. var AssetsProgressEvent = /** @class */ (function () {
  103375. /**
  103376. * Creates a {BABYLON.AssetsProgressEvent}
  103377. * @param remainingCount defines the number of remaining tasks to process
  103378. * @param totalCount defines the total number of tasks
  103379. * @param task defines the task that was just processed
  103380. */
  103381. function AssetsProgressEvent(remainingCount, totalCount, task) {
  103382. this.remainingCount = remainingCount;
  103383. this.totalCount = totalCount;
  103384. this.task = task;
  103385. }
  103386. return AssetsProgressEvent;
  103387. }());
  103388. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  103389. /**
  103390. * Define a task used by {BABYLON.AssetsManager} to load meshes
  103391. */
  103392. var MeshAssetTask = /** @class */ (function (_super) {
  103393. __extends(MeshAssetTask, _super);
  103394. /**
  103395. * Creates a new {BABYLON.MeshAssetTask}
  103396. * @param name defines the name of the task
  103397. * @param meshesNames defines the list of mesh's names you want to load
  103398. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  103399. * @param sceneFilename defines the filename of the scene to load from
  103400. */
  103401. function MeshAssetTask(
  103402. /**
  103403. * Defines the name of the task
  103404. */
  103405. name,
  103406. /**
  103407. * Defines the list of mesh's names you want to load
  103408. */
  103409. meshesNames,
  103410. /**
  103411. * Defines the root url to use as a base to load your meshes and associated resources
  103412. */
  103413. rootUrl,
  103414. /**
  103415. * Defines the filename of the scene to load from
  103416. */
  103417. sceneFilename) {
  103418. var _this = _super.call(this, name) || this;
  103419. _this.name = name;
  103420. _this.meshesNames = meshesNames;
  103421. _this.rootUrl = rootUrl;
  103422. _this.sceneFilename = sceneFilename;
  103423. return _this;
  103424. }
  103425. /**
  103426. * Execute the current task
  103427. * @param scene defines the scene where you want your assets to be loaded
  103428. * @param onSuccess is a callback called when the task is successfully executed
  103429. * @param onError is a callback called if an error occurs
  103430. */
  103431. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103432. var _this = this;
  103433. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  103434. _this.loadedMeshes = meshes;
  103435. _this.loadedParticleSystems = particleSystems;
  103436. _this.loadedSkeletons = skeletons;
  103437. onSuccess();
  103438. }, null, function (scene, message, exception) {
  103439. onError(message, exception);
  103440. });
  103441. };
  103442. return MeshAssetTask;
  103443. }(AbstractAssetTask));
  103444. BABYLON.MeshAssetTask = MeshAssetTask;
  103445. /**
  103446. * Define a task used by {BABYLON.AssetsManager} to load text content
  103447. */
  103448. var TextFileAssetTask = /** @class */ (function (_super) {
  103449. __extends(TextFileAssetTask, _super);
  103450. /**
  103451. * Creates a new TextFileAssetTask object
  103452. * @param name defines the name of the task
  103453. * @param url defines the location of the file to load
  103454. */
  103455. function TextFileAssetTask(
  103456. /**
  103457. * Defines the name of the task
  103458. */
  103459. name,
  103460. /**
  103461. * Defines the location of the file to load
  103462. */
  103463. url) {
  103464. var _this = _super.call(this, name) || this;
  103465. _this.name = name;
  103466. _this.url = url;
  103467. return _this;
  103468. }
  103469. /**
  103470. * Execute the current task
  103471. * @param scene defines the scene where you want your assets to be loaded
  103472. * @param onSuccess is a callback called when the task is successfully executed
  103473. * @param onError is a callback called if an error occurs
  103474. */
  103475. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103476. var _this = this;
  103477. scene._loadFile(this.url, function (data) {
  103478. _this.text = data;
  103479. onSuccess();
  103480. }, undefined, false, false, function (request, exception) {
  103481. if (request) {
  103482. onError(request.status + " " + request.statusText, exception);
  103483. }
  103484. });
  103485. };
  103486. return TextFileAssetTask;
  103487. }(AbstractAssetTask));
  103488. BABYLON.TextFileAssetTask = TextFileAssetTask;
  103489. /**
  103490. * Define a task used by {BABYLON.AssetsManager} to load binary data
  103491. */
  103492. var BinaryFileAssetTask = /** @class */ (function (_super) {
  103493. __extends(BinaryFileAssetTask, _super);
  103494. /**
  103495. * Creates a new BinaryFileAssetTask object
  103496. * @param name defines the name of the new task
  103497. * @param url defines the location of the file to load
  103498. */
  103499. function BinaryFileAssetTask(
  103500. /**
  103501. * Defines the name of the task
  103502. */
  103503. name,
  103504. /**
  103505. * Defines the location of the file to load
  103506. */
  103507. url) {
  103508. var _this = _super.call(this, name) || this;
  103509. _this.name = name;
  103510. _this.url = url;
  103511. return _this;
  103512. }
  103513. /**
  103514. * Execute the current task
  103515. * @param scene defines the scene where you want your assets to be loaded
  103516. * @param onSuccess is a callback called when the task is successfully executed
  103517. * @param onError is a callback called if an error occurs
  103518. */
  103519. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103520. var _this = this;
  103521. scene._loadFile(this.url, function (data) {
  103522. _this.data = data;
  103523. onSuccess();
  103524. }, undefined, true, true, function (request, exception) {
  103525. if (request) {
  103526. onError(request.status + " " + request.statusText, exception);
  103527. }
  103528. });
  103529. };
  103530. return BinaryFileAssetTask;
  103531. }(AbstractAssetTask));
  103532. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  103533. /**
  103534. * Define a task used by {BABYLON.AssetsManager} to load images
  103535. */
  103536. var ImageAssetTask = /** @class */ (function (_super) {
  103537. __extends(ImageAssetTask, _super);
  103538. /**
  103539. * Creates a new ImageAssetTask
  103540. * @param name defines the name of the task
  103541. * @param url defines the location of the image to load
  103542. */
  103543. function ImageAssetTask(
  103544. /**
  103545. * Defines the name of the task
  103546. */
  103547. name,
  103548. /**
  103549. * Defines the location of the image to load
  103550. */
  103551. url) {
  103552. var _this = _super.call(this, name) || this;
  103553. _this.name = name;
  103554. _this.url = url;
  103555. return _this;
  103556. }
  103557. /**
  103558. * Execute the current task
  103559. * @param scene defines the scene where you want your assets to be loaded
  103560. * @param onSuccess is a callback called when the task is successfully executed
  103561. * @param onError is a callback called if an error occurs
  103562. */
  103563. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103564. var _this = this;
  103565. var img = new Image();
  103566. BABYLON.Tools.SetCorsBehavior(this.url, img);
  103567. img.onload = function () {
  103568. _this.image = img;
  103569. onSuccess();
  103570. };
  103571. img.onerror = function (err) {
  103572. onError("Error loading image", err);
  103573. };
  103574. img.src = this.url;
  103575. };
  103576. return ImageAssetTask;
  103577. }(AbstractAssetTask));
  103578. BABYLON.ImageAssetTask = ImageAssetTask;
  103579. /**
  103580. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  103581. */
  103582. var TextureAssetTask = /** @class */ (function (_super) {
  103583. __extends(TextureAssetTask, _super);
  103584. /**
  103585. * Creates a new TextureAssetTask object
  103586. * @param name defines the name of the task
  103587. * @param url defines the location of the file to load
  103588. * @param noMipmap defines if mipmap should not be generated (default is false)
  103589. * @param invertY defines if texture must be inverted on Y axis (default is false)
  103590. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  103591. */
  103592. function TextureAssetTask(
  103593. /**
  103594. * Defines the name of the task
  103595. */
  103596. name,
  103597. /**
  103598. * Defines the location of the file to load
  103599. */
  103600. url,
  103601. /**
  103602. * Defines if mipmap should not be generated (default is false)
  103603. */
  103604. noMipmap,
  103605. /**
  103606. * Defines if texture must be inverted on Y axis (default is false)
  103607. */
  103608. invertY,
  103609. /**
  103610. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  103611. */
  103612. samplingMode) {
  103613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103614. var _this = _super.call(this, name) || this;
  103615. _this.name = name;
  103616. _this.url = url;
  103617. _this.noMipmap = noMipmap;
  103618. _this.invertY = invertY;
  103619. _this.samplingMode = samplingMode;
  103620. return _this;
  103621. }
  103622. /**
  103623. * Execute the current task
  103624. * @param scene defines the scene where you want your assets to be loaded
  103625. * @param onSuccess is a callback called when the task is successfully executed
  103626. * @param onError is a callback called if an error occurs
  103627. */
  103628. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103629. var onload = function () {
  103630. onSuccess();
  103631. };
  103632. var onerror = function (message, exception) {
  103633. onError(message, exception);
  103634. };
  103635. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  103636. };
  103637. return TextureAssetTask;
  103638. }(AbstractAssetTask));
  103639. BABYLON.TextureAssetTask = TextureAssetTask;
  103640. /**
  103641. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  103642. */
  103643. var CubeTextureAssetTask = /** @class */ (function (_super) {
  103644. __extends(CubeTextureAssetTask, _super);
  103645. /**
  103646. * Creates a new CubeTextureAssetTask
  103647. * @param name defines the name of the task
  103648. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  103649. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  103650. * @param noMipmap defines if mipmaps should not be generated (default is false)
  103651. * @param files defines the explicit list of files (undefined by default)
  103652. */
  103653. function CubeTextureAssetTask(
  103654. /**
  103655. * Defines the name of the task
  103656. */
  103657. name,
  103658. /**
  103659. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  103660. */
  103661. url,
  103662. /**
  103663. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  103664. */
  103665. extensions,
  103666. /**
  103667. * Defines if mipmaps should not be generated (default is false)
  103668. */
  103669. noMipmap,
  103670. /**
  103671. * Defines the explicit list of files (undefined by default)
  103672. */
  103673. files) {
  103674. var _this = _super.call(this, name) || this;
  103675. _this.name = name;
  103676. _this.url = url;
  103677. _this.extensions = extensions;
  103678. _this.noMipmap = noMipmap;
  103679. _this.files = files;
  103680. return _this;
  103681. }
  103682. /**
  103683. * Execute the current task
  103684. * @param scene defines the scene where you want your assets to be loaded
  103685. * @param onSuccess is a callback called when the task is successfully executed
  103686. * @param onError is a callback called if an error occurs
  103687. */
  103688. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103689. var onload = function () {
  103690. onSuccess();
  103691. };
  103692. var onerror = function (message, exception) {
  103693. onError(message, exception);
  103694. };
  103695. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  103696. };
  103697. return CubeTextureAssetTask;
  103698. }(AbstractAssetTask));
  103699. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  103700. /**
  103701. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  103702. */
  103703. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  103704. __extends(HDRCubeTextureAssetTask, _super);
  103705. /**
  103706. * Creates a new HDRCubeTextureAssetTask object
  103707. * @param name defines the name of the task
  103708. * @param url defines the location of the file to load
  103709. * @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.
  103710. * @param noMipmap defines if mipmaps should not be generated (default is false)
  103711. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  103712. * @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)
  103713. * @param reserved Internal use only
  103714. */
  103715. function HDRCubeTextureAssetTask(
  103716. /**
  103717. * Defines the name of the task
  103718. */
  103719. name,
  103720. /**
  103721. * Defines the location of the file to load
  103722. */
  103723. url,
  103724. /**
  103725. * Defines the desired size (the more it increases the longer the generation will be)
  103726. */
  103727. size,
  103728. /**
  103729. * Defines if mipmaps should not be generated (default is false)
  103730. */
  103731. noMipmap,
  103732. /**
  103733. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  103734. */
  103735. generateHarmonics,
  103736. /**
  103737. * 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)
  103738. */
  103739. gammaSpace,
  103740. /**
  103741. * Internal Use Only
  103742. */
  103743. reserved) {
  103744. if (noMipmap === void 0) { noMipmap = false; }
  103745. if (generateHarmonics === void 0) { generateHarmonics = true; }
  103746. if (gammaSpace === void 0) { gammaSpace = false; }
  103747. if (reserved === void 0) { reserved = false; }
  103748. var _this = _super.call(this, name) || this;
  103749. _this.name = name;
  103750. _this.url = url;
  103751. _this.size = size;
  103752. _this.noMipmap = noMipmap;
  103753. _this.generateHarmonics = generateHarmonics;
  103754. _this.gammaSpace = gammaSpace;
  103755. _this.reserved = reserved;
  103756. return _this;
  103757. }
  103758. /**
  103759. * Execute the current task
  103760. * @param scene defines the scene where you want your assets to be loaded
  103761. * @param onSuccess is a callback called when the task is successfully executed
  103762. * @param onError is a callback called if an error occurs
  103763. */
  103764. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103765. var onload = function () {
  103766. onSuccess();
  103767. };
  103768. var onerror = function (message, exception) {
  103769. onError(message, exception);
  103770. };
  103771. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  103772. };
  103773. return HDRCubeTextureAssetTask;
  103774. }(AbstractAssetTask));
  103775. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  103776. /**
  103777. * This class can be used to easily import assets into a scene
  103778. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  103779. */
  103780. var AssetsManager = /** @class */ (function () {
  103781. /**
  103782. * Creates a new AssetsManager
  103783. * @param scene defines the scene to work on
  103784. */
  103785. function AssetsManager(scene) {
  103786. this._isLoading = false;
  103787. this._tasks = new Array();
  103788. this._waitingTasksCount = 0;
  103789. this._totalTasksCount = 0;
  103790. /**
  103791. * Observable called when all tasks are processed
  103792. */
  103793. this.onTaskSuccessObservable = new BABYLON.Observable();
  103794. /**
  103795. * Observable called when a task had an error
  103796. */
  103797. this.onTaskErrorObservable = new BABYLON.Observable();
  103798. /**
  103799. * Observable called when a task is successful
  103800. */
  103801. this.onTasksDoneObservable = new BABYLON.Observable();
  103802. /**
  103803. * Observable called when a task is done (whatever the result is)
  103804. */
  103805. this.onProgressObservable = new BABYLON.Observable();
  103806. /**
  103807. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  103808. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  103809. */
  103810. this.useDefaultLoadingScreen = true;
  103811. this._scene = scene;
  103812. }
  103813. /**
  103814. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  103815. * @param taskName defines the name of the new task
  103816. * @param meshesNames defines the name of meshes to load
  103817. * @param rootUrl defines the root url to use to locate files
  103818. * @param sceneFilename defines the filename of the scene file
  103819. * @returns a new {BABYLON.MeshAssetTask} object
  103820. */
  103821. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  103822. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  103823. this._tasks.push(task);
  103824. return task;
  103825. };
  103826. /**
  103827. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  103828. * @param taskName defines the name of the new task
  103829. * @param url defines the url of the file to load
  103830. * @returns a new {BABYLON.TextFileAssetTask} object
  103831. */
  103832. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  103833. var task = new TextFileAssetTask(taskName, url);
  103834. this._tasks.push(task);
  103835. return task;
  103836. };
  103837. /**
  103838. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  103839. * @param taskName defines the name of the new task
  103840. * @param url defines the url of the file to load
  103841. * @returns a new {BABYLON.BinaryFileAssetTask} object
  103842. */
  103843. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  103844. var task = new BinaryFileAssetTask(taskName, url);
  103845. this._tasks.push(task);
  103846. return task;
  103847. };
  103848. /**
  103849. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  103850. * @param taskName defines the name of the new task
  103851. * @param url defines the url of the file to load
  103852. * @returns a new {BABYLON.ImageAssetTask} object
  103853. */
  103854. AssetsManager.prototype.addImageTask = function (taskName, url) {
  103855. var task = new ImageAssetTask(taskName, url);
  103856. this._tasks.push(task);
  103857. return task;
  103858. };
  103859. /**
  103860. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  103861. * @param taskName defines the name of the new task
  103862. * @param url defines the url of the file to load
  103863. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103864. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  103865. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  103866. * @returns a new {BABYLON.TextureAssetTask} object
  103867. */
  103868. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  103869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103870. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  103871. this._tasks.push(task);
  103872. return task;
  103873. };
  103874. /**
  103875. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  103876. * @param taskName defines the name of the new task
  103877. * @param url defines the url of the file to load
  103878. * @param extensions defines the extension to use to load the cube map (can be null)
  103879. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103880. * @param files defines the list of files to load (can be null)
  103881. * @returns a new {BABYLON.CubeTextureAssetTask} object
  103882. */
  103883. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  103884. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  103885. this._tasks.push(task);
  103886. return task;
  103887. };
  103888. /**
  103889. *
  103890. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  103891. * @param taskName defines the name of the new task
  103892. * @param url defines the url of the file to load
  103893. * @param size defines the size you want for the cubemap (can be null)
  103894. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103895. * @param generateHarmonics defines if you want to automatically generate (true by default)
  103896. * @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)
  103897. * @param reserved Internal use only
  103898. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  103899. */
  103900. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  103901. if (noMipmap === void 0) { noMipmap = false; }
  103902. if (generateHarmonics === void 0) { generateHarmonics = true; }
  103903. if (gammaSpace === void 0) { gammaSpace = false; }
  103904. if (reserved === void 0) { reserved = false; }
  103905. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  103906. this._tasks.push(task);
  103907. return task;
  103908. };
  103909. /**
  103910. * Remove a task from the assets manager.
  103911. * @param task the task to remove
  103912. */
  103913. AssetsManager.prototype.removeTask = function (task) {
  103914. var index = this._tasks.indexOf(task);
  103915. if (index > -1) {
  103916. this._tasks.splice(index, 1);
  103917. }
  103918. };
  103919. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  103920. this._waitingTasksCount--;
  103921. try {
  103922. if (this.onProgress) {
  103923. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  103924. }
  103925. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  103926. }
  103927. catch (e) {
  103928. BABYLON.Tools.Error("Error running progress callbacks.");
  103929. console.log(e);
  103930. }
  103931. if (this._waitingTasksCount === 0) {
  103932. try {
  103933. if (this.onFinish) {
  103934. this.onFinish(this._tasks);
  103935. }
  103936. // Let's remove successfull tasks
  103937. var currentTasks = this._tasks.slice();
  103938. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  103939. var task = currentTasks_1[_i];
  103940. if (task.taskState === AssetTaskState.DONE) {
  103941. var index = this._tasks.indexOf(task);
  103942. if (index > -1) {
  103943. this._tasks.splice(index, 1);
  103944. }
  103945. }
  103946. }
  103947. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103948. }
  103949. catch (e) {
  103950. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  103951. console.log(e);
  103952. }
  103953. this._isLoading = false;
  103954. this._scene.getEngine().hideLoadingUI();
  103955. }
  103956. };
  103957. AssetsManager.prototype._runTask = function (task) {
  103958. var _this = this;
  103959. var done = function () {
  103960. try {
  103961. if (_this.onTaskSuccess) {
  103962. _this.onTaskSuccess(task);
  103963. }
  103964. _this.onTaskSuccessObservable.notifyObservers(task);
  103965. _this._decreaseWaitingTasksCount(task);
  103966. }
  103967. catch (e) {
  103968. error("Error executing task success callbacks", e);
  103969. }
  103970. };
  103971. var error = function (message, exception) {
  103972. task._setErrorObject(message, exception);
  103973. if (_this.onTaskError) {
  103974. _this.onTaskError(task);
  103975. }
  103976. _this.onTaskErrorObservable.notifyObservers(task);
  103977. _this._decreaseWaitingTasksCount(task);
  103978. };
  103979. task.run(this._scene, done, error);
  103980. };
  103981. /**
  103982. * Reset the {BABYLON.AssetsManager} and remove all tasks
  103983. * @return the current instance of the {BABYLON.AssetsManager}
  103984. */
  103985. AssetsManager.prototype.reset = function () {
  103986. this._isLoading = false;
  103987. this._tasks = new Array();
  103988. return this;
  103989. };
  103990. /**
  103991. * Start the loading process
  103992. * @return the current instance of the {BABYLON.AssetsManager}
  103993. */
  103994. AssetsManager.prototype.load = function () {
  103995. if (this._isLoading) {
  103996. return this;
  103997. }
  103998. this._isLoading = true;
  103999. this._waitingTasksCount = this._tasks.length;
  104000. this._totalTasksCount = this._tasks.length;
  104001. if (this._waitingTasksCount === 0) {
  104002. this._isLoading = false;
  104003. if (this.onFinish) {
  104004. this.onFinish(this._tasks);
  104005. }
  104006. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104007. return this;
  104008. }
  104009. if (this.useDefaultLoadingScreen) {
  104010. this._scene.getEngine().displayLoadingUI();
  104011. }
  104012. for (var index = 0; index < this._tasks.length; index++) {
  104013. var task = this._tasks[index];
  104014. if (task.taskState === AssetTaskState.INIT) {
  104015. this._runTask(task);
  104016. }
  104017. }
  104018. return this;
  104019. };
  104020. return AssetsManager;
  104021. }());
  104022. BABYLON.AssetsManager = AssetsManager;
  104023. })(BABYLON || (BABYLON = {}));
  104024. //# sourceMappingURL=babylon.assetsManager.js.map
  104025. var BABYLON;
  104026. (function (BABYLON) {
  104027. var serializedGeometries = [];
  104028. var serializeGeometry = function (geometry, serializationGeometries) {
  104029. if (serializedGeometries[geometry.id]) {
  104030. return;
  104031. }
  104032. if (geometry.doNotSerialize) {
  104033. return;
  104034. }
  104035. if (geometry instanceof BABYLON.BoxGeometry) {
  104036. serializationGeometries.boxes.push(geometry.serialize());
  104037. }
  104038. else if (geometry instanceof BABYLON.SphereGeometry) {
  104039. serializationGeometries.spheres.push(geometry.serialize());
  104040. }
  104041. else if (geometry instanceof BABYLON.CylinderGeometry) {
  104042. serializationGeometries.cylinders.push(geometry.serialize());
  104043. }
  104044. else if (geometry instanceof BABYLON.TorusGeometry) {
  104045. serializationGeometries.toruses.push(geometry.serialize());
  104046. }
  104047. else if (geometry instanceof BABYLON.GroundGeometry) {
  104048. serializationGeometries.grounds.push(geometry.serialize());
  104049. }
  104050. else if (geometry instanceof BABYLON.Plane) {
  104051. serializationGeometries.planes.push(geometry.serialize());
  104052. }
  104053. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  104054. serializationGeometries.torusKnots.push(geometry.serialize());
  104055. }
  104056. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  104057. throw new Error("Unknown primitive type");
  104058. }
  104059. else {
  104060. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  104061. }
  104062. serializedGeometries[geometry.id] = true;
  104063. };
  104064. var serializeMesh = function (mesh, serializationScene) {
  104065. var serializationObject = {};
  104066. // Geometry
  104067. var geometry = mesh._geometry;
  104068. if (geometry) {
  104069. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  104070. // 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
  104071. serializeGeometry(geometry, serializationScene.geometries);
  104072. }
  104073. }
  104074. // Custom
  104075. if (mesh.serialize) {
  104076. mesh.serialize(serializationObject);
  104077. }
  104078. return serializationObject;
  104079. };
  104080. var finalizeSingleMesh = function (mesh, serializationObject) {
  104081. //only works if the mesh is already loaded
  104082. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104083. //serialize material
  104084. if (mesh.material) {
  104085. if (mesh.material instanceof BABYLON.MultiMaterial) {
  104086. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  104087. serializationObject.materials = serializationObject.materials || [];
  104088. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104089. serializationObject.multiMaterials.push(mesh.material.serialize());
  104090. var _loop_1 = function (submaterial) {
  104091. if (submaterial) {
  104092. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  104093. serializationObject.materials.push(submaterial.serialize());
  104094. }
  104095. }
  104096. };
  104097. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  104098. var submaterial = _a[_i];
  104099. _loop_1(submaterial);
  104100. }
  104101. }
  104102. }
  104103. else {
  104104. serializationObject.materials = serializationObject.materials || [];
  104105. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104106. serializationObject.materials.push(mesh.material.serialize());
  104107. }
  104108. }
  104109. }
  104110. //serialize geometry
  104111. var geometry = mesh._geometry;
  104112. if (geometry) {
  104113. if (!serializationObject.geometries) {
  104114. serializationObject.geometries = {};
  104115. serializationObject.geometries.boxes = [];
  104116. serializationObject.geometries.spheres = [];
  104117. serializationObject.geometries.cylinders = [];
  104118. serializationObject.geometries.toruses = [];
  104119. serializationObject.geometries.grounds = [];
  104120. serializationObject.geometries.planes = [];
  104121. serializationObject.geometries.torusKnots = [];
  104122. serializationObject.geometries.vertexData = [];
  104123. }
  104124. serializeGeometry(geometry, serializationObject.geometries);
  104125. }
  104126. // Skeletons
  104127. if (mesh.skeleton) {
  104128. serializationObject.skeletons = serializationObject.skeletons || [];
  104129. serializationObject.skeletons.push(mesh.skeleton.serialize());
  104130. }
  104131. //serialize the actual mesh
  104132. serializationObject.meshes = serializationObject.meshes || [];
  104133. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104134. }
  104135. };
  104136. var SceneSerializer = /** @class */ (function () {
  104137. function SceneSerializer() {
  104138. }
  104139. SceneSerializer.ClearCache = function () {
  104140. serializedGeometries = [];
  104141. };
  104142. SceneSerializer.Serialize = function (scene) {
  104143. var serializationObject = {};
  104144. SceneSerializer.ClearCache();
  104145. // Scene
  104146. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  104147. serializationObject.autoClear = scene.autoClear;
  104148. serializationObject.clearColor = scene.clearColor.asArray();
  104149. serializationObject.ambientColor = scene.ambientColor.asArray();
  104150. serializationObject.gravity = scene.gravity.asArray();
  104151. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  104152. serializationObject.workerCollisions = scene.workerCollisions;
  104153. // Fog
  104154. if (scene.fogMode && scene.fogMode !== 0) {
  104155. serializationObject.fogMode = scene.fogMode;
  104156. serializationObject.fogColor = scene.fogColor.asArray();
  104157. serializationObject.fogStart = scene.fogStart;
  104158. serializationObject.fogEnd = scene.fogEnd;
  104159. serializationObject.fogDensity = scene.fogDensity;
  104160. }
  104161. //Physics
  104162. if (scene.isPhysicsEnabled()) {
  104163. var physicEngine = scene.getPhysicsEngine();
  104164. if (physicEngine) {
  104165. serializationObject.physicsEnabled = true;
  104166. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  104167. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  104168. }
  104169. }
  104170. // Metadata
  104171. if (scene.metadata) {
  104172. serializationObject.metadata = scene.metadata;
  104173. }
  104174. // Morph targets
  104175. serializationObject.morphTargetManagers = [];
  104176. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  104177. var abstractMesh = _a[_i];
  104178. var manager = abstractMesh.morphTargetManager;
  104179. if (manager) {
  104180. serializationObject.morphTargetManagers.push(manager.serialize());
  104181. }
  104182. }
  104183. // Lights
  104184. serializationObject.lights = [];
  104185. var index;
  104186. var light;
  104187. for (index = 0; index < scene.lights.length; index++) {
  104188. light = scene.lights[index];
  104189. if (!light.doNotSerialize) {
  104190. serializationObject.lights.push(light.serialize());
  104191. }
  104192. }
  104193. // Cameras
  104194. serializationObject.cameras = [];
  104195. for (index = 0; index < scene.cameras.length; index++) {
  104196. var camera = scene.cameras[index];
  104197. if (!camera.doNotSerialize) {
  104198. serializationObject.cameras.push(camera.serialize());
  104199. }
  104200. }
  104201. if (scene.activeCamera) {
  104202. serializationObject.activeCameraID = scene.activeCamera.id;
  104203. }
  104204. // Animations
  104205. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  104206. // Materials
  104207. serializationObject.materials = [];
  104208. serializationObject.multiMaterials = [];
  104209. var material;
  104210. for (index = 0; index < scene.materials.length; index++) {
  104211. material = scene.materials[index];
  104212. if (!material.doNotSerialize) {
  104213. serializationObject.materials.push(material.serialize());
  104214. }
  104215. }
  104216. // MultiMaterials
  104217. serializationObject.multiMaterials = [];
  104218. for (index = 0; index < scene.multiMaterials.length; index++) {
  104219. var multiMaterial = scene.multiMaterials[index];
  104220. serializationObject.multiMaterials.push(multiMaterial.serialize());
  104221. }
  104222. // Environment texture
  104223. if (scene.environmentTexture) {
  104224. serializationObject.environmentTexture = scene.environmentTexture.name;
  104225. }
  104226. // Skeletons
  104227. serializationObject.skeletons = [];
  104228. for (index = 0; index < scene.skeletons.length; index++) {
  104229. var skeleton = scene.skeletons[index];
  104230. if (!skeleton.doNotSerialize) {
  104231. serializationObject.skeletons.push(skeleton.serialize());
  104232. }
  104233. }
  104234. // Transform nodes
  104235. serializationObject.transformNodes = [];
  104236. for (index = 0; index < scene.transformNodes.length; index++) {
  104237. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  104238. }
  104239. // Geometries
  104240. serializationObject.geometries = {};
  104241. serializationObject.geometries.boxes = [];
  104242. serializationObject.geometries.spheres = [];
  104243. serializationObject.geometries.cylinders = [];
  104244. serializationObject.geometries.toruses = [];
  104245. serializationObject.geometries.grounds = [];
  104246. serializationObject.geometries.planes = [];
  104247. serializationObject.geometries.torusKnots = [];
  104248. serializationObject.geometries.vertexData = [];
  104249. serializedGeometries = [];
  104250. var geometries = scene.getGeometries();
  104251. for (index = 0; index < geometries.length; index++) {
  104252. var geometry = geometries[index];
  104253. if (geometry.isReady()) {
  104254. serializeGeometry(geometry, serializationObject.geometries);
  104255. }
  104256. }
  104257. // Meshes
  104258. serializationObject.meshes = [];
  104259. for (index = 0; index < scene.meshes.length; index++) {
  104260. var abstractMesh = scene.meshes[index];
  104261. if (abstractMesh instanceof BABYLON.Mesh) {
  104262. var mesh = abstractMesh;
  104263. if (!mesh.doNotSerialize) {
  104264. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104265. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104266. }
  104267. }
  104268. }
  104269. }
  104270. // Particles Systems
  104271. serializationObject.particleSystems = [];
  104272. for (index = 0; index < scene.particleSystems.length; index++) {
  104273. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  104274. }
  104275. // Action Manager
  104276. if (scene.actionManager) {
  104277. serializationObject.actions = scene.actionManager.serialize("scene");
  104278. }
  104279. // Audio
  104280. serializationObject.sounds = [];
  104281. for (index = 0; index < scene.soundTracks.length; index++) {
  104282. var soundtrack = scene.soundTracks[index];
  104283. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  104284. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  104285. }
  104286. }
  104287. // Components
  104288. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  104289. var component = _c[_b];
  104290. component.serialize(serializationObject);
  104291. }
  104292. return serializationObject;
  104293. };
  104294. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  104295. if (withParents === void 0) { withParents = false; }
  104296. if (withChildren === void 0) { withChildren = false; }
  104297. var serializationObject = {};
  104298. SceneSerializer.ClearCache();
  104299. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  104300. if (withParents || withChildren) {
  104301. //deliberate for loop! not for each, appended should be processed as well.
  104302. for (var i = 0; i < toSerialize.length; ++i) {
  104303. if (withChildren) {
  104304. toSerialize[i].getDescendants().forEach(function (node) {
  104305. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  104306. toSerialize.push(node);
  104307. }
  104308. });
  104309. }
  104310. //make sure the array doesn't contain the object already
  104311. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  104312. toSerialize.push(toSerialize[i].parent);
  104313. }
  104314. }
  104315. }
  104316. toSerialize.forEach(function (mesh) {
  104317. finalizeSingleMesh(mesh, serializationObject);
  104318. });
  104319. return serializationObject;
  104320. };
  104321. return SceneSerializer;
  104322. }());
  104323. BABYLON.SceneSerializer = SceneSerializer;
  104324. })(BABYLON || (BABYLON = {}));
  104325. //# sourceMappingURL=babylon.sceneSerializer.js.map
  104326. var BABYLON;
  104327. (function (BABYLON) {
  104328. /**
  104329. * Class used to generate realtime reflection / refraction cube textures
  104330. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  104331. */
  104332. var ReflectionProbe = /** @class */ (function () {
  104333. /**
  104334. * Creates a new reflection probe
  104335. * @param name defines the name of the probe
  104336. * @param size defines the texture resolution (for each face)
  104337. * @param scene defines the hosting scene
  104338. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  104339. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  104340. */
  104341. function ReflectionProbe(
  104342. /** defines the name of the probe */
  104343. name, size, scene, generateMipMaps, useFloat) {
  104344. if (generateMipMaps === void 0) { generateMipMaps = true; }
  104345. if (useFloat === void 0) { useFloat = false; }
  104346. var _this = this;
  104347. this.name = name;
  104348. this._viewMatrix = BABYLON.Matrix.Identity();
  104349. this._target = BABYLON.Vector3.Zero();
  104350. this._add = BABYLON.Vector3.Zero();
  104351. this._invertYAxis = false;
  104352. /** Gets or sets probe position (center of the cube map) */
  104353. this.position = BABYLON.Vector3.Zero();
  104354. this._scene = scene;
  104355. // Create the scene field if not exist.
  104356. if (!this._scene.reflectionProbes) {
  104357. this._scene.reflectionProbes = new Array();
  104358. }
  104359. this._scene.reflectionProbes.push(this);
  104360. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  104361. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  104362. switch (faceIndex) {
  104363. case 0:
  104364. _this._add.copyFromFloats(1, 0, 0);
  104365. break;
  104366. case 1:
  104367. _this._add.copyFromFloats(-1, 0, 0);
  104368. break;
  104369. case 2:
  104370. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  104371. break;
  104372. case 3:
  104373. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  104374. break;
  104375. case 4:
  104376. _this._add.copyFromFloats(0, 0, 1);
  104377. break;
  104378. case 5:
  104379. _this._add.copyFromFloats(0, 0, -1);
  104380. break;
  104381. }
  104382. if (_this._attachedMesh) {
  104383. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  104384. }
  104385. _this.position.addToRef(_this._add, _this._target);
  104386. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  104387. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  104388. scene._forcedViewPosition = _this.position;
  104389. });
  104390. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  104391. scene._forcedViewPosition = null;
  104392. scene.updateTransformMatrix(true);
  104393. });
  104394. if (scene.activeCamera) {
  104395. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  104396. }
  104397. }
  104398. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  104399. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  104400. get: function () {
  104401. return this._renderTargetTexture.samples;
  104402. },
  104403. set: function (value) {
  104404. this._renderTargetTexture.samples = value;
  104405. },
  104406. enumerable: true,
  104407. configurable: true
  104408. });
  104409. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  104410. /** Gets or sets the refresh rate to use (on every frame by default) */
  104411. get: function () {
  104412. return this._renderTargetTexture.refreshRate;
  104413. },
  104414. set: function (value) {
  104415. this._renderTargetTexture.refreshRate = value;
  104416. },
  104417. enumerable: true,
  104418. configurable: true
  104419. });
  104420. /**
  104421. * Gets the hosting scene
  104422. * @returns a Scene
  104423. */
  104424. ReflectionProbe.prototype.getScene = function () {
  104425. return this._scene;
  104426. };
  104427. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  104428. /** Gets the internal CubeTexture used to render to */
  104429. get: function () {
  104430. return this._renderTargetTexture;
  104431. },
  104432. enumerable: true,
  104433. configurable: true
  104434. });
  104435. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  104436. /** Gets the list of meshes to render */
  104437. get: function () {
  104438. return this._renderTargetTexture.renderList;
  104439. },
  104440. enumerable: true,
  104441. configurable: true
  104442. });
  104443. /**
  104444. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  104445. * @param mesh defines the mesh to attach to
  104446. */
  104447. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  104448. this._attachedMesh = mesh;
  104449. };
  104450. /**
  104451. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  104452. * @param renderingGroupId The rendering group id corresponding to its index
  104453. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  104454. */
  104455. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  104456. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  104457. };
  104458. /**
  104459. * Clean all associated resources
  104460. */
  104461. ReflectionProbe.prototype.dispose = function () {
  104462. var index = this._scene.reflectionProbes.indexOf(this);
  104463. if (index !== -1) {
  104464. // Remove from the scene if found
  104465. this._scene.reflectionProbes.splice(index, 1);
  104466. }
  104467. if (this._renderTargetTexture) {
  104468. this._renderTargetTexture.dispose();
  104469. this._renderTargetTexture = null;
  104470. }
  104471. };
  104472. return ReflectionProbe;
  104473. }());
  104474. BABYLON.ReflectionProbe = ReflectionProbe;
  104475. })(BABYLON || (BABYLON = {}));
  104476. //# sourceMappingURL=babylon.reflectionProbe.js.map
  104477. var BABYLON;
  104478. (function (BABYLON) {
  104479. /**
  104480. * Defines the layer scene component responsible to manage any layers
  104481. * in a given scene.
  104482. */
  104483. var LayerSceneComponent = /** @class */ (function () {
  104484. /**
  104485. * Creates a new instance of the component for the given scene
  104486. * @param scene Defines the scene to register the component in
  104487. */
  104488. function LayerSceneComponent(scene) {
  104489. /**
  104490. * The component name helpfull to identify the component in the list of scene components.
  104491. */
  104492. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  104493. this.scene = scene;
  104494. this._engine = scene.getEngine();
  104495. scene.layers = new Array();
  104496. }
  104497. /**
  104498. * Registers the component in a given scene
  104499. */
  104500. LayerSceneComponent.prototype.register = function () {
  104501. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  104502. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  104503. };
  104504. /**
  104505. * Rebuilds the elements related to this component in case of
  104506. * context lost for instance.
  104507. */
  104508. LayerSceneComponent.prototype.rebuild = function () {
  104509. var layers = this.scene.layers;
  104510. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104511. var layer = layers_1[_i];
  104512. layer._rebuild();
  104513. }
  104514. };
  104515. /**
  104516. * Disposes the component and the associated ressources.
  104517. */
  104518. LayerSceneComponent.prototype.dispose = function () {
  104519. var layers = this.scene.layers;
  104520. while (layers.length) {
  104521. layers[0].dispose();
  104522. }
  104523. };
  104524. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  104525. var layers = this.scene.layers;
  104526. if (layers.length) {
  104527. this._engine.setDepthBuffer(false);
  104528. var cameraLayerMask = camera.layerMask;
  104529. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104530. var layer = layers_2[_i];
  104531. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  104532. layer.render();
  104533. }
  104534. }
  104535. this._engine.setDepthBuffer(true);
  104536. }
  104537. };
  104538. LayerSceneComponent.prototype._drawBackground = function (camera) {
  104539. this._draw(camera, true);
  104540. };
  104541. LayerSceneComponent.prototype._drawForeground = function (camera) {
  104542. this._draw(camera, false);
  104543. };
  104544. return LayerSceneComponent;
  104545. }());
  104546. BABYLON.LayerSceneComponent = LayerSceneComponent;
  104547. })(BABYLON || (BABYLON = {}));
  104548. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  104549. var BABYLON;
  104550. (function (BABYLON) {
  104551. var Layer = /** @class */ (function () {
  104552. function Layer(name, imgUrl, scene, isBackground, color) {
  104553. this.name = name;
  104554. this.scale = new BABYLON.Vector2(1, 1);
  104555. this.offset = new BABYLON.Vector2(0, 0);
  104556. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  104557. this.layerMask = 0x0FFFFFFF;
  104558. this._vertexBuffers = {};
  104559. // Events
  104560. /**
  104561. * An event triggered when the layer is disposed.
  104562. */
  104563. this.onDisposeObservable = new BABYLON.Observable();
  104564. /**
  104565. * An event triggered before rendering the scene
  104566. */
  104567. this.onBeforeRenderObservable = new BABYLON.Observable();
  104568. /**
  104569. * An event triggered after rendering the scene
  104570. */
  104571. this.onAfterRenderObservable = new BABYLON.Observable();
  104572. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  104573. this.isBackground = isBackground === undefined ? true : isBackground;
  104574. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  104575. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  104576. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  104577. if (!layerComponent) {
  104578. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  104579. this._scene._addComponent(layerComponent);
  104580. }
  104581. this._scene.layers.push(this);
  104582. var engine = this._scene.getEngine();
  104583. // VBO
  104584. var vertices = [];
  104585. vertices.push(1, 1);
  104586. vertices.push(-1, 1);
  104587. vertices.push(-1, -1);
  104588. vertices.push(1, -1);
  104589. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  104590. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  104591. this._createIndexBuffer();
  104592. // Effects
  104593. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  104594. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  104595. }
  104596. Object.defineProperty(Layer.prototype, "onDispose", {
  104597. set: function (callback) {
  104598. if (this._onDisposeObserver) {
  104599. this.onDisposeObservable.remove(this._onDisposeObserver);
  104600. }
  104601. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104602. },
  104603. enumerable: true,
  104604. configurable: true
  104605. });
  104606. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  104607. set: function (callback) {
  104608. if (this._onBeforeRenderObserver) {
  104609. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  104610. }
  104611. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  104612. },
  104613. enumerable: true,
  104614. configurable: true
  104615. });
  104616. Object.defineProperty(Layer.prototype, "onAfterRender", {
  104617. set: function (callback) {
  104618. if (this._onAfterRenderObserver) {
  104619. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  104620. }
  104621. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  104622. },
  104623. enumerable: true,
  104624. configurable: true
  104625. });
  104626. Layer.prototype._createIndexBuffer = function () {
  104627. var engine = this._scene.getEngine();
  104628. // Indices
  104629. var indices = [];
  104630. indices.push(0);
  104631. indices.push(1);
  104632. indices.push(2);
  104633. indices.push(0);
  104634. indices.push(2);
  104635. indices.push(3);
  104636. this._indexBuffer = engine.createIndexBuffer(indices);
  104637. };
  104638. /** @hidden */
  104639. Layer.prototype._rebuild = function () {
  104640. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104641. if (vb) {
  104642. vb._rebuild();
  104643. }
  104644. this._createIndexBuffer();
  104645. };
  104646. Layer.prototype.render = function () {
  104647. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  104648. // Check
  104649. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  104650. return;
  104651. var engine = this._scene.getEngine();
  104652. this.onBeforeRenderObservable.notifyObservers(this);
  104653. // Render
  104654. engine.enableEffect(currentEffect);
  104655. engine.setState(false);
  104656. // Texture
  104657. currentEffect.setTexture("textureSampler", this.texture);
  104658. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  104659. // Color
  104660. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  104661. // Scale / offset
  104662. currentEffect.setVector2("offset", this.offset);
  104663. currentEffect.setVector2("scale", this.scale);
  104664. // VBOs
  104665. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  104666. // Draw order
  104667. if (!this.alphaTest) {
  104668. engine.setAlphaMode(this.alphaBlendingMode);
  104669. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104670. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  104671. }
  104672. else {
  104673. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104674. }
  104675. this.onAfterRenderObservable.notifyObservers(this);
  104676. };
  104677. Layer.prototype.dispose = function () {
  104678. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104679. if (vertexBuffer) {
  104680. vertexBuffer.dispose();
  104681. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  104682. }
  104683. if (this._indexBuffer) {
  104684. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  104685. this._indexBuffer = null;
  104686. }
  104687. if (this.texture) {
  104688. this.texture.dispose();
  104689. this.texture = null;
  104690. }
  104691. // Remove from scene
  104692. var index = this._scene.layers.indexOf(this);
  104693. this._scene.layers.splice(index, 1);
  104694. // Callback
  104695. this.onDisposeObservable.notifyObservers(this);
  104696. this.onDisposeObservable.clear();
  104697. this.onAfterRenderObservable.clear();
  104698. this.onBeforeRenderObservable.clear();
  104699. };
  104700. return Layer;
  104701. }());
  104702. BABYLON.Layer = Layer;
  104703. })(BABYLON || (BABYLON = {}));
  104704. //# sourceMappingURL=babylon.layer.js.map
  104705. var BABYLON;
  104706. (function (BABYLON) {
  104707. var TextureTools = /** @class */ (function () {
  104708. function TextureTools() {
  104709. }
  104710. /**
  104711. * Uses the GPU to create a copy texture rescaled at a given size
  104712. * @param texture Texture to copy from
  104713. * @param width Desired width
  104714. * @param height Desired height
  104715. * @return Generated texture
  104716. */
  104717. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  104718. if (useBilinearMode === void 0) { useBilinearMode = true; }
  104719. var scene = texture.getScene();
  104720. var engine = scene.getEngine();
  104721. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  104722. rtt.wrapU = texture.wrapU;
  104723. rtt.wrapV = texture.wrapV;
  104724. rtt.uOffset = texture.uOffset;
  104725. rtt.vOffset = texture.vOffset;
  104726. rtt.uScale = texture.uScale;
  104727. rtt.vScale = texture.vScale;
  104728. rtt.uAng = texture.uAng;
  104729. rtt.vAng = texture.vAng;
  104730. rtt.wAng = texture.wAng;
  104731. rtt.coordinatesIndex = texture.coordinatesIndex;
  104732. rtt.level = texture.level;
  104733. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  104734. rtt._texture.isReady = false;
  104735. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104736. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104737. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  104738. passPostProcess.getEffect().executeWhenCompiled(function () {
  104739. passPostProcess.onApply = function (effect) {
  104740. effect.setTexture("textureSampler", texture);
  104741. };
  104742. var internalTexture = rtt.getInternalTexture();
  104743. if (internalTexture) {
  104744. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  104745. engine.unBindFramebuffer(internalTexture);
  104746. rtt.disposeFramebufferObjects();
  104747. passPostProcess.dispose();
  104748. internalTexture.isReady = true;
  104749. }
  104750. });
  104751. return rtt;
  104752. };
  104753. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  104754. if (!scene._environmentBRDFTexture) {
  104755. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  104756. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104757. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104758. scene._environmentBRDFTexture = texture;
  104759. }
  104760. return scene._environmentBRDFTexture;
  104761. };
  104762. 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=";
  104763. return TextureTools;
  104764. }());
  104765. BABYLON.TextureTools = TextureTools;
  104766. })(BABYLON || (BABYLON = {}));
  104767. //# sourceMappingURL=babylon.textureTools.js.map
  104768. var BABYLON;
  104769. (function (BABYLON) {
  104770. var FramingBehavior = /** @class */ (function () {
  104771. function FramingBehavior() {
  104772. this._mode = FramingBehavior.FitFrustumSidesMode;
  104773. this._radiusScale = 1.0;
  104774. this._positionScale = 0.5;
  104775. this._defaultElevation = 0.3;
  104776. this._elevationReturnTime = 1500;
  104777. this._elevationReturnWaitTime = 1000;
  104778. this._zoomStopsAnimation = false;
  104779. this._framingTime = 1500;
  104780. this._isPointerDown = false;
  104781. this._lastInteractionTime = -Infinity;
  104782. // Framing control
  104783. this._animatables = new Array();
  104784. this._betaIsAnimating = false;
  104785. }
  104786. Object.defineProperty(FramingBehavior.prototype, "name", {
  104787. get: function () {
  104788. return "Framing";
  104789. },
  104790. enumerable: true,
  104791. configurable: true
  104792. });
  104793. Object.defineProperty(FramingBehavior.prototype, "mode", {
  104794. /**
  104795. * Gets current mode used by the behavior.
  104796. */
  104797. get: function () {
  104798. return this._mode;
  104799. },
  104800. /**
  104801. * Sets the current mode used by the behavior
  104802. */
  104803. set: function (mode) {
  104804. this._mode = mode;
  104805. },
  104806. enumerable: true,
  104807. configurable: true
  104808. });
  104809. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  104810. /**
  104811. * Gets the scale applied to the radius
  104812. */
  104813. get: function () {
  104814. return this._radiusScale;
  104815. },
  104816. /**
  104817. * Sets the scale applied to the radius (1 by default)
  104818. */
  104819. set: function (radius) {
  104820. this._radiusScale = radius;
  104821. },
  104822. enumerable: true,
  104823. configurable: true
  104824. });
  104825. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  104826. /**
  104827. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104828. */
  104829. get: function () {
  104830. return this._positionScale;
  104831. },
  104832. /**
  104833. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104834. */
  104835. set: function (scale) {
  104836. this._positionScale = scale;
  104837. },
  104838. enumerable: true,
  104839. configurable: true
  104840. });
  104841. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  104842. /**
  104843. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104844. * behaviour is triggered, in radians.
  104845. */
  104846. get: function () {
  104847. return this._defaultElevation;
  104848. },
  104849. /**
  104850. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104851. * behaviour is triggered, in radians.
  104852. */
  104853. set: function (elevation) {
  104854. this._defaultElevation = elevation;
  104855. },
  104856. enumerable: true,
  104857. configurable: true
  104858. });
  104859. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  104860. /**
  104861. * Gets the time (in milliseconds) taken to return to the default beta position.
  104862. * Negative value indicates camera should not return to default.
  104863. */
  104864. get: function () {
  104865. return this._elevationReturnTime;
  104866. },
  104867. /**
  104868. * Sets the time (in milliseconds) taken to return to the default beta position.
  104869. * Negative value indicates camera should not return to default.
  104870. */
  104871. set: function (speed) {
  104872. this._elevationReturnTime = speed;
  104873. },
  104874. enumerable: true,
  104875. configurable: true
  104876. });
  104877. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  104878. /**
  104879. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104880. */
  104881. get: function () {
  104882. return this._elevationReturnWaitTime;
  104883. },
  104884. /**
  104885. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104886. */
  104887. set: function (time) {
  104888. this._elevationReturnWaitTime = time;
  104889. },
  104890. enumerable: true,
  104891. configurable: true
  104892. });
  104893. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  104894. /**
  104895. * Gets the flag that indicates if user zooming should stop animation.
  104896. */
  104897. get: function () {
  104898. return this._zoomStopsAnimation;
  104899. },
  104900. /**
  104901. * Sets the flag that indicates if user zooming should stop animation.
  104902. */
  104903. set: function (flag) {
  104904. this._zoomStopsAnimation = flag;
  104905. },
  104906. enumerable: true,
  104907. configurable: true
  104908. });
  104909. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  104910. /**
  104911. * Gets the transition time when framing the mesh, in milliseconds
  104912. */
  104913. get: function () {
  104914. return this._framingTime;
  104915. },
  104916. /**
  104917. * Sets the transition time when framing the mesh, in milliseconds
  104918. */
  104919. set: function (time) {
  104920. this._framingTime = time;
  104921. },
  104922. enumerable: true,
  104923. configurable: true
  104924. });
  104925. FramingBehavior.prototype.init = function () {
  104926. // Do notihng
  104927. };
  104928. FramingBehavior.prototype.attach = function (camera) {
  104929. var _this = this;
  104930. this._attachedCamera = camera;
  104931. var scene = this._attachedCamera.getScene();
  104932. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  104933. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  104934. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  104935. _this._isPointerDown = true;
  104936. return;
  104937. }
  104938. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  104939. _this._isPointerDown = false;
  104940. }
  104941. });
  104942. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  104943. if (mesh) {
  104944. _this.zoomOnMesh(mesh);
  104945. }
  104946. });
  104947. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  104948. // Stop the animation if there is user interaction and the animation should stop for this interaction
  104949. _this._applyUserInteraction();
  104950. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  104951. // back to the default position after a given timeout
  104952. _this._maintainCameraAboveGround();
  104953. });
  104954. };
  104955. FramingBehavior.prototype.detach = function () {
  104956. if (!this._attachedCamera) {
  104957. return;
  104958. }
  104959. var scene = this._attachedCamera.getScene();
  104960. if (this._onPrePointerObservableObserver) {
  104961. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  104962. }
  104963. if (this._onAfterCheckInputsObserver) {
  104964. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  104965. }
  104966. if (this._onMeshTargetChangedObserver) {
  104967. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  104968. }
  104969. this._attachedCamera = null;
  104970. };
  104971. /**
  104972. * Targets the given mesh and updates zoom level accordingly.
  104973. * @param mesh The mesh to target.
  104974. * @param radius Optional. If a cached radius position already exists, overrides default.
  104975. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104976. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104977. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104978. */
  104979. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104980. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104981. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104982. mesh.computeWorldMatrix(true);
  104983. var boundingBox = mesh.getBoundingInfo().boundingBox;
  104984. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  104985. };
  104986. /**
  104987. * Targets the given mesh with its children and updates zoom level accordingly.
  104988. * @param mesh The mesh to target.
  104989. * @param radius Optional. If a cached radius position already exists, overrides default.
  104990. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104991. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104992. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104993. */
  104994. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104995. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104996. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104997. mesh.computeWorldMatrix(true);
  104998. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  104999. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  105000. };
  105001. /**
  105002. * Targets the given meshes with their children and updates zoom level accordingly.
  105003. * @param meshes The mesh to target.
  105004. * @param radius Optional. If a cached radius position already exists, overrides default.
  105005. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105006. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105007. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105008. */
  105009. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  105010. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105011. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105012. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  105013. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  105014. for (var i = 0; i < meshes.length; i++) {
  105015. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  105016. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  105017. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  105018. }
  105019. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  105020. };
  105021. /**
  105022. * Targets the given mesh and updates zoom level accordingly.
  105023. * @param mesh The mesh to target.
  105024. * @param radius Optional. If a cached radius position already exists, overrides default.
  105025. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105026. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105027. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105028. */
  105029. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  105030. var _this = this;
  105031. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105032. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105033. var zoomTarget;
  105034. if (!this._attachedCamera) {
  105035. return;
  105036. }
  105037. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  105038. var bottom = minimumWorld.y;
  105039. var top = maximumWorld.y;
  105040. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  105041. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  105042. if (focusOnOriginXZ) {
  105043. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  105044. }
  105045. else {
  105046. var centerWorld = minimumWorld.add(radiusWorld);
  105047. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  105048. }
  105049. if (!this._vectorTransition) {
  105050. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  105051. }
  105052. this._betaIsAnimating = true;
  105053. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  105054. if (animatable) {
  105055. this._animatables.push(animatable);
  105056. }
  105057. // sets the radius and lower radius bounds
  105058. // Small delta ensures camera is not always at lower zoom limit.
  105059. var radius = 0;
  105060. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  105061. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105062. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  105063. radius = position;
  105064. }
  105065. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105066. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105067. if (this._attachedCamera.lowerRadiusLimit === null) {
  105068. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  105069. }
  105070. }
  105071. // Set sensibilities
  105072. var extend = maximumWorld.subtract(minimumWorld).length();
  105073. this._attachedCamera.panningSensibility = 5000 / extend;
  105074. this._attachedCamera.wheelPrecision = 100 / radius;
  105075. // transition to new radius
  105076. if (!this._radiusTransition) {
  105077. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105078. }
  105079. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  105080. _this.stopAllAnimations();
  105081. if (onAnimationEnd) {
  105082. onAnimationEnd();
  105083. }
  105084. if (_this._attachedCamera) {
  105085. _this._attachedCamera.storeState();
  105086. }
  105087. });
  105088. if (animatable) {
  105089. this._animatables.push(animatable);
  105090. }
  105091. };
  105092. /**
  105093. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  105094. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  105095. * frustum width.
  105096. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  105097. * to fully enclose the mesh in the viewing frustum.
  105098. */
  105099. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  105100. var size = maximumWorld.subtract(minimumWorld);
  105101. var boxVectorGlobalDiagonal = size.length();
  105102. var frustumSlope = this._getFrustumSlope();
  105103. // Formula for setting distance
  105104. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  105105. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  105106. // Horizon distance
  105107. var radius = radiusWithoutFraming * this._radiusScale;
  105108. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  105109. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  105110. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  105111. var camera = this._attachedCamera;
  105112. if (!camera) {
  105113. return 0;
  105114. }
  105115. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105116. // Don't exceed the requested limit
  105117. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  105118. }
  105119. // Don't exceed the upper radius limit
  105120. if (camera.upperRadiusLimit) {
  105121. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  105122. }
  105123. return distance;
  105124. };
  105125. /**
  105126. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  105127. * is automatically returned to its default position (expected to be above ground plane).
  105128. */
  105129. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  105130. var _this = this;
  105131. if (this._elevationReturnTime < 0) {
  105132. return;
  105133. }
  105134. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  105135. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  105136. var limitBeta = Math.PI * 0.5;
  105137. // Bring the camera back up if below the ground plane
  105138. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  105139. this._betaIsAnimating = true;
  105140. //Transition to new position
  105141. this.stopAllAnimations();
  105142. if (!this._betaTransition) {
  105143. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105144. }
  105145. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  105146. _this._clearAnimationLocks();
  105147. _this.stopAllAnimations();
  105148. });
  105149. if (animatabe) {
  105150. this._animatables.push(animatabe);
  105151. }
  105152. }
  105153. };
  105154. /**
  105155. * Returns the frustum slope based on the canvas ratio and camera FOV
  105156. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  105157. */
  105158. FramingBehavior.prototype._getFrustumSlope = function () {
  105159. // Calculate the viewport ratio
  105160. // Aspect Ratio is Height/Width.
  105161. var camera = this._attachedCamera;
  105162. if (!camera) {
  105163. return BABYLON.Vector2.Zero();
  105164. }
  105165. var engine = camera.getScene().getEngine();
  105166. var aspectRatio = engine.getAspectRatio(camera);
  105167. // Camera FOV is the vertical field of view (top-bottom) in radians.
  105168. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  105169. var frustumSlopeY = Math.tan(camera.fov / 2);
  105170. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  105171. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  105172. // along the forward vector.
  105173. var frustumSlopeX = frustumSlopeY * aspectRatio;
  105174. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  105175. };
  105176. /**
  105177. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  105178. */
  105179. FramingBehavior.prototype._clearAnimationLocks = function () {
  105180. this._betaIsAnimating = false;
  105181. };
  105182. /**
  105183. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105184. */
  105185. FramingBehavior.prototype._applyUserInteraction = function () {
  105186. if (this.isUserIsMoving) {
  105187. this._lastInteractionTime = BABYLON.Tools.Now;
  105188. this.stopAllAnimations();
  105189. this._clearAnimationLocks();
  105190. }
  105191. };
  105192. /**
  105193. * Stops and removes all animations that have been applied to the camera
  105194. */
  105195. FramingBehavior.prototype.stopAllAnimations = function () {
  105196. if (this._attachedCamera) {
  105197. this._attachedCamera.animations = [];
  105198. }
  105199. while (this._animatables.length) {
  105200. if (this._animatables[0]) {
  105201. this._animatables[0].onAnimationEnd = null;
  105202. this._animatables[0].stop();
  105203. }
  105204. this._animatables.shift();
  105205. }
  105206. };
  105207. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  105208. /**
  105209. * Gets a value indicating if the user is moving the camera
  105210. */
  105211. get: function () {
  105212. if (!this._attachedCamera) {
  105213. return false;
  105214. }
  105215. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105216. this._attachedCamera.inertialBetaOffset !== 0 ||
  105217. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105218. this._attachedCamera.inertialPanningX !== 0 ||
  105219. this._attachedCamera.inertialPanningY !== 0 ||
  105220. this._isPointerDown;
  105221. },
  105222. enumerable: true,
  105223. configurable: true
  105224. });
  105225. /**
  105226. * The easing function used by animations
  105227. */
  105228. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  105229. /**
  105230. * The easing mode used by animations
  105231. */
  105232. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  105233. // Statics
  105234. /**
  105235. * The camera can move all the way towards the mesh.
  105236. */
  105237. FramingBehavior.IgnoreBoundsSizeMode = 0;
  105238. /**
  105239. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  105240. */
  105241. FramingBehavior.FitFrustumSidesMode = 1;
  105242. return FramingBehavior;
  105243. }());
  105244. BABYLON.FramingBehavior = FramingBehavior;
  105245. })(BABYLON || (BABYLON = {}));
  105246. //# sourceMappingURL=babylon.framingBehavior.js.map
  105247. var BABYLON;
  105248. (function (BABYLON) {
  105249. /**
  105250. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  105251. */
  105252. var BouncingBehavior = /** @class */ (function () {
  105253. function BouncingBehavior() {
  105254. /**
  105255. * The duration of the animation, in milliseconds
  105256. */
  105257. this.transitionDuration = 450;
  105258. /**
  105259. * Length of the distance animated by the transition when lower radius is reached
  105260. */
  105261. this.lowerRadiusTransitionRange = 2;
  105262. /**
  105263. * Length of the distance animated by the transition when upper radius is reached
  105264. */
  105265. this.upperRadiusTransitionRange = -2;
  105266. this._autoTransitionRange = false;
  105267. // Animations
  105268. this._radiusIsAnimating = false;
  105269. this._radiusBounceTransition = null;
  105270. this._animatables = new Array();
  105271. }
  105272. Object.defineProperty(BouncingBehavior.prototype, "name", {
  105273. get: function () {
  105274. return "Bouncing";
  105275. },
  105276. enumerable: true,
  105277. configurable: true
  105278. });
  105279. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  105280. /**
  105281. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105282. */
  105283. get: function () {
  105284. return this._autoTransitionRange;
  105285. },
  105286. /**
  105287. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105288. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  105289. */
  105290. set: function (value) {
  105291. var _this = this;
  105292. if (this._autoTransitionRange === value) {
  105293. return;
  105294. }
  105295. this._autoTransitionRange = value;
  105296. var camera = this._attachedCamera;
  105297. if (!camera) {
  105298. return;
  105299. }
  105300. if (value) {
  105301. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105302. if (!mesh) {
  105303. return;
  105304. }
  105305. mesh.computeWorldMatrix(true);
  105306. var diagonal = mesh.getBoundingInfo().diagonalLength;
  105307. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  105308. _this.upperRadiusTransitionRange = diagonal * 0.05;
  105309. });
  105310. }
  105311. else if (this._onMeshTargetChangedObserver) {
  105312. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105313. }
  105314. },
  105315. enumerable: true,
  105316. configurable: true
  105317. });
  105318. BouncingBehavior.prototype.init = function () {
  105319. // Do notihng
  105320. };
  105321. BouncingBehavior.prototype.attach = function (camera) {
  105322. var _this = this;
  105323. this._attachedCamera = camera;
  105324. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105325. if (!_this._attachedCamera) {
  105326. return;
  105327. }
  105328. // Add the bounce animation to the lower radius limit
  105329. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  105330. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  105331. }
  105332. // Add the bounce animation to the upper radius limit
  105333. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  105334. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  105335. }
  105336. });
  105337. };
  105338. BouncingBehavior.prototype.detach = function () {
  105339. if (!this._attachedCamera) {
  105340. return;
  105341. }
  105342. if (this._onAfterCheckInputsObserver) {
  105343. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105344. }
  105345. if (this._onMeshTargetChangedObserver) {
  105346. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105347. }
  105348. this._attachedCamera = null;
  105349. };
  105350. /**
  105351. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  105352. * @param radiusLimit The limit to check against.
  105353. * @return Bool to indicate if at limit.
  105354. */
  105355. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  105356. if (!this._attachedCamera) {
  105357. return false;
  105358. }
  105359. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  105360. return true;
  105361. }
  105362. return false;
  105363. };
  105364. /**
  105365. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  105366. * @param radiusDelta The delta by which to animate to. Can be negative.
  105367. */
  105368. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  105369. var _this = this;
  105370. if (!this._attachedCamera) {
  105371. return;
  105372. }
  105373. if (!this._radiusBounceTransition) {
  105374. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  105375. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  105376. }
  105377. // Prevent zoom until bounce has completed
  105378. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  105379. this._attachedCamera.wheelPrecision = Infinity;
  105380. this._attachedCamera.inertialRadiusOffset = 0;
  105381. // Animate to the radius limit
  105382. this.stopAllAnimations();
  105383. this._radiusIsAnimating = true;
  105384. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  105385. if (animatable) {
  105386. this._animatables.push(animatable);
  105387. }
  105388. };
  105389. /**
  105390. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  105391. */
  105392. BouncingBehavior.prototype._clearAnimationLocks = function () {
  105393. this._radiusIsAnimating = false;
  105394. if (this._attachedCamera) {
  105395. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  105396. }
  105397. };
  105398. /**
  105399. * Stops and removes all animations that have been applied to the camera
  105400. */
  105401. BouncingBehavior.prototype.stopAllAnimations = function () {
  105402. if (this._attachedCamera) {
  105403. this._attachedCamera.animations = [];
  105404. }
  105405. while (this._animatables.length) {
  105406. this._animatables[0].onAnimationEnd = null;
  105407. this._animatables[0].stop();
  105408. this._animatables.shift();
  105409. }
  105410. };
  105411. /**
  105412. * The easing function used by animations
  105413. */
  105414. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  105415. /**
  105416. * The easing mode used by animations
  105417. */
  105418. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  105419. return BouncingBehavior;
  105420. }());
  105421. BABYLON.BouncingBehavior = BouncingBehavior;
  105422. })(BABYLON || (BABYLON = {}));
  105423. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  105424. var BABYLON;
  105425. (function (BABYLON) {
  105426. var AutoRotationBehavior = /** @class */ (function () {
  105427. function AutoRotationBehavior() {
  105428. this._zoomStopsAnimation = false;
  105429. this._idleRotationSpeed = 0.05;
  105430. this._idleRotationWaitTime = 2000;
  105431. this._idleRotationSpinupTime = 2000;
  105432. this._isPointerDown = false;
  105433. this._lastFrameTime = null;
  105434. this._lastInteractionTime = -Infinity;
  105435. this._cameraRotationSpeed = 0;
  105436. this._lastFrameRadius = 0;
  105437. }
  105438. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  105439. get: function () {
  105440. return "AutoRotation";
  105441. },
  105442. enumerable: true,
  105443. configurable: true
  105444. });
  105445. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  105446. /**
  105447. * Gets the flag that indicates if user zooming should stop animation.
  105448. */
  105449. get: function () {
  105450. return this._zoomStopsAnimation;
  105451. },
  105452. /**
  105453. * Sets the flag that indicates if user zooming should stop animation.
  105454. */
  105455. set: function (flag) {
  105456. this._zoomStopsAnimation = flag;
  105457. },
  105458. enumerable: true,
  105459. configurable: true
  105460. });
  105461. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  105462. /**
  105463. * Gets the default speed at which the camera rotates around the model.
  105464. */
  105465. get: function () {
  105466. return this._idleRotationSpeed;
  105467. },
  105468. /**
  105469. * Sets the default speed at which the camera rotates around the model.
  105470. */
  105471. set: function (speed) {
  105472. this._idleRotationSpeed = speed;
  105473. },
  105474. enumerable: true,
  105475. configurable: true
  105476. });
  105477. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  105478. /**
  105479. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  105480. */
  105481. get: function () {
  105482. return this._idleRotationWaitTime;
  105483. },
  105484. /**
  105485. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  105486. */
  105487. set: function (time) {
  105488. this._idleRotationWaitTime = time;
  105489. },
  105490. enumerable: true,
  105491. configurable: true
  105492. });
  105493. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  105494. /**
  105495. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105496. */
  105497. get: function () {
  105498. return this._idleRotationSpinupTime;
  105499. },
  105500. /**
  105501. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105502. */
  105503. set: function (time) {
  105504. this._idleRotationSpinupTime = time;
  105505. },
  105506. enumerable: true,
  105507. configurable: true
  105508. });
  105509. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  105510. /**
  105511. * Gets a value indicating if the camera is currently rotating because of this behavior
  105512. */
  105513. get: function () {
  105514. return Math.abs(this._cameraRotationSpeed) > 0;
  105515. },
  105516. enumerable: true,
  105517. configurable: true
  105518. });
  105519. AutoRotationBehavior.prototype.init = function () {
  105520. // Do notihng
  105521. };
  105522. AutoRotationBehavior.prototype.attach = function (camera) {
  105523. var _this = this;
  105524. this._attachedCamera = camera;
  105525. var scene = this._attachedCamera.getScene();
  105526. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105527. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105528. _this._isPointerDown = true;
  105529. return;
  105530. }
  105531. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105532. _this._isPointerDown = false;
  105533. }
  105534. });
  105535. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105536. var now = BABYLON.Tools.Now;
  105537. var dt = 0;
  105538. if (_this._lastFrameTime != null) {
  105539. dt = now - _this._lastFrameTime;
  105540. }
  105541. _this._lastFrameTime = now;
  105542. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105543. _this._applyUserInteraction();
  105544. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  105545. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  105546. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  105547. // Step camera rotation by rotation speed
  105548. if (_this._attachedCamera) {
  105549. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  105550. }
  105551. });
  105552. };
  105553. AutoRotationBehavior.prototype.detach = function () {
  105554. if (!this._attachedCamera) {
  105555. return;
  105556. }
  105557. var scene = this._attachedCamera.getScene();
  105558. if (this._onPrePointerObservableObserver) {
  105559. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  105560. }
  105561. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105562. this._attachedCamera = null;
  105563. };
  105564. /**
  105565. * Returns true if user is scrolling.
  105566. * @return true if user is scrolling.
  105567. */
  105568. AutoRotationBehavior.prototype._userIsZooming = function () {
  105569. if (!this._attachedCamera) {
  105570. return false;
  105571. }
  105572. return this._attachedCamera.inertialRadiusOffset !== 0;
  105573. };
  105574. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  105575. if (!this._attachedCamera) {
  105576. return false;
  105577. }
  105578. var zoomHasHitLimit = false;
  105579. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  105580. zoomHasHitLimit = true;
  105581. }
  105582. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  105583. this._lastFrameRadius = this._attachedCamera.radius;
  105584. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  105585. };
  105586. /**
  105587. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105588. */
  105589. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  105590. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  105591. this._lastInteractionTime = BABYLON.Tools.Now;
  105592. }
  105593. };
  105594. // Tools
  105595. AutoRotationBehavior.prototype._userIsMoving = function () {
  105596. if (!this._attachedCamera) {
  105597. return false;
  105598. }
  105599. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105600. this._attachedCamera.inertialBetaOffset !== 0 ||
  105601. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105602. this._attachedCamera.inertialPanningX !== 0 ||
  105603. this._attachedCamera.inertialPanningY !== 0 ||
  105604. this._isPointerDown;
  105605. };
  105606. return AutoRotationBehavior;
  105607. }());
  105608. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  105609. })(BABYLON || (BABYLON = {}));
  105610. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  105611. var BABYLON;
  105612. (function (BABYLON) {
  105613. var NullEngineOptions = /** @class */ (function () {
  105614. function NullEngineOptions() {
  105615. this.renderWidth = 512;
  105616. this.renderHeight = 256;
  105617. this.textureSize = 512;
  105618. this.deterministicLockstep = false;
  105619. this.lockstepMaxSteps = 4;
  105620. }
  105621. return NullEngineOptions;
  105622. }());
  105623. BABYLON.NullEngineOptions = NullEngineOptions;
  105624. /**
  105625. * The null engine class provides support for headless version of babylon.js.
  105626. * This can be used in server side scenario or for testing purposes
  105627. */
  105628. var NullEngine = /** @class */ (function (_super) {
  105629. __extends(NullEngine, _super);
  105630. function NullEngine(options) {
  105631. if (options === void 0) { options = new NullEngineOptions(); }
  105632. var _this = _super.call(this, null) || this;
  105633. if (options.deterministicLockstep === undefined) {
  105634. options.deterministicLockstep = false;
  105635. }
  105636. if (options.lockstepMaxSteps === undefined) {
  105637. options.lockstepMaxSteps = 4;
  105638. }
  105639. _this._options = options;
  105640. // Init caps
  105641. // We consider we are on a webgl1 capable device
  105642. _this._caps = new BABYLON.EngineCapabilities();
  105643. _this._caps.maxTexturesImageUnits = 16;
  105644. _this._caps.maxVertexTextureImageUnits = 16;
  105645. _this._caps.maxTextureSize = 512;
  105646. _this._caps.maxCubemapTextureSize = 512;
  105647. _this._caps.maxRenderTextureSize = 512;
  105648. _this._caps.maxVertexAttribs = 16;
  105649. _this._caps.maxVaryingVectors = 16;
  105650. _this._caps.maxFragmentUniformVectors = 16;
  105651. _this._caps.maxVertexUniformVectors = 16;
  105652. // Extensions
  105653. _this._caps.standardDerivatives = false;
  105654. _this._caps.astc = null;
  105655. _this._caps.s3tc = null;
  105656. _this._caps.pvrtc = null;
  105657. _this._caps.etc1 = null;
  105658. _this._caps.etc2 = null;
  105659. _this._caps.textureAnisotropicFilterExtension = null;
  105660. _this._caps.maxAnisotropy = 0;
  105661. _this._caps.uintIndices = false;
  105662. _this._caps.fragmentDepthSupported = false;
  105663. _this._caps.highPrecisionShaderSupported = true;
  105664. _this._caps.colorBufferFloat = false;
  105665. _this._caps.textureFloat = false;
  105666. _this._caps.textureFloatLinearFiltering = false;
  105667. _this._caps.textureFloatRender = false;
  105668. _this._caps.textureHalfFloat = false;
  105669. _this._caps.textureHalfFloatLinearFiltering = false;
  105670. _this._caps.textureHalfFloatRender = false;
  105671. _this._caps.textureLOD = false;
  105672. _this._caps.drawBuffersExtension = false;
  105673. _this._caps.depthTextureExtension = false;
  105674. _this._caps.vertexArrayObject = false;
  105675. _this._caps.instancedArrays = false;
  105676. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  105677. // Wrappers
  105678. if (typeof URL === "undefined") {
  105679. URL = {
  105680. createObjectURL: function () { },
  105681. revokeObjectURL: function () { }
  105682. };
  105683. }
  105684. if (typeof Blob === "undefined") {
  105685. Blob = function () { };
  105686. }
  105687. return _this;
  105688. }
  105689. NullEngine.prototype.isDeterministicLockStep = function () {
  105690. return this._options.deterministicLockstep;
  105691. };
  105692. NullEngine.prototype.getLockstepMaxSteps = function () {
  105693. return this._options.lockstepMaxSteps;
  105694. };
  105695. NullEngine.prototype.getHardwareScalingLevel = function () {
  105696. return 1.0;
  105697. };
  105698. NullEngine.prototype.createVertexBuffer = function (vertices) {
  105699. return {
  105700. capacity: 0,
  105701. references: 1,
  105702. is32Bits: false
  105703. };
  105704. };
  105705. NullEngine.prototype.createIndexBuffer = function (indices) {
  105706. return {
  105707. capacity: 0,
  105708. references: 1,
  105709. is32Bits: false
  105710. };
  105711. };
  105712. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  105713. if (stencil === void 0) { stencil = false; }
  105714. };
  105715. NullEngine.prototype.getRenderWidth = function (useScreen) {
  105716. if (useScreen === void 0) { useScreen = false; }
  105717. if (!useScreen && this._currentRenderTarget) {
  105718. return this._currentRenderTarget.width;
  105719. }
  105720. return this._options.renderWidth;
  105721. };
  105722. NullEngine.prototype.getRenderHeight = function (useScreen) {
  105723. if (useScreen === void 0) { useScreen = false; }
  105724. if (!useScreen && this._currentRenderTarget) {
  105725. return this._currentRenderTarget.height;
  105726. }
  105727. return this._options.renderHeight;
  105728. };
  105729. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  105730. this._cachedViewport = viewport;
  105731. };
  105732. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  105733. return {
  105734. transformFeedback: null,
  105735. __SPECTOR_rebuildProgram: null
  105736. };
  105737. };
  105738. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  105739. return [];
  105740. };
  105741. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  105742. return [];
  105743. };
  105744. NullEngine.prototype.bindSamplers = function (effect) {
  105745. this._currentEffect = null;
  105746. };
  105747. NullEngine.prototype.enableEffect = function (effect) {
  105748. this._currentEffect = effect;
  105749. if (effect.onBind) {
  105750. effect.onBind(effect);
  105751. }
  105752. if (effect._onBindObservable) {
  105753. effect._onBindObservable.notifyObservers(effect);
  105754. }
  105755. };
  105756. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  105757. if (zOffset === void 0) { zOffset = 0; }
  105758. if (reverseSide === void 0) { reverseSide = false; }
  105759. };
  105760. NullEngine.prototype.setIntArray = function (uniform, array) {
  105761. };
  105762. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  105763. };
  105764. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  105765. };
  105766. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  105767. };
  105768. NullEngine.prototype.setFloatArray = function (uniform, array) {
  105769. };
  105770. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  105771. };
  105772. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  105773. };
  105774. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  105775. };
  105776. NullEngine.prototype.setArray = function (uniform, array) {
  105777. };
  105778. NullEngine.prototype.setArray2 = function (uniform, array) {
  105779. };
  105780. NullEngine.prototype.setArray3 = function (uniform, array) {
  105781. };
  105782. NullEngine.prototype.setArray4 = function (uniform, array) {
  105783. };
  105784. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  105785. };
  105786. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  105787. };
  105788. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  105789. };
  105790. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  105791. };
  105792. NullEngine.prototype.setFloat = function (uniform, value) {
  105793. };
  105794. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  105795. };
  105796. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  105797. };
  105798. NullEngine.prototype.setBool = function (uniform, bool) {
  105799. };
  105800. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  105801. };
  105802. NullEngine.prototype.setColor3 = function (uniform, color3) {
  105803. };
  105804. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  105805. };
  105806. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  105807. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  105808. if (this._alphaMode === mode) {
  105809. return;
  105810. }
  105811. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  105812. if (!noDepthWriteChange) {
  105813. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  105814. }
  105815. this._alphaMode = mode;
  105816. };
  105817. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  105818. };
  105819. NullEngine.prototype.wipeCaches = function (bruteForce) {
  105820. if (this.preventCacheWipeBetweenFrames) {
  105821. return;
  105822. }
  105823. this.resetTextureCache();
  105824. this._currentEffect = null;
  105825. if (bruteForce) {
  105826. this._currentProgram = null;
  105827. this._stencilState.reset();
  105828. this._depthCullingState.reset();
  105829. this._alphaState.reset();
  105830. }
  105831. this._cachedVertexBuffers = null;
  105832. this._cachedIndexBuffer = null;
  105833. this._cachedEffectForVertexBuffers = null;
  105834. };
  105835. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  105836. };
  105837. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  105838. };
  105839. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  105840. };
  105841. /** @hidden */
  105842. NullEngine.prototype._createTexture = function () {
  105843. return {};
  105844. };
  105845. /** @hidden */
  105846. NullEngine.prototype._releaseTexture = function (texture) {
  105847. };
  105848. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  105849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  105850. if (onLoad === void 0) { onLoad = null; }
  105851. if (onError === void 0) { onError = null; }
  105852. if (buffer === void 0) { buffer = null; }
  105853. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  105854. var url = String(urlArg);
  105855. texture.url = url;
  105856. texture.generateMipMaps = !noMipmap;
  105857. texture.samplingMode = samplingMode;
  105858. texture.invertY = invertY;
  105859. texture.baseWidth = this._options.textureSize;
  105860. texture.baseHeight = this._options.textureSize;
  105861. texture.width = this._options.textureSize;
  105862. texture.height = this._options.textureSize;
  105863. if (format) {
  105864. texture.format = format;
  105865. }
  105866. texture.isReady = true;
  105867. if (onLoad) {
  105868. onLoad();
  105869. }
  105870. this._internalTexturesCache.push(texture);
  105871. return texture;
  105872. };
  105873. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  105874. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  105875. if (options !== undefined && typeof options === "object") {
  105876. fullOptions.generateMipMaps = options.generateMipMaps;
  105877. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  105878. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  105879. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  105880. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  105881. }
  105882. else {
  105883. fullOptions.generateMipMaps = options;
  105884. fullOptions.generateDepthBuffer = true;
  105885. fullOptions.generateStencilBuffer = false;
  105886. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105887. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  105888. }
  105889. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  105890. var width = size.width || size;
  105891. var height = size.height || size;
  105892. texture._depthStencilBuffer = {};
  105893. texture._framebuffer = {};
  105894. texture.baseWidth = width;
  105895. texture.baseHeight = height;
  105896. texture.width = width;
  105897. texture.height = height;
  105898. texture.isReady = true;
  105899. texture.samples = 1;
  105900. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  105901. texture.samplingMode = fullOptions.samplingMode;
  105902. texture.type = fullOptions.type;
  105903. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  105904. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  105905. this._internalTexturesCache.push(texture);
  105906. return texture;
  105907. };
  105908. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  105909. texture.samplingMode = samplingMode;
  105910. };
  105911. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  105912. if (this._currentRenderTarget) {
  105913. this.unBindFramebuffer(this._currentRenderTarget);
  105914. }
  105915. this._currentRenderTarget = texture;
  105916. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  105917. if (this._cachedViewport && !forceFullscreenViewport) {
  105918. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  105919. }
  105920. };
  105921. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  105922. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  105923. this._currentRenderTarget = null;
  105924. if (onBeforeUnbind) {
  105925. if (texture._MSAAFramebuffer) {
  105926. this._currentFramebuffer = texture._framebuffer;
  105927. }
  105928. onBeforeUnbind();
  105929. }
  105930. this._currentFramebuffer = null;
  105931. };
  105932. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  105933. var vbo = {
  105934. capacity: 1,
  105935. references: 1,
  105936. is32Bits: false
  105937. };
  105938. return vbo;
  105939. };
  105940. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  105941. if (premulAlpha === void 0) { premulAlpha = false; }
  105942. };
  105943. /**
  105944. * @hidden
  105945. * Get the current error code of the webGL context
  105946. * @returns the error code
  105947. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  105948. */
  105949. NullEngine.prototype.getError = function () {
  105950. return 0;
  105951. };
  105952. /** @hidden */
  105953. NullEngine.prototype._getUnpackAlignement = function () {
  105954. return 1;
  105955. };
  105956. /** @hidden */
  105957. NullEngine.prototype._unpackFlipY = function (value) {
  105958. };
  105959. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  105960. if (offset === void 0) { offset = 0; }
  105961. };
  105962. /**
  105963. * Updates a dynamic vertex buffer.
  105964. * @param vertexBuffer the vertex buffer to update
  105965. * @param data the data used to update the vertex buffer
  105966. * @param byteOffset the byte offset of the data (optional)
  105967. * @param byteLength the byte length of the data (optional)
  105968. */
  105969. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  105970. };
  105971. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  105972. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  105973. this._boundTexturesCache[this._activeChannel] = texture;
  105974. return true;
  105975. }
  105976. return false;
  105977. };
  105978. /** @hidden */
  105979. NullEngine.prototype._bindTexture = function (channel, texture) {
  105980. if (channel < 0) {
  105981. return;
  105982. }
  105983. this._bindTextureDirectly(0, texture);
  105984. };
  105985. /** @hidden */
  105986. NullEngine.prototype._releaseBuffer = function (buffer) {
  105987. buffer.references--;
  105988. if (buffer.references === 0) {
  105989. return true;
  105990. }
  105991. return false;
  105992. };
  105993. NullEngine.prototype.releaseEffects = function () {
  105994. };
  105995. NullEngine.prototype.displayLoadingUI = function () {
  105996. };
  105997. NullEngine.prototype.hideLoadingUI = function () {
  105998. };
  105999. /** @hidden */
  106000. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  106001. if (faceIndex === void 0) { faceIndex = 0; }
  106002. if (lod === void 0) { lod = 0; }
  106003. };
  106004. /** @hidden */
  106005. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  106006. if (faceIndex === void 0) { faceIndex = 0; }
  106007. if (lod === void 0) { lod = 0; }
  106008. };
  106009. /** @hidden */
  106010. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  106011. if (faceIndex === void 0) { faceIndex = 0; }
  106012. if (lod === void 0) { lod = 0; }
  106013. };
  106014. /** @hidden */
  106015. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  106016. if (faceIndex === void 0) { faceIndex = 0; }
  106017. if (lod === void 0) { lod = 0; }
  106018. };
  106019. return NullEngine;
  106020. }(BABYLON.Engine));
  106021. BABYLON.NullEngine = NullEngine;
  106022. })(BABYLON || (BABYLON = {}));
  106023. //# sourceMappingURL=babylon.nullEngine.js.map
  106024. var BABYLON;
  106025. (function (BABYLON) {
  106026. /**
  106027. * This class can be used to get instrumentation data from a Babylon engine
  106028. */
  106029. var EngineInstrumentation = /** @class */ (function () {
  106030. function EngineInstrumentation(engine) {
  106031. this.engine = engine;
  106032. this._captureGPUFrameTime = false;
  106033. this._gpuFrameTime = new BABYLON.PerfCounter();
  106034. this._captureShaderCompilationTime = false;
  106035. this._shaderCompilationTime = new BABYLON.PerfCounter();
  106036. // Observers
  106037. this._onBeginFrameObserver = null;
  106038. this._onEndFrameObserver = null;
  106039. this._onBeforeShaderCompilationObserver = null;
  106040. this._onAfterShaderCompilationObserver = null;
  106041. }
  106042. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  106043. // Properties
  106044. /**
  106045. * Gets the perf counter used for GPU frame time
  106046. */
  106047. get: function () {
  106048. return this._gpuFrameTime;
  106049. },
  106050. enumerable: true,
  106051. configurable: true
  106052. });
  106053. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  106054. /**
  106055. * Gets the GPU frame time capture status
  106056. */
  106057. get: function () {
  106058. return this._captureGPUFrameTime;
  106059. },
  106060. /**
  106061. * Enable or disable the GPU frame time capture
  106062. */
  106063. set: function (value) {
  106064. var _this = this;
  106065. if (value === this._captureGPUFrameTime) {
  106066. return;
  106067. }
  106068. this._captureGPUFrameTime = value;
  106069. if (value) {
  106070. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  106071. if (!_this._gpuFrameTimeToken) {
  106072. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  106073. }
  106074. });
  106075. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  106076. if (!_this._gpuFrameTimeToken) {
  106077. return;
  106078. }
  106079. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  106080. if (time > -1) {
  106081. _this._gpuFrameTimeToken = null;
  106082. _this._gpuFrameTime.fetchNewFrame();
  106083. _this._gpuFrameTime.addCount(time, true);
  106084. }
  106085. });
  106086. }
  106087. else {
  106088. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106089. this._onBeginFrameObserver = null;
  106090. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106091. this._onEndFrameObserver = null;
  106092. }
  106093. },
  106094. enumerable: true,
  106095. configurable: true
  106096. });
  106097. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  106098. /**
  106099. * Gets the perf counter used for shader compilation time
  106100. */
  106101. get: function () {
  106102. return this._shaderCompilationTime;
  106103. },
  106104. enumerable: true,
  106105. configurable: true
  106106. });
  106107. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  106108. /**
  106109. * Gets the shader compilation time capture status
  106110. */
  106111. get: function () {
  106112. return this._captureShaderCompilationTime;
  106113. },
  106114. /**
  106115. * Enable or disable the shader compilation time capture
  106116. */
  106117. set: function (value) {
  106118. var _this = this;
  106119. if (value === this._captureShaderCompilationTime) {
  106120. return;
  106121. }
  106122. this._captureShaderCompilationTime = value;
  106123. if (value) {
  106124. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  106125. _this._shaderCompilationTime.fetchNewFrame();
  106126. _this._shaderCompilationTime.beginMonitoring();
  106127. });
  106128. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  106129. _this._shaderCompilationTime.endMonitoring();
  106130. });
  106131. }
  106132. else {
  106133. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106134. this._onBeforeShaderCompilationObserver = null;
  106135. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106136. this._onAfterShaderCompilationObserver = null;
  106137. }
  106138. },
  106139. enumerable: true,
  106140. configurable: true
  106141. });
  106142. EngineInstrumentation.prototype.dispose = function () {
  106143. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106144. this._onBeginFrameObserver = null;
  106145. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106146. this._onEndFrameObserver = null;
  106147. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106148. this._onBeforeShaderCompilationObserver = null;
  106149. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106150. this._onAfterShaderCompilationObserver = null;
  106151. this.engine = null;
  106152. };
  106153. return EngineInstrumentation;
  106154. }());
  106155. BABYLON.EngineInstrumentation = EngineInstrumentation;
  106156. })(BABYLON || (BABYLON = {}));
  106157. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  106158. var BABYLON;
  106159. (function (BABYLON) {
  106160. /**
  106161. * This class can be used to get instrumentation data from a Babylon engine
  106162. */
  106163. var SceneInstrumentation = /** @class */ (function () {
  106164. function SceneInstrumentation(scene) {
  106165. var _this = this;
  106166. this.scene = scene;
  106167. this._captureActiveMeshesEvaluationTime = false;
  106168. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  106169. this._captureRenderTargetsRenderTime = false;
  106170. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  106171. this._captureFrameTime = false;
  106172. this._frameTime = new BABYLON.PerfCounter();
  106173. this._captureRenderTime = false;
  106174. this._renderTime = new BABYLON.PerfCounter();
  106175. this._captureInterFrameTime = false;
  106176. this._interFrameTime = new BABYLON.PerfCounter();
  106177. this._captureParticlesRenderTime = false;
  106178. this._particlesRenderTime = new BABYLON.PerfCounter();
  106179. this._captureSpritesRenderTime = false;
  106180. this._spritesRenderTime = new BABYLON.PerfCounter();
  106181. this._capturePhysicsTime = false;
  106182. this._physicsTime = new BABYLON.PerfCounter();
  106183. this._captureAnimationsTime = false;
  106184. this._animationsTime = new BABYLON.PerfCounter();
  106185. this._captureCameraRenderTime = false;
  106186. this._cameraRenderTime = new BABYLON.PerfCounter();
  106187. // Observers
  106188. this._onBeforeActiveMeshesEvaluationObserver = null;
  106189. this._onAfterActiveMeshesEvaluationObserver = null;
  106190. this._onBeforeRenderTargetsRenderObserver = null;
  106191. this._onAfterRenderTargetsRenderObserver = null;
  106192. this._onAfterRenderObserver = null;
  106193. this._onBeforeDrawPhaseObserver = null;
  106194. this._onAfterDrawPhaseObserver = null;
  106195. this._onBeforeAnimationsObserver = null;
  106196. this._onBeforeParticlesRenderingObserver = null;
  106197. this._onAfterParticlesRenderingObserver = null;
  106198. this._onBeforeSpritesRenderingObserver = null;
  106199. this._onAfterSpritesRenderingObserver = null;
  106200. this._onBeforePhysicsObserver = null;
  106201. this._onAfterPhysicsObserver = null;
  106202. this._onAfterAnimationsObserver = null;
  106203. this._onBeforeCameraRenderObserver = null;
  106204. this._onAfterCameraRenderObserver = null;
  106205. // Before render
  106206. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  106207. if (_this._captureActiveMeshesEvaluationTime) {
  106208. _this._activeMeshesEvaluationTime.fetchNewFrame();
  106209. }
  106210. if (_this._captureRenderTargetsRenderTime) {
  106211. _this._renderTargetsRenderTime.fetchNewFrame();
  106212. }
  106213. if (_this._captureFrameTime) {
  106214. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  106215. _this._frameTime.beginMonitoring();
  106216. }
  106217. if (_this._captureInterFrameTime) {
  106218. _this._interFrameTime.endMonitoring();
  106219. }
  106220. if (_this._captureParticlesRenderTime) {
  106221. _this._particlesRenderTime.fetchNewFrame();
  106222. }
  106223. if (_this._captureSpritesRenderTime) {
  106224. _this._spritesRenderTime.fetchNewFrame();
  106225. }
  106226. if (_this._captureAnimationsTime) {
  106227. _this._animationsTime.beginMonitoring();
  106228. }
  106229. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  106230. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  106231. });
  106232. // After render
  106233. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  106234. if (_this._captureFrameTime) {
  106235. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  106236. _this._frameTime.endMonitoring();
  106237. }
  106238. if (_this._captureRenderTime) {
  106239. _this._renderTime.endMonitoring(false);
  106240. }
  106241. if (_this._captureInterFrameTime) {
  106242. _this._interFrameTime.beginMonitoring();
  106243. }
  106244. });
  106245. }
  106246. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  106247. // Properties
  106248. /**
  106249. * Gets the perf counter used for active meshes evaluation time
  106250. */
  106251. get: function () {
  106252. return this._activeMeshesEvaluationTime;
  106253. },
  106254. enumerable: true,
  106255. configurable: true
  106256. });
  106257. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  106258. /**
  106259. * Gets the active meshes evaluation time capture status
  106260. */
  106261. get: function () {
  106262. return this._captureActiveMeshesEvaluationTime;
  106263. },
  106264. /**
  106265. * Enable or disable the active meshes evaluation time capture
  106266. */
  106267. set: function (value) {
  106268. var _this = this;
  106269. if (value === this._captureActiveMeshesEvaluationTime) {
  106270. return;
  106271. }
  106272. this._captureActiveMeshesEvaluationTime = value;
  106273. if (value) {
  106274. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  106275. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  106276. _this._activeMeshesEvaluationTime.beginMonitoring();
  106277. });
  106278. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  106279. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  106280. _this._activeMeshesEvaluationTime.endMonitoring();
  106281. });
  106282. }
  106283. else {
  106284. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106285. this._onBeforeActiveMeshesEvaluationObserver = null;
  106286. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106287. this._onAfterActiveMeshesEvaluationObserver = null;
  106288. }
  106289. },
  106290. enumerable: true,
  106291. configurable: true
  106292. });
  106293. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  106294. /**
  106295. * Gets the perf counter used for render targets render time
  106296. */
  106297. get: function () {
  106298. return this._renderTargetsRenderTime;
  106299. },
  106300. enumerable: true,
  106301. configurable: true
  106302. });
  106303. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  106304. /**
  106305. * Gets the render targets render time capture status
  106306. */
  106307. get: function () {
  106308. return this._captureRenderTargetsRenderTime;
  106309. },
  106310. /**
  106311. * Enable or disable the render targets render time capture
  106312. */
  106313. set: function (value) {
  106314. var _this = this;
  106315. if (value === this._captureRenderTargetsRenderTime) {
  106316. return;
  106317. }
  106318. this._captureRenderTargetsRenderTime = value;
  106319. if (value) {
  106320. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  106321. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  106322. _this._renderTargetsRenderTime.beginMonitoring();
  106323. });
  106324. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  106325. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  106326. _this._renderTargetsRenderTime.endMonitoring(false);
  106327. });
  106328. }
  106329. else {
  106330. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106331. this._onBeforeRenderTargetsRenderObserver = null;
  106332. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106333. this._onAfterRenderTargetsRenderObserver = null;
  106334. }
  106335. },
  106336. enumerable: true,
  106337. configurable: true
  106338. });
  106339. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  106340. /**
  106341. * Gets the perf counter used for particles render time
  106342. */
  106343. get: function () {
  106344. return this._particlesRenderTime;
  106345. },
  106346. enumerable: true,
  106347. configurable: true
  106348. });
  106349. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  106350. /**
  106351. * Gets the particles render time capture status
  106352. */
  106353. get: function () {
  106354. return this._captureParticlesRenderTime;
  106355. },
  106356. /**
  106357. * Enable or disable the particles render time capture
  106358. */
  106359. set: function (value) {
  106360. var _this = this;
  106361. if (value === this._captureParticlesRenderTime) {
  106362. return;
  106363. }
  106364. this._captureParticlesRenderTime = value;
  106365. if (value) {
  106366. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  106367. BABYLON.Tools.StartPerformanceCounter("Particles");
  106368. _this._particlesRenderTime.beginMonitoring();
  106369. });
  106370. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  106371. BABYLON.Tools.EndPerformanceCounter("Particles");
  106372. _this._particlesRenderTime.endMonitoring(false);
  106373. });
  106374. }
  106375. else {
  106376. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106377. this._onBeforeParticlesRenderingObserver = null;
  106378. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106379. this._onAfterParticlesRenderingObserver = null;
  106380. }
  106381. },
  106382. enumerable: true,
  106383. configurable: true
  106384. });
  106385. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  106386. /**
  106387. * Gets the perf counter used for sprites render time
  106388. */
  106389. get: function () {
  106390. return this._spritesRenderTime;
  106391. },
  106392. enumerable: true,
  106393. configurable: true
  106394. });
  106395. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  106396. /**
  106397. * Gets the sprites render time capture status
  106398. */
  106399. get: function () {
  106400. return this._captureSpritesRenderTime;
  106401. },
  106402. /**
  106403. * Enable or disable the sprites render time capture
  106404. */
  106405. set: function (value) {
  106406. var _this = this;
  106407. if (value === this._captureSpritesRenderTime) {
  106408. return;
  106409. }
  106410. this._captureSpritesRenderTime = value;
  106411. if (!this.scene.spriteManagers) {
  106412. return;
  106413. }
  106414. if (value) {
  106415. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  106416. BABYLON.Tools.StartPerformanceCounter("Sprites");
  106417. _this._spritesRenderTime.beginMonitoring();
  106418. });
  106419. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  106420. BABYLON.Tools.EndPerformanceCounter("Sprites");
  106421. _this._spritesRenderTime.endMonitoring(false);
  106422. });
  106423. }
  106424. else {
  106425. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106426. this._onBeforeSpritesRenderingObserver = null;
  106427. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106428. this._onAfterSpritesRenderingObserver = null;
  106429. }
  106430. },
  106431. enumerable: true,
  106432. configurable: true
  106433. });
  106434. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  106435. /**
  106436. * Gets the perf counter used for physics time
  106437. */
  106438. get: function () {
  106439. return this._physicsTime;
  106440. },
  106441. enumerable: true,
  106442. configurable: true
  106443. });
  106444. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  106445. /**
  106446. * Gets the physics time capture status
  106447. */
  106448. get: function () {
  106449. return this._capturePhysicsTime;
  106450. },
  106451. /**
  106452. * Enable or disable the physics time capture
  106453. */
  106454. set: function (value) {
  106455. var _this = this;
  106456. if (value === this._capturePhysicsTime) {
  106457. return;
  106458. }
  106459. this._capturePhysicsTime = value;
  106460. if (value) {
  106461. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  106462. BABYLON.Tools.StartPerformanceCounter("Physics");
  106463. _this._physicsTime.beginMonitoring();
  106464. });
  106465. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  106466. BABYLON.Tools.EndPerformanceCounter("Physics");
  106467. _this._physicsTime.endMonitoring();
  106468. });
  106469. }
  106470. else {
  106471. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106472. this._onBeforePhysicsObserver = null;
  106473. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106474. this._onAfterPhysicsObserver = null;
  106475. }
  106476. },
  106477. enumerable: true,
  106478. configurable: true
  106479. });
  106480. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  106481. /**
  106482. * Gets the perf counter used for animations time
  106483. */
  106484. get: function () {
  106485. return this._animationsTime;
  106486. },
  106487. enumerable: true,
  106488. configurable: true
  106489. });
  106490. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  106491. /**
  106492. * Gets the animations time capture status
  106493. */
  106494. get: function () {
  106495. return this._captureAnimationsTime;
  106496. },
  106497. /**
  106498. * Enable or disable the animations time capture
  106499. */
  106500. set: function (value) {
  106501. var _this = this;
  106502. if (value === this._captureAnimationsTime) {
  106503. return;
  106504. }
  106505. this._captureAnimationsTime = value;
  106506. if (value) {
  106507. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  106508. _this._animationsTime.endMonitoring();
  106509. });
  106510. }
  106511. else {
  106512. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106513. this._onAfterAnimationsObserver = null;
  106514. }
  106515. },
  106516. enumerable: true,
  106517. configurable: true
  106518. });
  106519. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  106520. /**
  106521. * Gets the perf counter used for frame time capture
  106522. */
  106523. get: function () {
  106524. return this._frameTime;
  106525. },
  106526. enumerable: true,
  106527. configurable: true
  106528. });
  106529. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  106530. /**
  106531. * Gets the frame time capture status
  106532. */
  106533. get: function () {
  106534. return this._captureFrameTime;
  106535. },
  106536. /**
  106537. * Enable or disable the frame time capture
  106538. */
  106539. set: function (value) {
  106540. this._captureFrameTime = value;
  106541. },
  106542. enumerable: true,
  106543. configurable: true
  106544. });
  106545. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  106546. /**
  106547. * Gets the perf counter used for inter-frames time capture
  106548. */
  106549. get: function () {
  106550. return this._interFrameTime;
  106551. },
  106552. enumerable: true,
  106553. configurable: true
  106554. });
  106555. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  106556. /**
  106557. * Gets the inter-frames time capture status
  106558. */
  106559. get: function () {
  106560. return this._captureInterFrameTime;
  106561. },
  106562. /**
  106563. * Enable or disable the inter-frames time capture
  106564. */
  106565. set: function (value) {
  106566. this._captureInterFrameTime = value;
  106567. },
  106568. enumerable: true,
  106569. configurable: true
  106570. });
  106571. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  106572. /**
  106573. * Gets the perf counter used for render time capture
  106574. */
  106575. get: function () {
  106576. return this._renderTime;
  106577. },
  106578. enumerable: true,
  106579. configurable: true
  106580. });
  106581. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  106582. /**
  106583. * Gets the render time capture status
  106584. */
  106585. get: function () {
  106586. return this._captureRenderTime;
  106587. },
  106588. /**
  106589. * Enable or disable the render time capture
  106590. */
  106591. set: function (value) {
  106592. var _this = this;
  106593. if (value === this._captureRenderTime) {
  106594. return;
  106595. }
  106596. this._captureRenderTime = value;
  106597. if (value) {
  106598. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  106599. _this._renderTime.beginMonitoring();
  106600. BABYLON.Tools.StartPerformanceCounter("Main render");
  106601. });
  106602. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  106603. _this._renderTime.endMonitoring(false);
  106604. BABYLON.Tools.EndPerformanceCounter("Main render");
  106605. });
  106606. }
  106607. else {
  106608. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  106609. this._onBeforeDrawPhaseObserver = null;
  106610. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  106611. this._onAfterDrawPhaseObserver = null;
  106612. }
  106613. },
  106614. enumerable: true,
  106615. configurable: true
  106616. });
  106617. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  106618. /**
  106619. * Gets the perf counter used for camera render time capture
  106620. */
  106621. get: function () {
  106622. return this._cameraRenderTime;
  106623. },
  106624. enumerable: true,
  106625. configurable: true
  106626. });
  106627. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  106628. /**
  106629. * Gets the camera render time capture status
  106630. */
  106631. get: function () {
  106632. return this._captureCameraRenderTime;
  106633. },
  106634. /**
  106635. * Enable or disable the camera render time capture
  106636. */
  106637. set: function (value) {
  106638. var _this = this;
  106639. if (value === this._captureCameraRenderTime) {
  106640. return;
  106641. }
  106642. this._captureCameraRenderTime = value;
  106643. if (value) {
  106644. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  106645. _this._cameraRenderTime.beginMonitoring();
  106646. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  106647. });
  106648. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  106649. _this._cameraRenderTime.endMonitoring(false);
  106650. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  106651. });
  106652. }
  106653. else {
  106654. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  106655. this._onBeforeCameraRenderObserver = null;
  106656. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  106657. this._onAfterCameraRenderObserver = null;
  106658. }
  106659. },
  106660. enumerable: true,
  106661. configurable: true
  106662. });
  106663. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  106664. /**
  106665. * Gets the perf counter used for draw calls
  106666. */
  106667. get: function () {
  106668. return this.scene.getEngine()._drawCalls;
  106669. },
  106670. enumerable: true,
  106671. configurable: true
  106672. });
  106673. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  106674. /**
  106675. * Gets the perf counter used for texture collisions
  106676. */
  106677. get: function () {
  106678. return this.scene.getEngine()._textureCollisions;
  106679. },
  106680. enumerable: true,
  106681. configurable: true
  106682. });
  106683. SceneInstrumentation.prototype.dispose = function () {
  106684. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  106685. this._onAfterRenderObserver = null;
  106686. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106687. this._onBeforeActiveMeshesEvaluationObserver = null;
  106688. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106689. this._onAfterActiveMeshesEvaluationObserver = null;
  106690. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106691. this._onBeforeRenderTargetsRenderObserver = null;
  106692. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106693. this._onAfterRenderTargetsRenderObserver = null;
  106694. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  106695. this._onBeforeAnimationsObserver = null;
  106696. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106697. this._onBeforeParticlesRenderingObserver = null;
  106698. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106699. this._onAfterParticlesRenderingObserver = null;
  106700. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106701. this._onBeforeSpritesRenderingObserver = null;
  106702. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106703. this._onAfterSpritesRenderingObserver = null;
  106704. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  106705. this._onBeforeDrawPhaseObserver = null;
  106706. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  106707. this._onAfterDrawPhaseObserver = null;
  106708. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106709. this._onBeforePhysicsObserver = null;
  106710. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106711. this._onAfterPhysicsObserver = null;
  106712. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106713. this._onAfterAnimationsObserver = null;
  106714. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  106715. this._onBeforeCameraRenderObserver = null;
  106716. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  106717. this._onAfterCameraRenderObserver = null;
  106718. this.scene = null;
  106719. };
  106720. return SceneInstrumentation;
  106721. }());
  106722. BABYLON.SceneInstrumentation = SceneInstrumentation;
  106723. })(BABYLON || (BABYLON = {}));
  106724. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  106725. var BABYLON;
  106726. (function (BABYLON) {
  106727. /**
  106728. * @hidden
  106729. **/
  106730. var _TimeToken = /** @class */ (function () {
  106731. function _TimeToken() {
  106732. this._timeElapsedQueryEnded = false;
  106733. }
  106734. return _TimeToken;
  106735. }());
  106736. BABYLON._TimeToken = _TimeToken;
  106737. })(BABYLON || (BABYLON = {}));
  106738. //# sourceMappingURL=babylon.timeToken.js.map
  106739. var BABYLON;
  106740. (function (BABYLON) {
  106741. /**
  106742. * Background material defines definition.
  106743. * @hidden Mainly internal Use
  106744. */
  106745. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  106746. __extends(BackgroundMaterialDefines, _super);
  106747. /**
  106748. * Constructor of the defines.
  106749. */
  106750. function BackgroundMaterialDefines() {
  106751. var _this = _super.call(this) || this;
  106752. /**
  106753. * True if the diffuse texture is in use.
  106754. */
  106755. _this.DIFFUSE = false;
  106756. /**
  106757. * The direct UV channel to use.
  106758. */
  106759. _this.DIFFUSEDIRECTUV = 0;
  106760. /**
  106761. * True if the diffuse texture is in gamma space.
  106762. */
  106763. _this.GAMMADIFFUSE = false;
  106764. /**
  106765. * True if the diffuse texture has opacity in the alpha channel.
  106766. */
  106767. _this.DIFFUSEHASALPHA = false;
  106768. /**
  106769. * True if you want the material to fade to transparent at grazing angle.
  106770. */
  106771. _this.OPACITYFRESNEL = false;
  106772. /**
  106773. * True if an extra blur needs to be added in the reflection.
  106774. */
  106775. _this.REFLECTIONBLUR = false;
  106776. /**
  106777. * True if you want the material to fade to reflection at grazing angle.
  106778. */
  106779. _this.REFLECTIONFRESNEL = false;
  106780. /**
  106781. * True if you want the material to falloff as far as you move away from the scene center.
  106782. */
  106783. _this.REFLECTIONFALLOFF = false;
  106784. /**
  106785. * False if the current Webgl implementation does not support the texture lod extension.
  106786. */
  106787. _this.TEXTURELODSUPPORT = false;
  106788. /**
  106789. * True to ensure the data are premultiplied.
  106790. */
  106791. _this.PREMULTIPLYALPHA = false;
  106792. /**
  106793. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  106794. */
  106795. _this.USERGBCOLOR = false;
  106796. /**
  106797. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  106798. * stays aligned with the desired configuration.
  106799. */
  106800. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  106801. /**
  106802. * True to add noise in order to reduce the banding effect.
  106803. */
  106804. _this.NOISE = false;
  106805. /**
  106806. * is the reflection texture in BGR color scheme?
  106807. * Mainly used to solve a bug in ios10 video tag
  106808. */
  106809. _this.REFLECTIONBGR = false;
  106810. _this.IMAGEPROCESSING = false;
  106811. _this.VIGNETTE = false;
  106812. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  106813. _this.VIGNETTEBLENDMODEOPAQUE = false;
  106814. _this.TONEMAPPING = false;
  106815. _this.TONEMAPPING_ACES = false;
  106816. _this.CONTRAST = false;
  106817. _this.COLORCURVES = false;
  106818. _this.COLORGRADING = false;
  106819. _this.COLORGRADING3D = false;
  106820. _this.SAMPLER3DGREENDEPTH = false;
  106821. _this.SAMPLER3DBGRMAP = false;
  106822. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  106823. _this.EXPOSURE = false;
  106824. // Reflection.
  106825. _this.REFLECTION = false;
  106826. _this.REFLECTIONMAP_3D = false;
  106827. _this.REFLECTIONMAP_SPHERICAL = false;
  106828. _this.REFLECTIONMAP_PLANAR = false;
  106829. _this.REFLECTIONMAP_CUBIC = false;
  106830. _this.REFLECTIONMAP_PROJECTION = false;
  106831. _this.REFLECTIONMAP_SKYBOX = false;
  106832. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  106833. _this.REFLECTIONMAP_EXPLICIT = false;
  106834. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  106835. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  106836. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  106837. _this.INVERTCUBICMAP = false;
  106838. _this.REFLECTIONMAP_OPPOSITEZ = false;
  106839. _this.LODINREFLECTIONALPHA = false;
  106840. _this.GAMMAREFLECTION = false;
  106841. _this.RGBDREFLECTION = false;
  106842. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  106843. // Default BJS.
  106844. _this.MAINUV1 = false;
  106845. _this.MAINUV2 = false;
  106846. _this.UV1 = false;
  106847. _this.UV2 = false;
  106848. _this.CLIPPLANE = false;
  106849. _this.CLIPPLANE2 = false;
  106850. _this.CLIPPLANE3 = false;
  106851. _this.CLIPPLANE4 = false;
  106852. _this.POINTSIZE = false;
  106853. _this.FOG = false;
  106854. _this.NORMAL = false;
  106855. _this.NUM_BONE_INFLUENCERS = 0;
  106856. _this.BonesPerMesh = 0;
  106857. _this.INSTANCES = false;
  106858. _this.SHADOWFLOAT = false;
  106859. _this.rebuild();
  106860. return _this;
  106861. }
  106862. return BackgroundMaterialDefines;
  106863. }(BABYLON.MaterialDefines));
  106864. /**
  106865. * Background material used to create an efficient environement around your scene.
  106866. */
  106867. var BackgroundMaterial = /** @class */ (function (_super) {
  106868. __extends(BackgroundMaterial, _super);
  106869. /**
  106870. * Instantiates a Background Material in the given scene
  106871. * @param name The friendly name of the material
  106872. * @param scene The scene to add the material to
  106873. */
  106874. function BackgroundMaterial(name, scene) {
  106875. var _this = _super.call(this, name, scene) || this;
  106876. /**
  106877. * Key light Color (multiply against the environement texture)
  106878. */
  106879. _this.primaryColor = BABYLON.Color3.White();
  106880. _this._primaryColorShadowLevel = 0;
  106881. _this._primaryColorHighlightLevel = 0;
  106882. /**
  106883. * Reflection Texture used in the material.
  106884. * Should be author in a specific way for the best result (refer to the documentation).
  106885. */
  106886. _this.reflectionTexture = null;
  106887. /**
  106888. * Reflection Texture level of blur.
  106889. *
  106890. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  106891. * texture twice.
  106892. */
  106893. _this.reflectionBlur = 0;
  106894. /**
  106895. * Diffuse Texture used in the material.
  106896. * Should be author in a specific way for the best result (refer to the documentation).
  106897. */
  106898. _this.diffuseTexture = null;
  106899. _this._shadowLights = null;
  106900. /**
  106901. * Specify the list of lights casting shadow on the material.
  106902. * All scene shadow lights will be included if null.
  106903. */
  106904. _this.shadowLights = null;
  106905. /**
  106906. * Helps adjusting the shadow to a softer level if required.
  106907. * 0 means black shadows and 1 means no shadows.
  106908. */
  106909. _this.shadowLevel = 0;
  106910. /**
  106911. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  106912. * It is usually zero but might be interesting to modify according to your setup.
  106913. */
  106914. _this.sceneCenter = BABYLON.Vector3.Zero();
  106915. /**
  106916. * This helps specifying that the material is falling off to the sky box at grazing angle.
  106917. * This helps ensuring a nice transition when the camera goes under the ground.
  106918. */
  106919. _this.opacityFresnel = true;
  106920. /**
  106921. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  106922. * This helps adding a mirror texture on the ground.
  106923. */
  106924. _this.reflectionFresnel = false;
  106925. /**
  106926. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  106927. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  106928. */
  106929. _this.reflectionFalloffDistance = 0.0;
  106930. /**
  106931. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  106932. */
  106933. _this.reflectionAmount = 1.0;
  106934. /**
  106935. * This specifies the weight of the reflection at grazing angle.
  106936. */
  106937. _this.reflectionReflectance0 = 0.05;
  106938. /**
  106939. * This specifies the weight of the reflection at a perpendicular point of view.
  106940. */
  106941. _this.reflectionReflectance90 = 0.5;
  106942. /**
  106943. * Helps to directly use the maps channels instead of their level.
  106944. */
  106945. _this.useRGBColor = true;
  106946. /**
  106947. * This helps reducing the banding effect that could occur on the background.
  106948. */
  106949. _this.enableNoise = false;
  106950. _this._fovMultiplier = 1.0;
  106951. /**
  106952. * Enable the FOV adjustment feature controlled by fovMultiplier.
  106953. */
  106954. _this.useEquirectangularFOV = false;
  106955. _this._maxSimultaneousLights = 4;
  106956. /**
  106957. * Number of Simultaneous lights allowed on the material.
  106958. */
  106959. _this.maxSimultaneousLights = 4;
  106960. /**
  106961. * Keep track of the image processing observer to allow dispose and replace.
  106962. */
  106963. _this._imageProcessingObserver = null;
  106964. /**
  106965. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  106966. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  106967. */
  106968. _this.switchToBGR = false;
  106969. // Temp values kept as cache in the material.
  106970. _this._renderTargets = new BABYLON.SmartArray(16);
  106971. _this._reflectionControls = BABYLON.Vector4.Zero();
  106972. _this._white = BABYLON.Color3.White();
  106973. _this._primaryShadowColor = BABYLON.Color3.Black();
  106974. _this._primaryHighlightColor = BABYLON.Color3.Black();
  106975. // Setup the default processing configuration to the scene.
  106976. _this._attachImageProcessingConfiguration(null);
  106977. _this.getRenderTargetTextures = function () {
  106978. _this._renderTargets.reset();
  106979. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  106980. _this._renderTargets.push(_this._diffuseTexture);
  106981. }
  106982. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  106983. _this._renderTargets.push(_this._reflectionTexture);
  106984. }
  106985. return _this._renderTargets;
  106986. };
  106987. return _this;
  106988. }
  106989. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  106990. /**
  106991. * Experimental Internal Use Only.
  106992. *
  106993. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  106994. * This acts as a helper to set the primary color to a more "human friendly" value.
  106995. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  106996. * output color as close as possible from the chosen value.
  106997. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  106998. * part of lighting setup.)
  106999. */
  107000. get: function () {
  107001. return this.__perceptualColor;
  107002. },
  107003. set: function (value) {
  107004. this.__perceptualColor = value;
  107005. this._computePrimaryColorFromPerceptualColor();
  107006. this._markAllSubMeshesAsLightsDirty();
  107007. },
  107008. enumerable: true,
  107009. configurable: true
  107010. });
  107011. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  107012. /**
  107013. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  107014. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  107015. */
  107016. get: function () {
  107017. return this._primaryColorShadowLevel;
  107018. },
  107019. set: function (value) {
  107020. this._primaryColorShadowLevel = value;
  107021. this._computePrimaryColors();
  107022. this._markAllSubMeshesAsLightsDirty();
  107023. },
  107024. enumerable: true,
  107025. configurable: true
  107026. });
  107027. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  107028. /**
  107029. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  107030. * The primary color is used at the level chosen to define what the white area would look.
  107031. */
  107032. get: function () {
  107033. return this._primaryColorHighlightLevel;
  107034. },
  107035. set: function (value) {
  107036. this._primaryColorHighlightLevel = value;
  107037. this._computePrimaryColors();
  107038. this._markAllSubMeshesAsLightsDirty();
  107039. },
  107040. enumerable: true,
  107041. configurable: true
  107042. });
  107043. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  107044. /**
  107045. * Sets the reflection reflectance fresnel values according to the default standard
  107046. * empirically know to work well :-)
  107047. */
  107048. set: function (value) {
  107049. var reflectionWeight = value;
  107050. if (reflectionWeight < 0.5) {
  107051. reflectionWeight = reflectionWeight * 2.0;
  107052. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  107053. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  107054. }
  107055. else {
  107056. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  107057. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  107058. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  107059. }
  107060. },
  107061. enumerable: true,
  107062. configurable: true
  107063. });
  107064. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  107065. /**
  107066. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107067. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  107068. * Recommended to be keep at 1.0 except for special cases.
  107069. */
  107070. get: function () {
  107071. return this._fovMultiplier;
  107072. },
  107073. set: function (value) {
  107074. if (isNaN(value)) {
  107075. value = 1.0;
  107076. }
  107077. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  107078. },
  107079. enumerable: true,
  107080. configurable: true
  107081. });
  107082. /**
  107083. * Attaches a new image processing configuration to the PBR Material.
  107084. * @param configuration (if null the scene configuration will be use)
  107085. */
  107086. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  107087. var _this = this;
  107088. if (configuration === this._imageProcessingConfiguration) {
  107089. return;
  107090. }
  107091. // Detaches observer.
  107092. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107093. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107094. }
  107095. // Pick the scene configuration if needed.
  107096. if (!configuration) {
  107097. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  107098. }
  107099. else {
  107100. this._imageProcessingConfiguration = configuration;
  107101. }
  107102. // Attaches observer.
  107103. if (this._imageProcessingConfiguration) {
  107104. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  107105. _this._computePrimaryColorFromPerceptualColor();
  107106. _this._markAllSubMeshesAsImageProcessingDirty();
  107107. });
  107108. }
  107109. };
  107110. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  107111. /**
  107112. * Gets the image processing configuration used either in this material.
  107113. */
  107114. get: function () {
  107115. return this._imageProcessingConfiguration;
  107116. },
  107117. /**
  107118. * Sets the Default image processing configuration used either in the this material.
  107119. *
  107120. * If sets to null, the scene one is in use.
  107121. */
  107122. set: function (value) {
  107123. this._attachImageProcessingConfiguration(value);
  107124. // Ensure the effect will be rebuilt.
  107125. this._markAllSubMeshesAsTexturesDirty();
  107126. },
  107127. enumerable: true,
  107128. configurable: true
  107129. });
  107130. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  107131. /**
  107132. * Gets wether the color curves effect is enabled.
  107133. */
  107134. get: function () {
  107135. return this.imageProcessingConfiguration.colorCurvesEnabled;
  107136. },
  107137. /**
  107138. * Sets wether the color curves effect is enabled.
  107139. */
  107140. set: function (value) {
  107141. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  107142. },
  107143. enumerable: true,
  107144. configurable: true
  107145. });
  107146. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  107147. /**
  107148. * Gets wether the color grading effect is enabled.
  107149. */
  107150. get: function () {
  107151. return this.imageProcessingConfiguration.colorGradingEnabled;
  107152. },
  107153. /**
  107154. * Gets wether the color grading effect is enabled.
  107155. */
  107156. set: function (value) {
  107157. this.imageProcessingConfiguration.colorGradingEnabled = value;
  107158. },
  107159. enumerable: true,
  107160. configurable: true
  107161. });
  107162. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  107163. /**
  107164. * Gets wether tonemapping is enabled or not.
  107165. */
  107166. get: function () {
  107167. return this._imageProcessingConfiguration.toneMappingEnabled;
  107168. },
  107169. /**
  107170. * Sets wether tonemapping is enabled or not
  107171. */
  107172. set: function (value) {
  107173. this._imageProcessingConfiguration.toneMappingEnabled = value;
  107174. },
  107175. enumerable: true,
  107176. configurable: true
  107177. });
  107178. ;
  107179. ;
  107180. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  107181. /**
  107182. * The camera exposure used on this material.
  107183. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107184. * This corresponds to a photographic exposure.
  107185. */
  107186. get: function () {
  107187. return this._imageProcessingConfiguration.exposure;
  107188. },
  107189. /**
  107190. * The camera exposure used on this material.
  107191. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107192. * This corresponds to a photographic exposure.
  107193. */
  107194. set: function (value) {
  107195. this._imageProcessingConfiguration.exposure = value;
  107196. },
  107197. enumerable: true,
  107198. configurable: true
  107199. });
  107200. ;
  107201. ;
  107202. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  107203. /**
  107204. * Gets The camera contrast used on this material.
  107205. */
  107206. get: function () {
  107207. return this._imageProcessingConfiguration.contrast;
  107208. },
  107209. /**
  107210. * Sets The camera contrast used on this material.
  107211. */
  107212. set: function (value) {
  107213. this._imageProcessingConfiguration.contrast = value;
  107214. },
  107215. enumerable: true,
  107216. configurable: true
  107217. });
  107218. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  107219. /**
  107220. * Gets the Color Grading 2D Lookup Texture.
  107221. */
  107222. get: function () {
  107223. return this._imageProcessingConfiguration.colorGradingTexture;
  107224. },
  107225. /**
  107226. * Sets the Color Grading 2D Lookup Texture.
  107227. */
  107228. set: function (value) {
  107229. this.imageProcessingConfiguration.colorGradingTexture = value;
  107230. },
  107231. enumerable: true,
  107232. configurable: true
  107233. });
  107234. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  107235. /**
  107236. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107237. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107238. * 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;
  107239. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107240. */
  107241. get: function () {
  107242. return this.imageProcessingConfiguration.colorCurves;
  107243. },
  107244. /**
  107245. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107246. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107247. * 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;
  107248. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107249. */
  107250. set: function (value) {
  107251. this.imageProcessingConfiguration.colorCurves = value;
  107252. },
  107253. enumerable: true,
  107254. configurable: true
  107255. });
  107256. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  107257. /**
  107258. * Gets a boolean indicating that current material needs to register RTT
  107259. */
  107260. get: function () {
  107261. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107262. return true;
  107263. }
  107264. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107265. return true;
  107266. }
  107267. return false;
  107268. },
  107269. enumerable: true,
  107270. configurable: true
  107271. });
  107272. /**
  107273. * The entire material has been created in order to prevent overdraw.
  107274. * @returns false
  107275. */
  107276. BackgroundMaterial.prototype.needAlphaTesting = function () {
  107277. return true;
  107278. };
  107279. /**
  107280. * The entire material has been created in order to prevent overdraw.
  107281. * @returns true if blending is enable
  107282. */
  107283. BackgroundMaterial.prototype.needAlphaBlending = function () {
  107284. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  107285. };
  107286. /**
  107287. * Checks wether the material is ready to be rendered for a given mesh.
  107288. * @param mesh The mesh to render
  107289. * @param subMesh The submesh to check against
  107290. * @param useInstances Specify wether or not the material is used with instances
  107291. * @returns true if all the dependencies are ready (Textures, Effects...)
  107292. */
  107293. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  107294. var _this = this;
  107295. if (useInstances === void 0) { useInstances = false; }
  107296. if (subMesh.effect && this.isFrozen) {
  107297. if (this._wasPreviouslyReady) {
  107298. return true;
  107299. }
  107300. }
  107301. if (!subMesh._materialDefines) {
  107302. subMesh._materialDefines = new BackgroundMaterialDefines();
  107303. }
  107304. var scene = this.getScene();
  107305. var defines = subMesh._materialDefines;
  107306. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  107307. if (defines._renderId === scene.getRenderId()) {
  107308. return true;
  107309. }
  107310. }
  107311. var engine = scene.getEngine();
  107312. // Lights
  107313. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  107314. defines._needNormals = true;
  107315. // Textures
  107316. if (defines._areTexturesDirty) {
  107317. defines._needUVs = false;
  107318. if (scene.texturesEnabled) {
  107319. if (scene.getEngine().getCaps().textureLOD) {
  107320. defines.TEXTURELODSUPPORT = true;
  107321. }
  107322. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107323. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  107324. return false;
  107325. }
  107326. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  107327. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  107328. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  107329. defines.OPACITYFRESNEL = this._opacityFresnel;
  107330. }
  107331. else {
  107332. defines.DIFFUSE = false;
  107333. defines.DIFFUSEHASALPHA = false;
  107334. defines.GAMMADIFFUSE = false;
  107335. defines.OPACITYFRESNEL = false;
  107336. }
  107337. var reflectionTexture = this._reflectionTexture;
  107338. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107339. if (!reflectionTexture.isReadyOrNotBlocking()) {
  107340. return false;
  107341. }
  107342. defines.REFLECTION = true;
  107343. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  107344. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  107345. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  107346. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  107347. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  107348. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  107349. defines.REFLECTIONBGR = this.switchToBGR;
  107350. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  107351. defines.INVERTCUBICMAP = true;
  107352. }
  107353. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  107354. switch (reflectionTexture.coordinatesMode) {
  107355. case BABYLON.Texture.EXPLICIT_MODE:
  107356. defines.REFLECTIONMAP_EXPLICIT = true;
  107357. break;
  107358. case BABYLON.Texture.PLANAR_MODE:
  107359. defines.REFLECTIONMAP_PLANAR = true;
  107360. break;
  107361. case BABYLON.Texture.PROJECTION_MODE:
  107362. defines.REFLECTIONMAP_PROJECTION = true;
  107363. break;
  107364. case BABYLON.Texture.SKYBOX_MODE:
  107365. defines.REFLECTIONMAP_SKYBOX = true;
  107366. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  107367. break;
  107368. case BABYLON.Texture.SPHERICAL_MODE:
  107369. defines.REFLECTIONMAP_SPHERICAL = true;
  107370. break;
  107371. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  107372. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  107373. break;
  107374. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  107375. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  107376. break;
  107377. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  107378. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  107379. break;
  107380. case BABYLON.Texture.CUBIC_MODE:
  107381. case BABYLON.Texture.INVCUBIC_MODE:
  107382. default:
  107383. defines.REFLECTIONMAP_CUBIC = true;
  107384. break;
  107385. }
  107386. if (this.reflectionFresnel) {
  107387. defines.REFLECTIONFRESNEL = true;
  107388. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  107389. this._reflectionControls.x = this.reflectionAmount;
  107390. this._reflectionControls.y = this.reflectionReflectance0;
  107391. this._reflectionControls.z = this.reflectionReflectance90;
  107392. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  107393. }
  107394. else {
  107395. defines.REFLECTIONFRESNEL = false;
  107396. defines.REFLECTIONFALLOFF = false;
  107397. }
  107398. }
  107399. else {
  107400. defines.REFLECTION = false;
  107401. defines.REFLECTIONFRESNEL = false;
  107402. defines.REFLECTIONFALLOFF = false;
  107403. defines.REFLECTIONBLUR = false;
  107404. defines.REFLECTIONMAP_3D = false;
  107405. defines.REFLECTIONMAP_SPHERICAL = false;
  107406. defines.REFLECTIONMAP_PLANAR = false;
  107407. defines.REFLECTIONMAP_CUBIC = false;
  107408. defines.REFLECTIONMAP_PROJECTION = false;
  107409. defines.REFLECTIONMAP_SKYBOX = false;
  107410. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107411. defines.REFLECTIONMAP_EXPLICIT = false;
  107412. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107413. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107414. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107415. defines.INVERTCUBICMAP = false;
  107416. defines.REFLECTIONMAP_OPPOSITEZ = false;
  107417. defines.LODINREFLECTIONALPHA = false;
  107418. defines.GAMMAREFLECTION = false;
  107419. defines.RGBDREFLECTION = false;
  107420. }
  107421. }
  107422. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  107423. defines.USERGBCOLOR = this._useRGBColor;
  107424. defines.NOISE = this._enableNoise;
  107425. }
  107426. if (defines._areLightsDirty) {
  107427. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  107428. }
  107429. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  107430. if (!this._imageProcessingConfiguration.isReady()) {
  107431. return false;
  107432. }
  107433. this._imageProcessingConfiguration.prepareDefines(defines);
  107434. }
  107435. // Misc.
  107436. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  107437. // Values that need to be evaluated on every frame
  107438. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  107439. // Attribs
  107440. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  107441. if (mesh) {
  107442. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  107443. mesh.createNormals(true);
  107444. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  107445. }
  107446. }
  107447. }
  107448. // Get correct effect
  107449. if (defines.isDirty) {
  107450. defines.markAsProcessed();
  107451. scene.resetCachedMaterial();
  107452. // Fallbacks
  107453. var fallbacks = new BABYLON.EffectFallbacks();
  107454. if (defines.FOG) {
  107455. fallbacks.addFallback(0, "FOG");
  107456. }
  107457. if (defines.POINTSIZE) {
  107458. fallbacks.addFallback(1, "POINTSIZE");
  107459. }
  107460. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  107461. if (defines.NUM_BONE_INFLUENCERS > 0) {
  107462. fallbacks.addCPUSkinningFallback(0, mesh);
  107463. }
  107464. //Attributes
  107465. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107466. if (defines.NORMAL) {
  107467. attribs.push(BABYLON.VertexBuffer.NormalKind);
  107468. }
  107469. if (defines.UV1) {
  107470. attribs.push(BABYLON.VertexBuffer.UVKind);
  107471. }
  107472. if (defines.UV2) {
  107473. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107474. }
  107475. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  107476. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  107477. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  107478. "vFogInfos", "vFogColor", "pointSize",
  107479. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  107480. "vPrimaryColor", "vPrimaryColorShadow",
  107481. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  107482. "shadowLevel", "alpha",
  107483. "vBackgroundCenter", "vReflectionControl",
  107484. "vDiffuseInfos", "diffuseMatrix",
  107485. ];
  107486. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  107487. var uniformBuffers = ["Material", "Scene"];
  107488. if (BABYLON.ImageProcessingConfiguration) {
  107489. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  107490. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  107491. }
  107492. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  107493. uniformsNames: uniforms,
  107494. uniformBuffersNames: uniformBuffers,
  107495. samplers: samplers,
  107496. defines: defines,
  107497. maxSimultaneousLights: this._maxSimultaneousLights
  107498. });
  107499. var onCompiled = function (effect) {
  107500. if (_this.onCompiled) {
  107501. _this.onCompiled(effect);
  107502. }
  107503. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  107504. };
  107505. var join = defines.toString();
  107506. subMesh.setEffect(scene.getEngine().createEffect("background", {
  107507. attributes: attribs,
  107508. uniformsNames: uniforms,
  107509. uniformBuffersNames: uniformBuffers,
  107510. samplers: samplers,
  107511. defines: join,
  107512. fallbacks: fallbacks,
  107513. onCompiled: onCompiled,
  107514. onError: this.onError,
  107515. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  107516. }, engine), defines);
  107517. this.buildUniformLayout();
  107518. }
  107519. if (!subMesh.effect || !subMesh.effect.isReady()) {
  107520. return false;
  107521. }
  107522. defines._renderId = scene.getRenderId();
  107523. this._wasPreviouslyReady = true;
  107524. return true;
  107525. };
  107526. /**
  107527. * Compute the primary color according to the chosen perceptual color.
  107528. */
  107529. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  107530. if (!this.__perceptualColor) {
  107531. return;
  107532. }
  107533. this._primaryColor.copyFrom(this.__perceptualColor);
  107534. // Revert gamma space.
  107535. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  107536. // Revert image processing configuration.
  107537. if (this._imageProcessingConfiguration) {
  107538. // Revert Exposure.
  107539. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  107540. }
  107541. this._computePrimaryColors();
  107542. };
  107543. /**
  107544. * Compute the highlights and shadow colors according to their chosen levels.
  107545. */
  107546. BackgroundMaterial.prototype._computePrimaryColors = function () {
  107547. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  107548. return;
  107549. }
  107550. // Find the highlight color based on the configuration.
  107551. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  107552. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  107553. // Find the shadow color based on the configuration.
  107554. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  107555. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  107556. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  107557. };
  107558. /**
  107559. * Build the uniform buffer used in the material.
  107560. */
  107561. BackgroundMaterial.prototype.buildUniformLayout = function () {
  107562. // Order is important !
  107563. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  107564. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  107565. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  107566. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  107567. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  107568. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  107569. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  107570. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  107571. this._uniformBuffer.addUniform("pointSize", 1);
  107572. this._uniformBuffer.addUniform("shadowLevel", 1);
  107573. this._uniformBuffer.addUniform("alpha", 1);
  107574. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  107575. this._uniformBuffer.addUniform("vReflectionControl", 4);
  107576. this._uniformBuffer.create();
  107577. };
  107578. /**
  107579. * Unbind the material.
  107580. */
  107581. BackgroundMaterial.prototype.unbind = function () {
  107582. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107583. this._uniformBuffer.setTexture("diffuseSampler", null);
  107584. }
  107585. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107586. this._uniformBuffer.setTexture("reflectionSampler", null);
  107587. }
  107588. _super.prototype.unbind.call(this);
  107589. };
  107590. /**
  107591. * Bind only the world matrix to the material.
  107592. * @param world The world matrix to bind.
  107593. */
  107594. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  107595. this._activeEffect.setMatrix("world", world);
  107596. };
  107597. /**
  107598. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  107599. * @param world The world matrix to bind.
  107600. * @param subMesh The submesh to bind for.
  107601. */
  107602. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  107603. var scene = this.getScene();
  107604. var defines = subMesh._materialDefines;
  107605. if (!defines) {
  107606. return;
  107607. }
  107608. var effect = subMesh.effect;
  107609. if (!effect) {
  107610. return;
  107611. }
  107612. this._activeEffect = effect;
  107613. // Matrices
  107614. this.bindOnlyWorldMatrix(world);
  107615. // Bones
  107616. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  107617. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  107618. if (mustRebind) {
  107619. this._uniformBuffer.bindToEffect(effect, "Material");
  107620. this.bindViewProjection(effect);
  107621. var reflectionTexture = this._reflectionTexture;
  107622. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  107623. // Texture uniforms
  107624. if (scene.texturesEnabled) {
  107625. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107626. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  107627. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  107628. }
  107629. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107630. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  107631. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  107632. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  107633. }
  107634. }
  107635. if (this.shadowLevel > 0) {
  107636. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  107637. }
  107638. this._uniformBuffer.updateFloat("alpha", this.alpha);
  107639. // Point size
  107640. if (this.pointsCloud) {
  107641. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  107642. }
  107643. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  107644. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  107645. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  107646. }
  107647. else {
  107648. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  107649. }
  107650. }
  107651. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  107652. // Textures
  107653. if (scene.texturesEnabled) {
  107654. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107655. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  107656. }
  107657. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107658. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  107659. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  107660. }
  107661. else if (!defines.REFLECTIONBLUR) {
  107662. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  107663. }
  107664. else {
  107665. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  107666. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  107667. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  107668. }
  107669. if (defines.REFLECTIONFRESNEL) {
  107670. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  107671. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  107672. }
  107673. }
  107674. }
  107675. // Clip plane
  107676. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  107677. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  107678. }
  107679. if (mustRebind || !this.isFrozen) {
  107680. if (scene.lightsEnabled) {
  107681. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  107682. }
  107683. // View
  107684. this.bindView(effect);
  107685. // Fog
  107686. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  107687. // image processing
  107688. if (this._imageProcessingConfiguration) {
  107689. this._imageProcessingConfiguration.bind(this._activeEffect);
  107690. }
  107691. }
  107692. this._uniformBuffer.update();
  107693. this._afterBind(mesh, this._activeEffect);
  107694. };
  107695. /**
  107696. * Dispose the material.
  107697. * @param forceDisposeEffect Force disposal of the associated effect.
  107698. * @param forceDisposeTextures Force disposal of the associated textures.
  107699. */
  107700. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  107701. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  107702. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  107703. if (forceDisposeTextures) {
  107704. if (this.diffuseTexture) {
  107705. this.diffuseTexture.dispose();
  107706. }
  107707. if (this.reflectionTexture) {
  107708. this.reflectionTexture.dispose();
  107709. }
  107710. }
  107711. this._renderTargets.dispose();
  107712. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107713. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107714. }
  107715. _super.prototype.dispose.call(this, forceDisposeEffect);
  107716. };
  107717. /**
  107718. * Clones the material.
  107719. * @param name The cloned name.
  107720. * @returns The cloned material.
  107721. */
  107722. BackgroundMaterial.prototype.clone = function (name) {
  107723. var _this = this;
  107724. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  107725. };
  107726. /**
  107727. * Serializes the current material to its JSON representation.
  107728. * @returns The JSON representation.
  107729. */
  107730. BackgroundMaterial.prototype.serialize = function () {
  107731. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107732. serializationObject.customType = "BABYLON.BackgroundMaterial";
  107733. return serializationObject;
  107734. };
  107735. /**
  107736. * Gets the class name of the material
  107737. * @returns "BackgroundMaterial"
  107738. */
  107739. BackgroundMaterial.prototype.getClassName = function () {
  107740. return "BackgroundMaterial";
  107741. };
  107742. /**
  107743. * Parse a JSON input to create back a background material.
  107744. * @param source The JSON data to parse
  107745. * @param scene The scene to create the parsed material in
  107746. * @param rootUrl The root url of the assets the material depends upon
  107747. * @returns the instantiated BackgroundMaterial.
  107748. */
  107749. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  107750. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  107751. };
  107752. /**
  107753. * Standard reflectance value at parallel view angle.
  107754. */
  107755. BackgroundMaterial.StandardReflectance0 = 0.05;
  107756. /**
  107757. * Standard reflectance value at grazing angle.
  107758. */
  107759. BackgroundMaterial.StandardReflectance90 = 0.5;
  107760. __decorate([
  107761. BABYLON.serializeAsColor3()
  107762. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  107763. __decorate([
  107764. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  107765. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  107766. __decorate([
  107767. BABYLON.serializeAsColor3()
  107768. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  107769. __decorate([
  107770. BABYLON.serialize()
  107771. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  107772. __decorate([
  107773. BABYLON.serialize()
  107774. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  107775. __decorate([
  107776. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  107777. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  107778. __decorate([
  107779. BABYLON.serializeAsTexture()
  107780. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  107781. __decorate([
  107782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107783. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  107784. __decorate([
  107785. BABYLON.serialize()
  107786. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  107787. __decorate([
  107788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107789. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  107790. __decorate([
  107791. BABYLON.serializeAsTexture()
  107792. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  107793. __decorate([
  107794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107795. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  107796. __decorate([
  107797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107798. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  107799. __decorate([
  107800. BABYLON.serialize()
  107801. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  107802. __decorate([
  107803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107804. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  107805. __decorate([
  107806. BABYLON.serializeAsVector3()
  107807. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  107808. __decorate([
  107809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107810. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  107811. __decorate([
  107812. BABYLON.serialize()
  107813. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  107814. __decorate([
  107815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107816. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  107817. __decorate([
  107818. BABYLON.serialize()
  107819. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  107820. __decorate([
  107821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107822. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  107823. __decorate([
  107824. BABYLON.serialize()
  107825. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  107826. __decorate([
  107827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107828. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  107829. __decorate([
  107830. BABYLON.serialize()
  107831. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  107832. __decorate([
  107833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107834. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  107835. __decorate([
  107836. BABYLON.serialize()
  107837. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  107838. __decorate([
  107839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107840. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  107841. __decorate([
  107842. BABYLON.serialize()
  107843. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  107844. __decorate([
  107845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107846. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  107847. __decorate([
  107848. BABYLON.serialize()
  107849. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  107850. __decorate([
  107851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107852. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  107853. __decorate([
  107854. BABYLON.serialize()
  107855. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  107856. __decorate([
  107857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107858. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  107859. __decorate([
  107860. BABYLON.serialize()
  107861. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  107862. __decorate([
  107863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107864. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  107865. __decorate([
  107866. BABYLON.serializeAsImageProcessingConfiguration()
  107867. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  107868. return BackgroundMaterial;
  107869. }(BABYLON.PushMaterial));
  107870. BABYLON.BackgroundMaterial = BackgroundMaterial;
  107871. })(BABYLON || (BABYLON = {}));
  107872. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  107873. var __assign = (this && this.__assign) || function () {
  107874. __assign = Object.assign || function(t) {
  107875. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107876. s = arguments[i];
  107877. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107878. t[p] = s[p];
  107879. }
  107880. return t;
  107881. };
  107882. return __assign.apply(this, arguments);
  107883. };
  107884. var BABYLON;
  107885. (function (BABYLON) {
  107886. /**
  107887. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  107888. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  107889. * It also helps with the default setup of your imageProcessing configuration.
  107890. */
  107891. var EnvironmentHelper = /** @class */ (function () {
  107892. /**
  107893. * constructor
  107894. * @param options
  107895. * @param scene The scene to add the material to
  107896. */
  107897. function EnvironmentHelper(options, scene) {
  107898. var _this = this;
  107899. this._errorHandler = function (message, exception) {
  107900. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  107901. };
  107902. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  107903. this._scene = scene;
  107904. this.onErrorObservable = new BABYLON.Observable();
  107905. this._setupBackground();
  107906. this._setupImageProcessing();
  107907. }
  107908. /**
  107909. * Creates the default options for the helper.
  107910. */
  107911. EnvironmentHelper._getDefaultOptions = function () {
  107912. return {
  107913. createGround: true,
  107914. groundSize: 15,
  107915. groundTexture: this._groundTextureCDNUrl,
  107916. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107917. groundOpacity: 0.9,
  107918. enableGroundShadow: true,
  107919. groundShadowLevel: 0.5,
  107920. enableGroundMirror: false,
  107921. groundMirrorSizeRatio: 0.3,
  107922. groundMirrorBlurKernel: 64,
  107923. groundMirrorAmount: 1,
  107924. groundMirrorFresnelWeight: 1,
  107925. groundMirrorFallOffDistance: 0,
  107926. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  107927. groundYBias: 0.00001,
  107928. createSkybox: true,
  107929. skyboxSize: 20,
  107930. skyboxTexture: this._skyboxTextureCDNUrl,
  107931. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107932. backgroundYRotation: 0,
  107933. sizeAuto: true,
  107934. rootPosition: BABYLON.Vector3.Zero(),
  107935. setupImageProcessing: true,
  107936. environmentTexture: this._environmentTextureCDNUrl,
  107937. cameraExposure: 0.8,
  107938. cameraContrast: 1.2,
  107939. toneMappingEnabled: true,
  107940. };
  107941. };
  107942. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  107943. /**
  107944. * Gets the root mesh created by the helper.
  107945. */
  107946. get: function () {
  107947. return this._rootMesh;
  107948. },
  107949. enumerable: true,
  107950. configurable: true
  107951. });
  107952. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  107953. /**
  107954. * Gets the skybox created by the helper.
  107955. */
  107956. get: function () {
  107957. return this._skybox;
  107958. },
  107959. enumerable: true,
  107960. configurable: true
  107961. });
  107962. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  107963. /**
  107964. * Gets the skybox texture created by the helper.
  107965. */
  107966. get: function () {
  107967. return this._skyboxTexture;
  107968. },
  107969. enumerable: true,
  107970. configurable: true
  107971. });
  107972. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  107973. /**
  107974. * Gets the skybox material created by the helper.
  107975. */
  107976. get: function () {
  107977. return this._skyboxMaterial;
  107978. },
  107979. enumerable: true,
  107980. configurable: true
  107981. });
  107982. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  107983. /**
  107984. * Gets the ground mesh created by the helper.
  107985. */
  107986. get: function () {
  107987. return this._ground;
  107988. },
  107989. enumerable: true,
  107990. configurable: true
  107991. });
  107992. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  107993. /**
  107994. * Gets the ground texture created by the helper.
  107995. */
  107996. get: function () {
  107997. return this._groundTexture;
  107998. },
  107999. enumerable: true,
  108000. configurable: true
  108001. });
  108002. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  108003. /**
  108004. * Gets the ground mirror created by the helper.
  108005. */
  108006. get: function () {
  108007. return this._groundMirror;
  108008. },
  108009. enumerable: true,
  108010. configurable: true
  108011. });
  108012. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  108013. /**
  108014. * Gets the ground mirror render list to helps pushing the meshes
  108015. * you wish in the ground reflection.
  108016. */
  108017. get: function () {
  108018. if (this._groundMirror) {
  108019. return this._groundMirror.renderList;
  108020. }
  108021. return null;
  108022. },
  108023. enumerable: true,
  108024. configurable: true
  108025. });
  108026. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  108027. /**
  108028. * Gets the ground material created by the helper.
  108029. */
  108030. get: function () {
  108031. return this._groundMaterial;
  108032. },
  108033. enumerable: true,
  108034. configurable: true
  108035. });
  108036. /**
  108037. * Updates the background according to the new options
  108038. * @param options
  108039. */
  108040. EnvironmentHelper.prototype.updateOptions = function (options) {
  108041. var newOptions = __assign({}, this._options, options);
  108042. if (this._ground && !newOptions.createGround) {
  108043. this._ground.dispose();
  108044. this._ground = null;
  108045. }
  108046. if (this._groundMaterial && !newOptions.createGround) {
  108047. this._groundMaterial.dispose();
  108048. this._groundMaterial = null;
  108049. }
  108050. if (this._groundTexture) {
  108051. if (this._options.groundTexture != newOptions.groundTexture) {
  108052. this._groundTexture.dispose();
  108053. this._groundTexture = null;
  108054. }
  108055. }
  108056. if (this._skybox && !newOptions.createSkybox) {
  108057. this._skybox.dispose();
  108058. this._skybox = null;
  108059. }
  108060. if (this._skyboxMaterial && !newOptions.createSkybox) {
  108061. this._skyboxMaterial.dispose();
  108062. this._skyboxMaterial = null;
  108063. }
  108064. if (this._skyboxTexture) {
  108065. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  108066. this._skyboxTexture.dispose();
  108067. this._skyboxTexture = null;
  108068. }
  108069. }
  108070. if (this._groundMirror && !newOptions.enableGroundMirror) {
  108071. this._groundMirror.dispose();
  108072. this._groundMirror = null;
  108073. }
  108074. if (this._scene.environmentTexture) {
  108075. if (this._options.environmentTexture != newOptions.environmentTexture) {
  108076. this._scene.environmentTexture.dispose();
  108077. }
  108078. }
  108079. this._options = newOptions;
  108080. this._setupBackground();
  108081. this._setupImageProcessing();
  108082. };
  108083. /**
  108084. * Sets the primary color of all the available elements.
  108085. * @param color the main color to affect to the ground and the background
  108086. */
  108087. EnvironmentHelper.prototype.setMainColor = function (color) {
  108088. if (this.groundMaterial) {
  108089. this.groundMaterial.primaryColor = color;
  108090. }
  108091. if (this.skyboxMaterial) {
  108092. this.skyboxMaterial.primaryColor = color;
  108093. }
  108094. if (this.groundMirror) {
  108095. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  108096. }
  108097. };
  108098. /**
  108099. * Setup the image processing according to the specified options.
  108100. */
  108101. EnvironmentHelper.prototype._setupImageProcessing = function () {
  108102. if (this._options.setupImageProcessing) {
  108103. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  108104. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  108105. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  108106. this._setupEnvironmentTexture();
  108107. }
  108108. };
  108109. /**
  108110. * Setup the environment texture according to the specified options.
  108111. */
  108112. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  108113. if (this._scene.environmentTexture) {
  108114. return;
  108115. }
  108116. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  108117. this._scene.environmentTexture = this._options.environmentTexture;
  108118. return;
  108119. }
  108120. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  108121. this._scene.environmentTexture = environmentTexture;
  108122. };
  108123. /**
  108124. * Setup the background according to the specified options.
  108125. */
  108126. EnvironmentHelper.prototype._setupBackground = function () {
  108127. if (!this._rootMesh) {
  108128. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  108129. }
  108130. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  108131. var sceneSize = this._getSceneSize();
  108132. if (this._options.createGround) {
  108133. this._setupGround(sceneSize);
  108134. this._setupGroundMaterial();
  108135. this._setupGroundDiffuseTexture();
  108136. if (this._options.enableGroundMirror) {
  108137. this._setupGroundMirrorTexture(sceneSize);
  108138. }
  108139. this._setupMirrorInGroundMaterial();
  108140. }
  108141. if (this._options.createSkybox) {
  108142. this._setupSkybox(sceneSize);
  108143. this._setupSkyboxMaterial();
  108144. this._setupSkyboxReflectionTexture();
  108145. }
  108146. this._rootMesh.position.x = sceneSize.rootPosition.x;
  108147. this._rootMesh.position.z = sceneSize.rootPosition.z;
  108148. this._rootMesh.position.y = sceneSize.rootPosition.y;
  108149. };
  108150. /**
  108151. * Get the scene sizes according to the setup.
  108152. */
  108153. EnvironmentHelper.prototype._getSceneSize = function () {
  108154. var _this = this;
  108155. var groundSize = this._options.groundSize;
  108156. var skyboxSize = this._options.skyboxSize;
  108157. var rootPosition = this._options.rootPosition;
  108158. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  108159. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108160. }
  108161. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  108162. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  108163. });
  108164. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108165. if (this._options.sizeAuto) {
  108166. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  108167. this._scene.activeCamera.upperRadiusLimit) {
  108168. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  108169. skyboxSize = groundSize;
  108170. }
  108171. var sceneDiagonalLenght = sceneDiagonal.length();
  108172. if (sceneDiagonalLenght > groundSize) {
  108173. groundSize = sceneDiagonalLenght * 2;
  108174. skyboxSize = groundSize;
  108175. }
  108176. // 10 % bigger.
  108177. groundSize *= 1.1;
  108178. skyboxSize *= 1.5;
  108179. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  108180. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  108181. }
  108182. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108183. };
  108184. /**
  108185. * Setup the ground according to the specified options.
  108186. */
  108187. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  108188. var _this = this;
  108189. if (!this._ground || this._ground.isDisposed()) {
  108190. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  108191. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  108192. this._ground.parent = this._rootMesh;
  108193. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  108194. }
  108195. this._ground.receiveShadows = this._options.enableGroundShadow;
  108196. };
  108197. /**
  108198. * Setup the ground material according to the specified options.
  108199. */
  108200. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  108201. if (!this._groundMaterial) {
  108202. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  108203. }
  108204. this._groundMaterial.alpha = this._options.groundOpacity;
  108205. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108206. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  108207. this._groundMaterial.primaryColor = this._options.groundColor;
  108208. this._groundMaterial.useRGBColor = false;
  108209. this._groundMaterial.enableNoise = true;
  108210. if (this._ground) {
  108211. this._ground.material = this._groundMaterial;
  108212. }
  108213. };
  108214. /**
  108215. * Setup the ground diffuse texture according to the specified options.
  108216. */
  108217. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  108218. if (!this._groundMaterial) {
  108219. return;
  108220. }
  108221. if (this._groundTexture) {
  108222. return;
  108223. }
  108224. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  108225. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  108226. return;
  108227. }
  108228. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108229. diffuseTexture.gammaSpace = false;
  108230. diffuseTexture.hasAlpha = true;
  108231. this._groundMaterial.diffuseTexture = diffuseTexture;
  108232. };
  108233. /**
  108234. * Setup the ground mirror texture according to the specified options.
  108235. */
  108236. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  108237. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108238. if (!this._groundMirror) {
  108239. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  108240. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  108241. this._groundMirror.anisotropicFilteringLevel = 1;
  108242. this._groundMirror.wrapU = wrapping;
  108243. this._groundMirror.wrapV = wrapping;
  108244. this._groundMirror.gammaSpace = false;
  108245. if (this._groundMirror.renderList) {
  108246. for (var i = 0; i < this._scene.meshes.length; i++) {
  108247. var mesh = this._scene.meshes[i];
  108248. if (mesh !== this._ground &&
  108249. mesh !== this._skybox &&
  108250. mesh !== this._rootMesh) {
  108251. this._groundMirror.renderList.push(mesh);
  108252. }
  108253. }
  108254. }
  108255. }
  108256. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  108257. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  108258. };
  108259. /**
  108260. * Setup the ground to receive the mirror texture.
  108261. */
  108262. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  108263. if (this._groundMaterial) {
  108264. this._groundMaterial.reflectionTexture = this._groundMirror;
  108265. this._groundMaterial.reflectionFresnel = true;
  108266. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  108267. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  108268. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  108269. }
  108270. };
  108271. /**
  108272. * Setup the skybox according to the specified options.
  108273. */
  108274. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  108275. var _this = this;
  108276. if (!this._skybox || this._skybox.isDisposed()) {
  108277. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  108278. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  108279. }
  108280. this._skybox.parent = this._rootMesh;
  108281. };
  108282. /**
  108283. * Setup the skybox material according to the specified options.
  108284. */
  108285. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  108286. if (!this._skybox) {
  108287. return;
  108288. }
  108289. if (!this._skyboxMaterial) {
  108290. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  108291. }
  108292. this._skyboxMaterial.useRGBColor = false;
  108293. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  108294. this._skyboxMaterial.enableNoise = true;
  108295. this._skybox.material = this._skyboxMaterial;
  108296. };
  108297. /**
  108298. * Setup the skybox reflection texture according to the specified options.
  108299. */
  108300. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  108301. if (!this._skyboxMaterial) {
  108302. return;
  108303. }
  108304. if (this._skyboxTexture) {
  108305. return;
  108306. }
  108307. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  108308. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  108309. return;
  108310. }
  108311. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108312. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  108313. this._skyboxTexture.gammaSpace = false;
  108314. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  108315. };
  108316. /**
  108317. * Dispose all the elements created by the Helper.
  108318. */
  108319. EnvironmentHelper.prototype.dispose = function () {
  108320. if (this._groundMaterial) {
  108321. this._groundMaterial.dispose(true, true);
  108322. }
  108323. if (this._skyboxMaterial) {
  108324. this._skyboxMaterial.dispose(true, true);
  108325. }
  108326. this._rootMesh.dispose(false);
  108327. };
  108328. /**
  108329. * Default ground texture URL.
  108330. */
  108331. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  108332. /**
  108333. * Default skybox texture URL.
  108334. */
  108335. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  108336. /**
  108337. * Default environment texture URL.
  108338. */
  108339. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  108340. return EnvironmentHelper;
  108341. }());
  108342. BABYLON.EnvironmentHelper = EnvironmentHelper;
  108343. })(BABYLON || (BABYLON = {}));
  108344. //# sourceMappingURL=babylon.environmentHelper.js.map
  108345. var BABYLON;
  108346. (function (BABYLON) {
  108347. /** Internal class used to store shapes for emitters */
  108348. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  108349. function ParticleSystemSetEmitterCreationOptions() {
  108350. }
  108351. return ParticleSystemSetEmitterCreationOptions;
  108352. }());
  108353. /**
  108354. * Represents a set of particle systems working together to create a specific effect
  108355. */
  108356. var ParticleSystemSet = /** @class */ (function () {
  108357. function ParticleSystemSet() {
  108358. /**
  108359. * Gets the particle system list
  108360. */
  108361. this.systems = new Array();
  108362. }
  108363. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  108364. /**
  108365. * Gets the emitter node used with this set
  108366. */
  108367. get: function () {
  108368. return this._emitterNode;
  108369. },
  108370. enumerable: true,
  108371. configurable: true
  108372. });
  108373. /**
  108374. * Creates a new emitter mesh as a sphere
  108375. * @param options defines the options used to create the sphere
  108376. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  108377. * @param scene defines the hosting scene
  108378. */
  108379. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  108380. if (this._emitterNode) {
  108381. this._emitterNode.dispose();
  108382. }
  108383. this._emitterCreationOptions = {
  108384. kind: "Sphere",
  108385. options: options,
  108386. renderingGroupId: renderingGroupId
  108387. };
  108388. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  108389. emitterMesh.renderingGroupId = renderingGroupId;
  108390. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  108391. material.emissiveColor = options.color;
  108392. emitterMesh.material = material;
  108393. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108394. var system = _a[_i];
  108395. system.emitter = emitterMesh;
  108396. }
  108397. this._emitterNode = emitterMesh;
  108398. };
  108399. /**
  108400. * Starts all particle systems of the set
  108401. * @param emitter defines an optional mesh to use as emitter for the particle systems
  108402. */
  108403. ParticleSystemSet.prototype.start = function (emitter) {
  108404. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108405. var system = _a[_i];
  108406. if (emitter) {
  108407. system.emitter = emitter;
  108408. }
  108409. system.start();
  108410. }
  108411. };
  108412. /**
  108413. * Release all associated resources
  108414. */
  108415. ParticleSystemSet.prototype.dispose = function () {
  108416. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108417. var system = _a[_i];
  108418. system.dispose();
  108419. }
  108420. this.systems = [];
  108421. if (this._emitterNode) {
  108422. this._emitterNode.dispose();
  108423. this._emitterNode = null;
  108424. }
  108425. };
  108426. /**
  108427. * Serialize the set into a JSON compatible object
  108428. * @returns a JSON compatible representation of the set
  108429. */
  108430. ParticleSystemSet.prototype.serialize = function () {
  108431. var result = {};
  108432. result.systems = [];
  108433. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108434. var system = _a[_i];
  108435. result.systems.push(system.serialize());
  108436. }
  108437. if (this._emitterNode) {
  108438. result.emitter = this._emitterCreationOptions;
  108439. }
  108440. return result;
  108441. };
  108442. /**
  108443. * Parse a new ParticleSystemSet from a serialized source
  108444. * @param data defines a JSON compatible representation of the set
  108445. * @param scene defines the hosting scene
  108446. * @param gpu defines if we want GPU particles or CPU particles
  108447. * @returns a new ParticleSystemSet
  108448. */
  108449. ParticleSystemSet.Parse = function (data, scene, gpu) {
  108450. if (gpu === void 0) { gpu = false; }
  108451. var result = new ParticleSystemSet();
  108452. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  108453. scene = scene || BABYLON.Engine.LastCreatedScene;
  108454. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  108455. var system = _a[_i];
  108456. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  108457. }
  108458. if (data.emitter) {
  108459. var options = data.emitter.options;
  108460. switch (data.emitter.kind) {
  108461. case "Sphere":
  108462. result.setEmitterAsSphere({
  108463. diameter: options.diameter,
  108464. segments: options.segments,
  108465. color: BABYLON.Color3.FromArray(options.color)
  108466. }, data.emitter.renderingGroupId, scene);
  108467. break;
  108468. }
  108469. }
  108470. return result;
  108471. };
  108472. return ParticleSystemSet;
  108473. }());
  108474. BABYLON.ParticleSystemSet = ParticleSystemSet;
  108475. })(BABYLON || (BABYLON = {}));
  108476. //# sourceMappingURL=babylon.particleSystemSet.js.map
  108477. var BABYLON;
  108478. (function (BABYLON) {
  108479. /**
  108480. * This class is made for on one-liner static method to help creating particle system set.
  108481. */
  108482. var ParticleHelper = /** @class */ (function () {
  108483. function ParticleHelper() {
  108484. }
  108485. /**
  108486. * Create a default particle system that you can tweak
  108487. * @param emitter defines the emitter to use
  108488. * @param capacity defines the system capacity (default is 500 particles)
  108489. * @param scene defines the hosting scene
  108490. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  108491. * @returns the new Particle system
  108492. */
  108493. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  108494. if (capacity === void 0) { capacity = 500; }
  108495. if (useGPU === void 0) { useGPU = false; }
  108496. var system;
  108497. if (useGPU) {
  108498. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  108499. }
  108500. else {
  108501. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  108502. }
  108503. system.emitter = emitter;
  108504. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  108505. system.createConeEmitter(0.1, Math.PI / 4);
  108506. // Particle color
  108507. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108508. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108509. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  108510. // Particle Size
  108511. system.minSize = 0.1;
  108512. system.maxSize = 0.1;
  108513. // Emission speed
  108514. system.minEmitPower = 2;
  108515. system.maxEmitPower = 2;
  108516. // Update speed
  108517. system.updateSpeed = 1 / 60;
  108518. system.emitRate = 30;
  108519. return system;
  108520. };
  108521. /**
  108522. * This is the main static method (one-liner) of this helper to create different particle systems
  108523. * @param type This string represents the type to the particle system to create
  108524. * @param scene The scene where the particle system should live
  108525. * @param gpu If the system will use gpu
  108526. * @returns the ParticleSystemSet created
  108527. */
  108528. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  108529. if (gpu === void 0) { gpu = false; }
  108530. if (!scene) {
  108531. scene = BABYLON.Engine.LastCreatedScene;
  108532. ;
  108533. }
  108534. var token = {};
  108535. scene._addPendingData(token);
  108536. return new Promise(function (resolve, reject) {
  108537. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  108538. scene._removePendingData(token);
  108539. return reject("Particle system with GPU is not supported.");
  108540. }
  108541. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  108542. scene._removePendingData(token);
  108543. var newData = JSON.parse(data.toString());
  108544. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  108545. }, undefined, undefined, undefined, function (req, exception) {
  108546. scene._removePendingData(token);
  108547. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  108548. });
  108549. });
  108550. };
  108551. /**
  108552. * Static function used to export a particle system to a ParticleSystemSet variable.
  108553. * Please note that the emitter shape is not exported
  108554. * @param system defines the particle systems to export
  108555. */
  108556. ParticleHelper.ExportSet = function (systems) {
  108557. var set = new BABYLON.ParticleSystemSet();
  108558. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  108559. var system = systems_1[_i];
  108560. set.systems.push(system);
  108561. }
  108562. return set;
  108563. };
  108564. /**
  108565. * Gets or sets base Assets URL
  108566. */
  108567. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  108568. return ParticleHelper;
  108569. }());
  108570. BABYLON.ParticleHelper = ParticleHelper;
  108571. })(BABYLON || (BABYLON = {}));
  108572. //# sourceMappingURL=babylon.particleHelper.js.map
  108573. var BABYLON;
  108574. (function (BABYLON) {
  108575. /**
  108576. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  108577. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  108578. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  108579. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  108580. */
  108581. var VideoDome = /** @class */ (function (_super) {
  108582. __extends(VideoDome, _super);
  108583. /**
  108584. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  108585. * @param name Element's name, child elements will append suffixes for their own names.
  108586. * @param urlsOrVideo defines the url(s) or the video element to use
  108587. * @param options An object containing optional or exposed sub element properties
  108588. */
  108589. function VideoDome(name, urlsOrVideo, options, scene) {
  108590. var _this = _super.call(this, name, scene) || this;
  108591. _this._useDirectMapping = false;
  108592. // set defaults and manage values
  108593. name = name || "videoDome";
  108594. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  108595. options.clickToPlay = Boolean(options.clickToPlay);
  108596. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  108597. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  108598. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  108599. if (options.useDirectMapping === undefined) {
  108600. _this._useDirectMapping = true;
  108601. }
  108602. else {
  108603. _this._useDirectMapping = options.useDirectMapping;
  108604. }
  108605. _this._setReady(false);
  108606. // create
  108607. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  108608. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  108609. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  108610. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  108611. texture.onLoadObservable.addOnce(function () {
  108612. _this._setReady(true);
  108613. });
  108614. // configure material
  108615. material.useEquirectangularFOV = true;
  108616. material.fovMultiplier = 1.0;
  108617. material.opacityFresnel = false;
  108618. if (_this._useDirectMapping) {
  108619. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108620. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108621. material.diffuseTexture = texture;
  108622. }
  108623. else {
  108624. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  108625. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108626. material.reflectionTexture = texture;
  108627. }
  108628. // configure mesh
  108629. _this._mesh.material = material;
  108630. _this._mesh.parent = _this;
  108631. // optional configuration
  108632. if (options.clickToPlay) {
  108633. scene.onPointerUp = function () {
  108634. _this._videoTexture.video.play();
  108635. };
  108636. }
  108637. return _this;
  108638. }
  108639. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  108640. /**
  108641. * Gets the video texture being displayed on the sphere
  108642. */
  108643. get: function () {
  108644. return this._videoTexture;
  108645. },
  108646. enumerable: true,
  108647. configurable: true
  108648. });
  108649. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  108650. /**
  108651. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  108652. * Also see the options.resolution property.
  108653. */
  108654. get: function () {
  108655. return this._material.fovMultiplier;
  108656. },
  108657. set: function (value) {
  108658. this._material.fovMultiplier = value;
  108659. },
  108660. enumerable: true,
  108661. configurable: true
  108662. });
  108663. /**
  108664. * Releases resources associated with this node.
  108665. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  108666. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  108667. */
  108668. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  108669. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  108670. this._videoTexture.dispose();
  108671. this._mesh.dispose();
  108672. this._material.dispose();
  108673. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  108674. };
  108675. return VideoDome;
  108676. }(BABYLON.TransformNode));
  108677. BABYLON.VideoDome = VideoDome;
  108678. })(BABYLON || (BABYLON = {}));
  108679. //# sourceMappingURL=babylon.videoDome.js.map
  108680. var BABYLON;
  108681. (function (BABYLON) {
  108682. /**
  108683. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  108684. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  108685. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  108686. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  108687. */
  108688. var PhotoDome = /** @class */ (function (_super) {
  108689. __extends(PhotoDome, _super);
  108690. /**
  108691. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  108692. * @param name Element's name, child elements will append suffixes for their own names.
  108693. * @param urlsOfPhoto defines the url of the photo to display
  108694. * @param options defines an object containing optional or exposed sub element properties
  108695. * @param onError defines a callback called when an error occured while loading the texture
  108696. */
  108697. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  108698. if (onError === void 0) { onError = null; }
  108699. var _this = _super.call(this, name, scene) || this;
  108700. _this._useDirectMapping = false;
  108701. /**
  108702. * Observable raised when an error occured while loading the 360 image
  108703. */
  108704. _this.onLoadErrorObservable = new BABYLON.Observable();
  108705. // set defaults and manage values
  108706. name = name || "photoDome";
  108707. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  108708. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  108709. if (options.useDirectMapping === undefined) {
  108710. _this._useDirectMapping = true;
  108711. }
  108712. else {
  108713. _this._useDirectMapping = options.useDirectMapping;
  108714. }
  108715. _this._setReady(false);
  108716. // create
  108717. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  108718. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  108719. // configure material
  108720. material.opacityFresnel = false;
  108721. material.useEquirectangularFOV = true;
  108722. material.fovMultiplier = 1.0;
  108723. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  108724. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  108725. if (onError) {
  108726. onError(message, exception);
  108727. }
  108728. });
  108729. _this.photoTexture.onLoadObservable.addOnce(function () {
  108730. _this._setReady(true);
  108731. });
  108732. // configure mesh
  108733. _this._mesh.material = material;
  108734. _this._mesh.parent = _this;
  108735. return _this;
  108736. }
  108737. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  108738. /**
  108739. * Gets or sets the texture being displayed on the sphere
  108740. */
  108741. get: function () {
  108742. return this._photoTexture;
  108743. },
  108744. set: function (value) {
  108745. if (this._photoTexture === value) {
  108746. return;
  108747. }
  108748. this._photoTexture = value;
  108749. if (this._useDirectMapping) {
  108750. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108751. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108752. this._material.diffuseTexture = this._photoTexture;
  108753. }
  108754. else {
  108755. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  108756. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108757. this._material.reflectionTexture = this._photoTexture;
  108758. }
  108759. },
  108760. enumerable: true,
  108761. configurable: true
  108762. });
  108763. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  108764. /**
  108765. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  108766. * Also see the options.resolution property.
  108767. */
  108768. get: function () {
  108769. return this._material.fovMultiplier;
  108770. },
  108771. set: function (value) {
  108772. this._material.fovMultiplier = value;
  108773. },
  108774. enumerable: true,
  108775. configurable: true
  108776. });
  108777. /**
  108778. * Releases resources associated with this node.
  108779. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  108780. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  108781. */
  108782. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  108783. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  108784. this._photoTexture.dispose();
  108785. this._mesh.dispose();
  108786. this._material.dispose();
  108787. this.onLoadErrorObservable.clear();
  108788. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  108789. };
  108790. return PhotoDome;
  108791. }(BABYLON.TransformNode));
  108792. BABYLON.PhotoDome = PhotoDome;
  108793. })(BABYLON || (BABYLON = {}));
  108794. //# sourceMappingURL=babylon.photoDome.js.map
  108795. var BABYLON;
  108796. (function (BABYLON) {
  108797. BABYLON.Engine.prototype.createQuery = function () {
  108798. return this._gl.createQuery();
  108799. };
  108800. BABYLON.Engine.prototype.deleteQuery = function (query) {
  108801. this._gl.deleteQuery(query);
  108802. return this;
  108803. };
  108804. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  108805. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  108806. };
  108807. BABYLON.Engine.prototype.getQueryResult = function (query) {
  108808. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  108809. };
  108810. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  108811. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108812. this._gl.beginQuery(glAlgorithm, query);
  108813. return this;
  108814. };
  108815. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  108816. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108817. this._gl.endQuery(glAlgorithm);
  108818. return this;
  108819. };
  108820. BABYLON.Engine.prototype._createTimeQuery = function () {
  108821. var timerQuery = this.getCaps().timerQuery;
  108822. if (timerQuery.createQueryEXT) {
  108823. return timerQuery.createQueryEXT();
  108824. }
  108825. return this.createQuery();
  108826. };
  108827. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  108828. var timerQuery = this.getCaps().timerQuery;
  108829. if (timerQuery.deleteQueryEXT) {
  108830. timerQuery.deleteQueryEXT(query);
  108831. return;
  108832. }
  108833. this.deleteQuery(query);
  108834. };
  108835. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  108836. var timerQuery = this.getCaps().timerQuery;
  108837. if (timerQuery.getQueryObjectEXT) {
  108838. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  108839. }
  108840. return this.getQueryResult(query);
  108841. };
  108842. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  108843. var timerQuery = this.getCaps().timerQuery;
  108844. if (timerQuery.getQueryObjectEXT) {
  108845. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  108846. }
  108847. return this.isQueryResultAvailable(query);
  108848. };
  108849. BABYLON.Engine.prototype.startTimeQuery = function () {
  108850. var caps = this.getCaps();
  108851. var timerQuery = caps.timerQuery;
  108852. if (!timerQuery) {
  108853. return null;
  108854. }
  108855. var token = new BABYLON._TimeToken();
  108856. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108857. if (caps.canUseTimestampForTimerQuery) {
  108858. token._startTimeQuery = this._createTimeQuery();
  108859. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  108860. }
  108861. else {
  108862. if (this._currentNonTimestampToken) {
  108863. return this._currentNonTimestampToken;
  108864. }
  108865. token._timeElapsedQuery = this._createTimeQuery();
  108866. if (timerQuery.beginQueryEXT) {
  108867. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108868. }
  108869. else {
  108870. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108871. }
  108872. this._currentNonTimestampToken = token;
  108873. }
  108874. return token;
  108875. };
  108876. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  108877. var caps = this.getCaps();
  108878. var timerQuery = caps.timerQuery;
  108879. if (!timerQuery || !token) {
  108880. return -1;
  108881. }
  108882. if (caps.canUseTimestampForTimerQuery) {
  108883. if (!token._startTimeQuery) {
  108884. return -1;
  108885. }
  108886. if (!token._endTimeQuery) {
  108887. token._endTimeQuery = this._createTimeQuery();
  108888. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  108889. }
  108890. }
  108891. else if (!token._timeElapsedQueryEnded) {
  108892. if (!token._timeElapsedQuery) {
  108893. return -1;
  108894. }
  108895. if (timerQuery.endQueryEXT) {
  108896. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  108897. }
  108898. else {
  108899. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  108900. }
  108901. token._timeElapsedQueryEnded = true;
  108902. }
  108903. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108904. var available = false;
  108905. if (token._endTimeQuery) {
  108906. available = this._getTimeQueryAvailability(token._endTimeQuery);
  108907. }
  108908. else if (token._timeElapsedQuery) {
  108909. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  108910. }
  108911. if (available && !disjoint) {
  108912. var result = 0;
  108913. if (caps.canUseTimestampForTimerQuery) {
  108914. if (!token._startTimeQuery || !token._endTimeQuery) {
  108915. return -1;
  108916. }
  108917. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  108918. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  108919. result = timeEnd - timeStart;
  108920. this._deleteTimeQuery(token._startTimeQuery);
  108921. this._deleteTimeQuery(token._endTimeQuery);
  108922. token._startTimeQuery = null;
  108923. token._endTimeQuery = null;
  108924. }
  108925. else {
  108926. if (!token._timeElapsedQuery) {
  108927. return -1;
  108928. }
  108929. result = this._getTimeQueryResult(token._timeElapsedQuery);
  108930. this._deleteTimeQuery(token._timeElapsedQuery);
  108931. token._timeElapsedQuery = null;
  108932. token._timeElapsedQueryEnded = false;
  108933. this._currentNonTimestampToken = null;
  108934. }
  108935. return result;
  108936. }
  108937. return -1;
  108938. };
  108939. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  108940. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  108941. };
  108942. // We also need to update AbstractMesh as there is a portion of the code there
  108943. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  108944. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  108945. this._isOccluded = false;
  108946. return;
  108947. }
  108948. var engine = this.getEngine();
  108949. if (engine.webGLVersion < 2) {
  108950. this._isOccluded = false;
  108951. return;
  108952. }
  108953. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  108954. this._isOccluded = false;
  108955. return;
  108956. }
  108957. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  108958. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  108959. if (isOcclusionQueryAvailable) {
  108960. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  108961. this._isOcclusionQueryInProgress = false;
  108962. this._occlusionInternalRetryCounter = 0;
  108963. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  108964. }
  108965. else {
  108966. this._occlusionInternalRetryCounter++;
  108967. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  108968. this._isOcclusionQueryInProgress = false;
  108969. this._occlusionInternalRetryCounter = 0;
  108970. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  108971. // if strict continue the last state of the object.
  108972. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  108973. }
  108974. else {
  108975. return;
  108976. }
  108977. }
  108978. }
  108979. var scene = this.getScene();
  108980. if (scene.getBoundingBoxRenderer) {
  108981. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  108982. if (!this._occlusionQuery) {
  108983. this._occlusionQuery = engine.createQuery();
  108984. }
  108985. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  108986. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  108987. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  108988. this._isOcclusionQueryInProgress = true;
  108989. }
  108990. };
  108991. })(BABYLON || (BABYLON = {}));
  108992. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  108993. var BABYLON;
  108994. (function (BABYLON) {
  108995. /**
  108996. * Class used to generate noise procedural textures
  108997. */
  108998. var NoiseProceduralTexture = /** @class */ (function (_super) {
  108999. __extends(NoiseProceduralTexture, _super);
  109000. /**
  109001. * Creates a new NoiseProceduralTexture
  109002. * @param name defines the name fo the texture
  109003. * @param size defines the size of the texture (default is 256)
  109004. * @param scene defines the hosting scene
  109005. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  109006. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  109007. */
  109008. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  109009. if (size === void 0) { size = 256; }
  109010. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  109011. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  109012. _this._time = 0;
  109013. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  109014. _this.brightness = 0.2;
  109015. /** Defines the number of octaves to process */
  109016. _this.octaves = 3;
  109017. /** Defines the level of persistence (0.8 by default) */
  109018. _this.persistence = 0.8;
  109019. /** Gets or sets animation speed factor (default is 1) */
  109020. _this.animationSpeedFactor = 1;
  109021. _this._updateShaderUniforms();
  109022. return _this;
  109023. }
  109024. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  109025. var scene = this.getScene();
  109026. if (!scene) {
  109027. return;
  109028. }
  109029. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  109030. this.setFloat("brightness", this.brightness);
  109031. this.setFloat("persistence", this.persistence);
  109032. this.setFloat("timeScale", this._time);
  109033. };
  109034. NoiseProceduralTexture.prototype._getDefines = function () {
  109035. return "#define OCTAVES " + (this.octaves | 0);
  109036. };
  109037. /** Generate the current state of the procedural texture */
  109038. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  109039. this._updateShaderUniforms();
  109040. _super.prototype.render.call(this, useCameraPostProcess);
  109041. };
  109042. /**
  109043. * Serializes this noise procedural texture
  109044. * @returns a serialized noise procedural texture object
  109045. */
  109046. NoiseProceduralTexture.prototype.serialize = function () {
  109047. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  109048. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  109049. return serializationObject;
  109050. };
  109051. /**
  109052. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  109053. * @param parsedTexture defines parsed texture data
  109054. * @param scene defines the current scene
  109055. * @param rootUrl defines the root URL containing noise procedural texture information
  109056. * @returns a parsed NoiseProceduralTexture
  109057. */
  109058. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  109059. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  109060. return texture;
  109061. };
  109062. return NoiseProceduralTexture;
  109063. }(BABYLON.ProceduralTexture));
  109064. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  109065. })(BABYLON || (BABYLON = {}));
  109066. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  109067. var __assign = (this && this.__assign) || function () {
  109068. __assign = Object.assign || function(t) {
  109069. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109070. s = arguments[i];
  109071. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109072. t[p] = s[p];
  109073. }
  109074. return t;
  109075. };
  109076. return __assign.apply(this, arguments);
  109077. };
  109078. var BABYLON;
  109079. (function (BABYLON) {
  109080. /**
  109081. * This can helps recording videos from BabylonJS.
  109082. * This is based on the available WebRTC functionalities of the browser.
  109083. *
  109084. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  109085. */
  109086. var VideoRecorder = /** @class */ (function () {
  109087. /**
  109088. * Create a new VideoCapture object which can help converting what you see in Babylon to
  109089. * a video file.
  109090. * @param engine Defines the BabylonJS Engine you wish to record
  109091. * @param options Defines options that can be used to customized the capture
  109092. */
  109093. function VideoRecorder(engine, options) {
  109094. if (options === void 0) { options = null; }
  109095. if (!VideoRecorder.IsSupported(engine)) {
  109096. throw "Your browser does not support recording so far.";
  109097. }
  109098. var canvas = engine.getRenderingCanvas();
  109099. if (!canvas) {
  109100. throw "The babylon engine must have a canvas to be recorded";
  109101. }
  109102. this._canvas = canvas;
  109103. this._canvas.isRecording = false;
  109104. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  109105. var stream = this._canvas.captureStream(this._options.fps);
  109106. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  109107. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  109108. this._mediaRecorder.onerror = this._handleError.bind(this);
  109109. this._mediaRecorder.onstop = this._handleStop.bind(this);
  109110. }
  109111. /**
  109112. * Returns wehther or not the VideoRecorder is available in your browser.
  109113. * @param engine Defines the Babylon Engine to check the support for
  109114. * @returns true if supported otherwise false
  109115. */
  109116. VideoRecorder.IsSupported = function (engine) {
  109117. var canvas = engine.getRenderingCanvas();
  109118. return (!!canvas && typeof canvas.captureStream === "function");
  109119. };
  109120. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  109121. /**
  109122. * True wether a recording is already in progress.
  109123. */
  109124. get: function () {
  109125. return !!this._canvas && this._canvas.isRecording;
  109126. },
  109127. enumerable: true,
  109128. configurable: true
  109129. });
  109130. /**
  109131. * Stops the current recording before the default capture timeout passed in the startRecording
  109132. * functions.
  109133. */
  109134. VideoRecorder.prototype.stopRecording = function () {
  109135. if (!this._canvas || !this._mediaRecorder) {
  109136. return;
  109137. }
  109138. if (!this.isRecording) {
  109139. return;
  109140. }
  109141. this._canvas.isRecording = false;
  109142. this._mediaRecorder.stop();
  109143. };
  109144. /**
  109145. * Starts recording the canvas for a max duration specified in parameters.
  109146. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  109147. * @param maxDuration Defines the maximum recording time in seconds.
  109148. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  109149. * @return a promise callback at the end of the recording with the video data in Blob.
  109150. */
  109151. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  109152. var _this = this;
  109153. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  109154. if (maxDuration === void 0) { maxDuration = 7; }
  109155. if (!this._canvas || !this._mediaRecorder) {
  109156. throw "Recorder has already been disposed";
  109157. }
  109158. if (this.isRecording) {
  109159. throw "Recording already in progress";
  109160. }
  109161. if (maxDuration > 0) {
  109162. setTimeout(function () {
  109163. _this.stopRecording();
  109164. }, maxDuration * 1000);
  109165. }
  109166. this._fileName = fileName;
  109167. this._recordedChunks = [];
  109168. this._resolve = null;
  109169. this._reject = null;
  109170. this._canvas.isRecording = true;
  109171. this._mediaRecorder.start(this._options.recordChunckSize);
  109172. return new Promise(function (resolve, reject) {
  109173. _this._resolve = resolve;
  109174. _this._reject = reject;
  109175. });
  109176. };
  109177. /**
  109178. * Releases internal resources used during the recording.
  109179. */
  109180. VideoRecorder.prototype.dispose = function () {
  109181. this._canvas = null;
  109182. this._mediaRecorder = null;
  109183. this._recordedChunks = [];
  109184. this._fileName = null;
  109185. this._resolve = null;
  109186. this._reject = null;
  109187. };
  109188. VideoRecorder.prototype._handleDataAvailable = function (event) {
  109189. if (event.data.size > 0) {
  109190. this._recordedChunks.push(event.data);
  109191. }
  109192. };
  109193. VideoRecorder.prototype._handleError = function (event) {
  109194. this.stopRecording();
  109195. if (this._reject) {
  109196. this._reject(event.error);
  109197. }
  109198. else {
  109199. throw new event.error;
  109200. }
  109201. };
  109202. VideoRecorder.prototype._handleStop = function () {
  109203. this.stopRecording();
  109204. var superBuffer = new Blob(this._recordedChunks);
  109205. if (this._resolve) {
  109206. this._resolve(superBuffer);
  109207. }
  109208. window.URL.createObjectURL(superBuffer);
  109209. if (this._fileName) {
  109210. BABYLON.Tools.Download(superBuffer, this._fileName);
  109211. }
  109212. };
  109213. VideoRecorder._defaultOptions = {
  109214. mimeType: "video/webm",
  109215. fps: 25,
  109216. recordChunckSize: 3000
  109217. };
  109218. return VideoRecorder;
  109219. }());
  109220. BABYLON.VideoRecorder = VideoRecorder;
  109221. })(BABYLON || (BABYLON = {}));
  109222. //# sourceMappingURL=babylon.videoRecorder.js.map
  109223. var BABYLON;
  109224. (function (BABYLON) {
  109225. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  109226. if (replace === void 0) { replace = false; }
  109227. // Dispose existing light in replace mode.
  109228. if (replace) {
  109229. if (this.lights) {
  109230. for (var i = 0; i < this.lights.length; i++) {
  109231. this.lights[i].dispose();
  109232. }
  109233. }
  109234. }
  109235. // Light
  109236. if (this.lights.length === 0) {
  109237. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  109238. }
  109239. };
  109240. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  109241. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109242. if (replace === void 0) { replace = false; }
  109243. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109244. // Dispose existing camera in replace mode.
  109245. if (replace) {
  109246. if (this.activeCamera) {
  109247. this.activeCamera.dispose();
  109248. this.activeCamera = null;
  109249. }
  109250. }
  109251. // Camera
  109252. if (!this.activeCamera) {
  109253. var worldExtends = this.getWorldExtends();
  109254. var worldSize = worldExtends.max.subtract(worldExtends.min);
  109255. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  109256. var camera;
  109257. var radius = worldSize.length() * 1.5;
  109258. // empty scene scenario!
  109259. if (!isFinite(radius)) {
  109260. radius = 1;
  109261. worldCenter.copyFromFloats(0, 0, 0);
  109262. }
  109263. if (createArcRotateCamera) {
  109264. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  109265. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  109266. arcRotateCamera.wheelPrecision = 100 / radius;
  109267. camera = arcRotateCamera;
  109268. }
  109269. else {
  109270. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  109271. freeCamera.setTarget(worldCenter);
  109272. camera = freeCamera;
  109273. }
  109274. camera.minZ = radius * 0.01;
  109275. camera.maxZ = radius * 1000;
  109276. camera.speed = radius * 0.2;
  109277. this.activeCamera = camera;
  109278. var canvas = this.getEngine().getRenderingCanvas();
  109279. if (attachCameraControls && canvas) {
  109280. camera.attachControl(canvas);
  109281. }
  109282. }
  109283. };
  109284. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  109285. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109286. if (replace === void 0) { replace = false; }
  109287. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109288. this.createDefaultLight(replace);
  109289. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  109290. };
  109291. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  109292. if (pbr === void 0) { pbr = false; }
  109293. if (scale === void 0) { scale = 1000; }
  109294. if (blur === void 0) { blur = 0; }
  109295. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  109296. if (!environmentTexture) {
  109297. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  109298. return null;
  109299. }
  109300. if (setGlobalEnvTexture) {
  109301. if (environmentTexture) {
  109302. this.environmentTexture = environmentTexture;
  109303. }
  109304. }
  109305. // Skybox
  109306. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  109307. if (pbr) {
  109308. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  109309. hdrSkyboxMaterial.backFaceCulling = false;
  109310. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  109311. if (hdrSkyboxMaterial.reflectionTexture) {
  109312. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109313. }
  109314. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  109315. hdrSkyboxMaterial.disableLighting = true;
  109316. hdrSkyboxMaterial.twoSidedLighting = true;
  109317. hdrSkybox.infiniteDistance = true;
  109318. hdrSkybox.material = hdrSkyboxMaterial;
  109319. }
  109320. else {
  109321. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  109322. skyboxMaterial.backFaceCulling = false;
  109323. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  109324. if (skyboxMaterial.reflectionTexture) {
  109325. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109326. }
  109327. skyboxMaterial.disableLighting = true;
  109328. hdrSkybox.infiniteDistance = true;
  109329. hdrSkybox.material = skyboxMaterial;
  109330. }
  109331. return hdrSkybox;
  109332. };
  109333. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  109334. if (BABYLON.EnvironmentHelper) {
  109335. return new BABYLON.EnvironmentHelper(options, this);
  109336. }
  109337. return null;
  109338. };
  109339. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  109340. if (webVROptions === void 0) { webVROptions = {}; }
  109341. return new BABYLON.VRExperienceHelper(this, webVROptions);
  109342. };
  109343. })(BABYLON || (BABYLON = {}));
  109344. //# sourceMappingURL=babylon.sceneHelpers.js.map
  109345. 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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\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\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=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;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\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.rgb*=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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\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#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,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() {\nfloat newAge=age+timeDelta;\n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*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(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-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;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}","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}","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;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\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;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\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\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\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}","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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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\nvec4 reflectionColor=vec4(1.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=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.rgb*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.rgb,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","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  109346. 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\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\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};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(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;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(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 REFLECTION\nuniform mat4 reflectionMatrix;\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=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\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\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\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\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>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}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(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#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(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#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif 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 vec4 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 vec4 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 vec4 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#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\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};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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;\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;\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}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\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};","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};"};